path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
temp.js
SerenityTn/knowledge_map
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { constructor(){ super(); this.state = { user: {firstName: "Serenity", lastName: "Amamou"} } } hello(user){ return "Good morning " + user.firstName + " " + user.lastName; } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> {this.hello(this.state.user)} </p> </div> ); } } export default App;
lib/shared/routes.js
Josecc/spotify-hipster
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _reactRouter = require("react-router"); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _componentsSpotify = require("./components/Spotify"); var _componentsSpotify2 = _interopRequireDefault(_componentsSpotify); exports["default"] = _react2["default"].createElement(_reactRouter.Route, { handler: _componentsSpotify2["default"], path: "/" }); module.exports = exports["default"];
src/templates/blog-post.js
huw/nu
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import { Link, graphql } from 'gatsby'; import styled from 'styled-components'; import Layout from '../components/layout'; import { rhythm, scale } from '../utils/typography'; import 'katex/dist/katex.min.css'; const Date = styled(Link)` ${scale(-1 / 5)}; display: block; margin-bottom: ${rhythm(1)}; margin-top: ${rhythm(-1)}; text-decoration: none; color: inherit; `; const NavigationLink = styled(Link)` text-decoration: none; color: inherit; font-weight: 600; `; const Navigation = styled.ul` display: flex; flex-wrap: wrap; justify-content: space-between; list-style: none; padding: 0; margin-left: 0; `; const BlogPostTemplate = (props) => { const { data: { markdownRemark: post, site: { siteMetadata: { title: siteTitle }, }, }, pageContext: { previous, next }, location, } = props; return ( <Layout> <div> <Helmet title={`${post.frontmatter.title} • ${siteTitle}`} /> <h1> {post.frontmatter.title} </h1> <Date to={location.pathname}> <time dateTime={post.frontmatter.date}> {post.frontmatter.date} </time> </Date> <div dangerouslySetInnerHTML={{ __html: post.html }} /> <Navigation> {previous && ( <li> <NavigationLink to={previous.fields.slug} rel="prev"> {'← '} {previous.frontmatter.title} </NavigationLink> </li> )} {next && ( <li> <NavigationLink to={next.fields.slug} rel="next"> {next.frontmatter.title} {' →'} </NavigationLink> </li> )} </Navigation> </div> </Layout> ); }; const OtherArticle = PropTypes.shape({ frontmatter: PropTypes.shape({ title: PropTypes.string.isRequired, }).isRequired, fields: PropTypes.shape({ slug: PropTypes.string.isRequired, }).isRequired, }); BlogPostTemplate.propTypes = { data: PropTypes.shape({ markdownRemark: PropTypes.shape({ frontmatter: PropTypes.shape({ title: PropTypes.string.isRequired, date: PropTypes.string.isRequired, }).isRequired, html: PropTypes.node.isRequired, }).isRequired, }).isRequired, pageContext: PropTypes.shape({ previous: OtherArticle, next: OtherArticle, }).isRequired, location: PropTypes.shape({ pathname: PropTypes.string.isRequired, }).isRequired, }; export default BlogPostTemplate; export const pageQuery = graphql` query BlogPostBySlug($slug: String!) { site { siteMetadata { title author } } markdownRemark(fields: { slug: { eq: $slug } }) { id html frontmatter { title date(formatString: "D MMMM, YYYY") } } } `;
src/components/Book.js
karaken12/ysfbc-web
import React from 'react'; import {Link} from "react-router-dom"; function Book(props) { const type = props.type; const meeting = props.meeting; const isCurrent = props.isCurrent; const book = meeting[type]; return ( <section className="book"> {isCurrent && CurrentHeader(type)} {Header(book)} {BookImage(book)} {book['store-links'] && StoreLinks(book)} {AdditionalInfo(book)} {MeetingName(book)} {isCurrent && PreviousLink(type)} </section> ); } function CurrentHeader(type) { switch (type) { case 'book': return <h1>Current book</h1>; case 'short': return <h1>Current short story</h1>; case 'film': return <h1>Current film</h1>; default: return; } } function Header(props) { return <header> <h2>{props.title}</h2> {props.author && ( <p>by {props.author}</p>) } </header>; } function BookImage(props) { return <div className="bookimg"> <img src={"https://www-assets.yorkscifibookclub.co.uk" + props["img-url"]} alt={props.title}/> </div>; } function StoreLinks(props) { return ( <ul className="affiliate-links"> {props['store-links'].map((link) => <li key={link.url}><a className={link.class} href={link.url}>{link.name}</a></li> )} </ul> ); } function AdditionalInfo(props) { return ( <ul className="info-links"> {props['info-links'].map((link) => <li key={link.url}><a className={link.class} href={link.url}>{link.name}</a></li> )} </ul> ); } function MeetingName(props) { return <p className="meeting">{props.meeting_for}</p>; } function PreviousLink(type) { switch (type) { case 'book': return ( <div className="prevbooks"><Link to="/books">Previous books</Link></div> ); case 'short': return ( <div className="prevshorts"><Link to="/shorts">Previous short stories</Link></div> ); case 'film': return ( <div className="prevfilms"><Link to="/films">Previous films</Link></div> ); default: return; } } export default Book;
frontend/components/content-selector/content-selector.js
apostolidhs/wiregoose
import mapValues from 'lodash/mapValues'; import uniqBy from 'lodash/uniqBy'; import keys from 'lodash/keys'; import map from 'lodash/map'; import capitalize from 'lodash/capitalize'; import React from 'react'; import PropTypes from 'prop-types'; import CSSModules from 'react-css-modules'; import Panel from 'react-bootstrap/lib/Panel'; import Row from 'react-bootstrap/lib/Row'; import Col from 'react-bootstrap/lib/Col'; import Button from 'react-bootstrap/lib/Button'; import {CATEGORIES} from '../../../config-public.js'; import Loader from '../../components/loader/loader.js'; import * as WiregooseApi from '../../components/services/wiregoose-api.js'; import BrowserLanguageDetection from '../../components/utilities/browser-language-detection.js'; import timeout from '../../components/utilities/timeout.js'; import tr from '../localization/localization.js'; import ArticlePlaceholderImage from '../article-box/article-placeholder-image.js'; import CategoryImages from '../category/images.js'; import styles from './content-selector.less'; @CSSModules(styles, { allowMultiple: true, }) export default class ContentSelector extends React.Component { static propTypes = { onCategoryClick: PropTypes.func.isRequired, onProviderClick: PropTypes.func.isRequired, onCategoryByProviderClick: PropTypes.func.isRequired } state = {} componentDidMount() { const lang = BrowserLanguageDetection(); this.refs.registrationFetches.promise = timeout(() => {}, 200) .then(() => WiregooseApi.rssFeed.registrationFetches(lang, {cache: true})) .then(resp => timeout(() => resp, 0)) .then(resp => { const categoriesPerProviders = mapValues( resp.data.data, regs => uniqBy(regs, reg => reg.category) ); const providers = keys(categoriesPerProviders); this.setState({providers, categoriesPerProviders}); }); } render() { const { onCategoryClick, onProviderClick, onCategoryByProviderClick } = this.props; return ( <div className="content-selector" > <Panel> <h3 data-sticky-head={tr.categories}>{tr.categories}</h3> <Row> {map(CATEGORIES, cat => <Col key={cat} className={'w-mb-14'} xs={6} sm={4} md={3} lg={2} > <a href="#" styleName="link" className="btn btn-default" title={tr[cat]} onClick={evt => { evt.preventDefault(); onCategoryClick(cat); }} > <CategoryImages name={cat} /> {tr[cat]} </a> </Col> )} </Row> <h3 data-sticky-head={tr.providers}>{tr.providers}</h3> <Loader ref="registrationFetches"> <Row> {map(this.state.providers, p => <Col key={p} className={'w-mb-14'} xs={6} sm={4} md={3} lg={3} > <a href="#" title={capitalize(p)} styleName="link" className="btn btn-default" onClick={evt => { evt.preventDefault(); onProviderClick(p); }} > {capitalize(p)} </a> </Col> )} </Row> </Loader> <h3 data-sticky-head={tr.categoriesPerProvider} >{tr.categoriesPerProvider}</h3> <Loader ref="registrationFetches"> {map(this.state.categoriesPerProviders, (cats, provider) => <div key={provider}> <a href="#" title={capitalize(provider)} className="blind-link" onClick={evt => { evt.preventDefault(); onProviderClick(provider); }} > <h4>{capitalize(provider)}</h4> </a> <Row> {map(cats, ({category, total, _id}, idx) => <Col key={idx} className={'w-mb-14'} xs={6} sm={4} md={3} lg={2} > <a href="#" title={tr[category]} styleName="link" className="btn btn-default" onClick={evt => { evt.preventDefault(); const lang = BrowserLanguageDetection(); const link = [provider, category, lang, _id].join('-'); onCategoryByProviderClick(link); }} > <CategoryImages name={category} /> {tr[category]} </a> </Col> )} </Row> </div>)} </Loader> </Panel> </div> ); } }
src/components/Page.js
weaintplastic/react-sketchapp
/* @flow */ import React from 'react'; import PropTypes from 'prop-types'; const propTypes = { name: PropTypes.string, children: PropTypes.node, }; class Page extends React.Component { static defaultProps = { name: 'Page 1', }; render() { const { name, children } = this.props; const _name = name === 'Symbols' ? 'Symbols (renamed to avoid conflict)' : name; return <page name={_name}>{children}</page>; } } Page.propTypes = propTypes; module.exports = Page;
ajax/libs/material-ui/4.12.1/es/Tooltip/Tooltip.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { deepmerge, elementAcceptingRef } from '@material-ui/utils'; import { alpha } from '../styles/colorManipulator'; import withStyles from '../styles/withStyles'; import capitalize from '../utils/capitalize'; import Grow from '../Grow'; import Popper from '../Popper'; import useForkRef from '../utils/useForkRef'; import useId from '../utils/unstable_useId'; import setRef from '../utils/setRef'; import useIsFocusVisible from '../utils/useIsFocusVisible'; import useControlled from '../utils/useControlled'; import useTheme from '../styles/useTheme'; function round(value) { return Math.round(value * 1e5) / 1e5; } function arrowGenerator() { return { '&[x-placement*="bottom"] $arrow': { top: 0, left: 0, marginTop: '-0.71em', marginLeft: 4, marginRight: 4, '&::before': { transformOrigin: '0 100%' } }, '&[x-placement*="top"] $arrow': { bottom: 0, left: 0, marginBottom: '-0.71em', marginLeft: 4, marginRight: 4, '&::before': { transformOrigin: '100% 0' } }, '&[x-placement*="right"] $arrow': { left: 0, marginLeft: '-0.71em', height: '1em', width: '0.71em', marginTop: 4, marginBottom: 4, '&::before': { transformOrigin: '100% 100%' } }, '&[x-placement*="left"] $arrow': { right: 0, marginRight: '-0.71em', height: '1em', width: '0.71em', marginTop: 4, marginBottom: 4, '&::before': { transformOrigin: '0 0' } } }; } export const styles = theme => ({ /* Styles applied to the Popper component. */ popper: { zIndex: theme.zIndex.tooltip, pointerEvents: 'none' // disable jss-rtl plugin }, /* Styles applied to the Popper component if `interactive={true}`. */ popperInteractive: { pointerEvents: 'auto' }, /* Styles applied to the Popper component if `arrow={true}`. */ popperArrow: arrowGenerator(), /* Styles applied to the tooltip (label wrapper) element. */ tooltip: { backgroundColor: alpha(theme.palette.grey[700], 0.9), borderRadius: theme.shape.borderRadius, color: theme.palette.common.white, fontFamily: theme.typography.fontFamily, padding: '4px 8px', fontSize: theme.typography.pxToRem(10), lineHeight: `${round(14 / 10)}em`, maxWidth: 300, wordWrap: 'break-word', fontWeight: theme.typography.fontWeightMedium }, /* Styles applied to the tooltip (label wrapper) element if `arrow={true}`. */ tooltipArrow: { position: 'relative', margin: '0' }, /* Styles applied to the arrow element. */ arrow: { overflow: 'hidden', position: 'absolute', width: '1em', height: '0.71em' /* = width / sqrt(2) = (length of the hypotenuse) */ , boxSizing: 'border-box', color: alpha(theme.palette.grey[700], 0.9), '&::before': { content: '""', margin: 'auto', display: 'block', width: '100%', height: '100%', backgroundColor: 'currentColor', transform: 'rotate(45deg)' } }, /* Styles applied to the tooltip (label wrapper) element if the tooltip is opened by touch. */ touch: { padding: '8px 16px', fontSize: theme.typography.pxToRem(14), lineHeight: `${round(16 / 14)}em`, fontWeight: theme.typography.fontWeightRegular }, /* Styles applied to the tooltip (label wrapper) element if `placement` contains "left". */ tooltipPlacementLeft: { transformOrigin: 'right center', margin: '0 24px ', [theme.breakpoints.up('sm')]: { margin: '0 14px' } }, /* Styles applied to the tooltip (label wrapper) element if `placement` contains "right". */ tooltipPlacementRight: { transformOrigin: 'left center', margin: '0 24px', [theme.breakpoints.up('sm')]: { margin: '0 14px' } }, /* Styles applied to the tooltip (label wrapper) element if `placement` contains "top". */ tooltipPlacementTop: { transformOrigin: 'center bottom', margin: '24px 0', [theme.breakpoints.up('sm')]: { margin: '14px 0' } }, /* Styles applied to the tooltip (label wrapper) element if `placement` contains "bottom". */ tooltipPlacementBottom: { transformOrigin: 'center top', margin: '24px 0', [theme.breakpoints.up('sm')]: { margin: '14px 0' } } }); let hystersisOpen = false; let hystersisTimer = null; export function testReset() { hystersisOpen = false; clearTimeout(hystersisTimer); } const Tooltip = /*#__PURE__*/React.forwardRef(function Tooltip(props, ref) { const { arrow = false, children, classes, disableFocusListener = false, disableHoverListener = false, disableTouchListener = false, enterDelay = 100, enterNextDelay = 0, enterTouchDelay = 700, id: idProp, interactive = false, leaveDelay = 0, leaveTouchDelay = 1500, onClose, onOpen, open: openProp, placement = 'bottom', PopperComponent = Popper, PopperProps, title, TransitionComponent = Grow, TransitionProps } = props, other = _objectWithoutPropertiesLoose(props, ["arrow", "children", "classes", "disableFocusListener", "disableHoverListener", "disableTouchListener", "enterDelay", "enterNextDelay", "enterTouchDelay", "id", "interactive", "leaveDelay", "leaveTouchDelay", "onClose", "onOpen", "open", "placement", "PopperComponent", "PopperProps", "title", "TransitionComponent", "TransitionProps"]); const theme = useTheme(); const [childNode, setChildNode] = React.useState(); const [arrowRef, setArrowRef] = React.useState(null); const ignoreNonTouchEvents = React.useRef(false); const closeTimer = React.useRef(); const enterTimer = React.useRef(); const leaveTimer = React.useRef(); const touchTimer = React.useRef(); const [openState, setOpenState] = useControlled({ controlled: openProp, default: false, name: 'Tooltip', state: 'open' }); let open = openState; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks const { current: isControlled } = React.useRef(openProp !== undefined); // eslint-disable-next-line react-hooks/rules-of-hooks React.useEffect(() => { if (childNode && childNode.disabled && !isControlled && title !== '' && childNode.tagName.toLowerCase() === 'button') { console.error(['Material-UI: You are providing a disabled `button` child to the Tooltip component.', 'A disabled element does not fire events.', "Tooltip needs to listen to the child element's events to display the title.", '', 'Add a simple wrapper element, such as a `span`.'].join('\n')); } }, [title, childNode, isControlled]); } const id = useId(idProp); React.useEffect(() => { return () => { clearTimeout(closeTimer.current); clearTimeout(enterTimer.current); clearTimeout(leaveTimer.current); clearTimeout(touchTimer.current); }; }, []); const handleOpen = event => { clearTimeout(hystersisTimer); hystersisOpen = true; // The mouseover event will trigger for every nested element in the tooltip. // We can skip rerendering when the tooltip is already open. // We are using the mouseover event instead of the mouseenter event to fix a hide/show issue. setOpenState(true); if (onOpen) { onOpen(event); } }; const handleEnter = (forward = true) => event => { const childrenProps = children.props; if (event.type === 'mouseover' && childrenProps.onMouseOver && forward) { childrenProps.onMouseOver(event); } if (ignoreNonTouchEvents.current && event.type !== 'touchstart') { return; } // Remove the title ahead of time. // We don't want to wait for the next render commit. // We would risk displaying two tooltips at the same time (native + this one). if (childNode) { childNode.removeAttribute('title'); } clearTimeout(enterTimer.current); clearTimeout(leaveTimer.current); if (enterDelay || hystersisOpen && enterNextDelay) { event.persist(); enterTimer.current = setTimeout(() => { handleOpen(event); }, hystersisOpen ? enterNextDelay : enterDelay); } else { handleOpen(event); } }; const { isFocusVisible, onBlurVisible, ref: focusVisibleRef } = useIsFocusVisible(); const [childIsFocusVisible, setChildIsFocusVisible] = React.useState(false); const handleBlur = () => { if (childIsFocusVisible) { setChildIsFocusVisible(false); onBlurVisible(); } }; const handleFocus = (forward = true) => event => { // Workaround for https://github.com/facebook/react/issues/7769 // The autoFocus of React might trigger the event before the componentDidMount. // We need to account for this eventuality. if (!childNode) { setChildNode(event.currentTarget); } if (isFocusVisible(event)) { setChildIsFocusVisible(true); handleEnter()(event); } const childrenProps = children.props; if (childrenProps.onFocus && forward) { childrenProps.onFocus(event); } }; const handleClose = event => { clearTimeout(hystersisTimer); hystersisTimer = setTimeout(() => { hystersisOpen = false; }, 800 + leaveDelay); setOpenState(false); if (onClose) { onClose(event); } clearTimeout(closeTimer.current); closeTimer.current = setTimeout(() => { ignoreNonTouchEvents.current = false; }, theme.transitions.duration.shortest); }; const handleLeave = (forward = true) => event => { const childrenProps = children.props; if (event.type === 'blur') { if (childrenProps.onBlur && forward) { childrenProps.onBlur(event); } handleBlur(); } if (event.type === 'mouseleave' && childrenProps.onMouseLeave && event.currentTarget === childNode) { childrenProps.onMouseLeave(event); } clearTimeout(enterTimer.current); clearTimeout(leaveTimer.current); event.persist(); leaveTimer.current = setTimeout(() => { handleClose(event); }, leaveDelay); }; const detectTouchStart = event => { ignoreNonTouchEvents.current = true; const childrenProps = children.props; if (childrenProps.onTouchStart) { childrenProps.onTouchStart(event); } }; const handleTouchStart = event => { detectTouchStart(event); clearTimeout(leaveTimer.current); clearTimeout(closeTimer.current); clearTimeout(touchTimer.current); event.persist(); touchTimer.current = setTimeout(() => { handleEnter()(event); }, enterTouchDelay); }; const handleTouchEnd = event => { if (children.props.onTouchEnd) { children.props.onTouchEnd(event); } clearTimeout(touchTimer.current); clearTimeout(leaveTimer.current); event.persist(); leaveTimer.current = setTimeout(() => { handleClose(event); }, leaveTouchDelay); }; const handleUseRef = useForkRef(setChildNode, ref); const handleFocusRef = useForkRef(focusVisibleRef, handleUseRef); // can be removed once we drop support for non ref forwarding class components const handleOwnRef = React.useCallback(instance => { // #StrictMode ready setRef(handleFocusRef, ReactDOM.findDOMNode(instance)); }, [handleFocusRef]); const handleRef = useForkRef(children.ref, handleOwnRef); // There is no point in displaying an empty tooltip. if (title === '') { open = false; } // For accessibility and SEO concerns, we render the title to the DOM node when // the tooltip is hidden. However, we have made a tradeoff when // `disableHoverListener` is set. This title logic is disabled. // It's allowing us to keep the implementation size minimal. // We are open to change the tradeoff. const shouldShowNativeTitle = !open && !disableHoverListener; const childrenProps = _extends({ 'aria-describedby': open ? id : null, title: shouldShowNativeTitle && typeof title === 'string' ? title : null }, other, children.props, { className: clsx(other.className, children.props.className), onTouchStart: detectTouchStart, ref: handleRef }); const interactiveWrapperListeners = {}; if (!disableTouchListener) { childrenProps.onTouchStart = handleTouchStart; childrenProps.onTouchEnd = handleTouchEnd; } if (!disableHoverListener) { childrenProps.onMouseOver = handleEnter(); childrenProps.onMouseLeave = handleLeave(); if (interactive) { interactiveWrapperListeners.onMouseOver = handleEnter(false); interactiveWrapperListeners.onMouseLeave = handleLeave(false); } } if (!disableFocusListener) { childrenProps.onFocus = handleFocus(); childrenProps.onBlur = handleLeave(); if (interactive) { interactiveWrapperListeners.onFocus = handleFocus(false); interactiveWrapperListeners.onBlur = handleLeave(false); } } if (process.env.NODE_ENV !== 'production') { if (children.props.title) { console.error(['Material-UI: You have provided a `title` prop to the child of <Tooltip />.', `Remove this title prop \`${children.props.title}\` or the Tooltip component.`].join('\n')); } } const mergedPopperProps = React.useMemo(() => { return deepmerge({ popperOptions: { modifiers: { arrow: { enabled: Boolean(arrowRef), element: arrowRef } } } }, PopperProps); }, [arrowRef, PopperProps]); return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.cloneElement(children, childrenProps), /*#__PURE__*/React.createElement(PopperComponent, _extends({ className: clsx(classes.popper, interactive && classes.popperInteractive, arrow && classes.popperArrow), placement: placement, anchorEl: childNode, open: childNode ? open : false, id: childrenProps['aria-describedby'], transition: true }, interactiveWrapperListeners, mergedPopperProps), ({ placement: placementInner, TransitionProps: TransitionPropsInner }) => /*#__PURE__*/React.createElement(TransitionComponent, _extends({ timeout: theme.transitions.duration.shorter }, TransitionPropsInner, TransitionProps), /*#__PURE__*/React.createElement("div", { className: clsx(classes.tooltip, classes[`tooltipPlacement${capitalize(placementInner.split('-')[0])}`], ignoreNonTouchEvents.current && classes.touch, arrow && classes.tooltipArrow) }, title, arrow ? /*#__PURE__*/React.createElement("span", { className: classes.arrow, ref: setArrowRef }) : null)))); }); process.env.NODE_ENV !== "production" ? Tooltip.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, adds an arrow to the tooltip. */ arrow: PropTypes.bool, /** * Tooltip reference element. */ children: elementAcceptingRef.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * Do not respond to focus events. */ disableFocusListener: PropTypes.bool, /** * Do not respond to hover events. */ disableHoverListener: PropTypes.bool, /** * Do not respond to long press touch events. */ disableTouchListener: PropTypes.bool, /** * The number of milliseconds to wait before showing the tooltip. * This prop won't impact the enter touch delay (`enterTouchDelay`). */ enterDelay: PropTypes.number, /** * The number of milliseconds to wait before showing the tooltip when one was already recently opened. */ enterNextDelay: PropTypes.number, /** * The number of milliseconds a user must touch the element before showing the tooltip. */ enterTouchDelay: PropTypes.number, /** * This prop is used to help implement the accessibility logic. * If you don't provide this prop. It falls back to a randomly generated id. */ id: PropTypes.string, /** * Makes a tooltip interactive, i.e. will not close when the user * hovers over the tooltip before the `leaveDelay` is expired. */ interactive: PropTypes.bool, /** * The number of milliseconds to wait before hiding the tooltip. * This prop won't impact the leave touch delay (`leaveTouchDelay`). */ leaveDelay: PropTypes.number, /** * The number of milliseconds after the user stops touching an element before hiding the tooltip. */ leaveTouchDelay: PropTypes.number, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. */ onClose: PropTypes.func, /** * Callback fired when the component requests to be open. * * @param {object} event The event source of the callback. */ onOpen: PropTypes.func, /** * If `true`, the tooltip is shown. */ open: PropTypes.bool, /** * Tooltip placement. */ placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']), /** * The component used for the popper. */ PopperComponent: PropTypes.elementType, /** * Props applied to the [`Popper`](/api/popper/) element. */ PopperProps: PropTypes.object, /** * Tooltip title. Zero-length titles string are never displayed. */ title: PropTypes /* @typescript-to-proptypes-ignore */ .node.isRequired, /** * The component used for the transition. * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component. */ TransitionComponent: PropTypes.elementType, /** * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element. */ TransitionProps: PropTypes.object } : void 0; export default withStyles(styles, { name: 'MuiTooltip', flip: false })(Tooltip);
src/svg-icons/image/texture.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTexture = (props) => ( <SvgIcon {...props}> <path d="M19.51 3.08L3.08 19.51c.09.34.27.65.51.9.25.24.56.42.9.51L20.93 4.49c-.19-.69-.73-1.23-1.42-1.41zM11.88 3L3 11.88v2.83L14.71 3h-2.83zM5 3c-1.1 0-2 .9-2 2v2l4-4H5zm14 18c.55 0 1.05-.22 1.41-.59.37-.36.59-.86.59-1.41v-2l-4 4h2zm-9.71 0h2.83L21 12.12V9.29L9.29 21z"/> </SvgIcon> ); ImageTexture = pure(ImageTexture); ImageTexture.displayName = 'ImageTexture'; ImageTexture.muiName = 'SvgIcon'; export default ImageTexture;
Realization/frontend/czechidm-core/src/components/advanced/ValidationMessage/ValidationMessage.js
bcvsolutions/CzechIdMng
import PropTypes from 'prop-types'; import React from 'react'; import _ from 'lodash'; // import * as Basic from '../../basic'; import DateValue from '../DateValue/DateValue'; /** * Parameters in errors. Contain names of not success policies * @type {String} */ const PASSWORD_POLICIES_NAMES = 'policiesNames'; /** * Enchanced control, minimal rules to fulfill. * Value of parameter MIN_RULES_TO_FULFILL is map with rules * @type {String} */ const MIN_RULES_TO_FULFILL = 'minRulesToFulfill'; /** * Enchanced control, count with minimal rules to fulfill * @type {String} */ const MIN_RULES_TO_FULFILL_COUNT = 'minRulesToFulfillCount'; /** * Special character base for each required policies * @type {String} */ const SPECIAL_CHARACTER_BASE = 'specialCharacterBase'; /** * Forbidden character base for each required policies * @type {String} */ const FORBIDDEN_CHARACTER_BASE = 'forbiddenCharacterBase'; /** * Forbidden character at the beginning of passwords base for each required policies * @type {String} */ const FORBIDDEN_BEGIN_CHARACTER_BASE = 'forbiddenBeginCharacterBase'; /** * Forbidden character at the end of passwords base for each required policies * @type {String} */ const FORBIDDEN_END_CHARACTER_BASE = 'forbiddenEndCharacterBase'; /** * Merge similar password lines * @type {String} */ const PWD_SIMILAR = 'passwordSimilarPreValidate'; /** * Error message with date, date is format by local * @type {String} */ const DATE = 'date'; /** * Array with all validation message parameters, when you add some validation warrning into BE, * you also must add this parameters into this arrray. * @type {Array} */ const VALIDATION_WARNINGS = ['minLength', 'maxLength', 'minUpperChar', 'minLowerChar', 'minNumber', 'minSpecialChar', 'prohibited', 'beginProhibited', 'endProhibited', 'weakPass', 'minRulesToFulfill', 'minRulesToFulfillCount', 'policiesNames', 'passwordSimilarUsername', 'passwordSimilarEmail', 'passwordSimilarFirstName', 'passwordSimilarLastName', 'passwordSimilarTitlesAfter', 'passwordSimilarTitlesBefore', 'passwordSimilarExternalCode', 'maxHistorySimilar', 'passwordSimilarUsernamePreValidate', 'passwordSimilarEmailPreValidate', 'passwordSimilarFirstNamePreValidate', 'passwordSimilarLastNamePreValidate', 'passwordSimilarTitlesAfterPreValidate', 'passwordSimilarTitlesBeforePreValidate', 'passwordSimilarExternalCodePreValidate']; /** * @author Ondřej Kopr * @author Patrik Stloukal */ export default class ValidationMessage extends Basic.AbstractFormComponent { componentDidMount() { const { error, validationDefinition } = this.props; this._prepareValidationMessage(error, validationDefinition); } _showCharacterBase(parameter, type) { const rules = []; const all = []; all.push(this.i18n('content.passwordPolicies.validation.' + type + '.list')); for (const ruleKey in parameter) { if (parameter.hasOwnProperty(ruleKey)) { rules.push(_.size(parameter) === 1 ? parameter[ruleKey] : ruleKey + ': ' + parameter[ruleKey]); } } all.push(this._pointList(rules)); return all; } /** * Method prepare error from password validation. * Only validation message is required, other will be skiped. */ _prepareValidationMessage(error) { if (!error || !error.parameters) { return null; } // For pre validate it shows as info (blue) const levelWarning = `warning`; const levelDanger = `danger`; const validationMessage = []; // iterate over all parameters in error for (const key in error.parameters) { // error prameters must contain key and VALIDATION_WARNINGS must also contain key if (error.parameters.hasOwnProperty(key) && _.indexOf(VALIDATION_WARNINGS, key) !== -1) { // enchanced control special message, minimal rules to fulfill if (key === MIN_RULES_TO_FULFILL) { // fill rules with not required messages const rules = []; rules.push(this.i18n('content.passwordPolicies.validation.' + MIN_RULES_TO_FULFILL, {'count': error.parameters[MIN_RULES_TO_FULFILL_COUNT]} )); const rule = []; for (const ruleKey in error.parameters[key]) { if (error.parameters[key].hasOwnProperty(ruleKey)) { rule.push(this.i18n('content.passwordPolicies.validation.' + ruleKey) + error.parameters[key][ruleKey]); } } rules.push(this._pointList(rule)); validationMessage.push( <Basic.Alert level={levelWarning} className="no-margin"> <span> {rules} </span> </Basic.Alert>); } else if (key !== PASSWORD_POLICIES_NAMES) { // set all attributes as parameter zero // validation message with date if (key === DATE) { validationMessage.push( <Basic.Alert level={levelWarning} className="no-margin"> {this.i18n('content.passwordPolicies.validation.' + key, { 0: <DateValue value={error.parameters[key]}/> } )} </Basic.Alert> ); } else { // other validation messages validationMessage.push( <Basic.Alert level={levelWarning} className="no-margin"> {this.i18n('content.passwordPolicies.validation.' + key, { 0: error.parameters[key] })} </Basic.Alert> ); } } } } // first message is password policies names, with danger class if (error.parameters.hasOwnProperty(PASSWORD_POLICIES_NAMES)) { validationMessage.unshift( <Basic.Alert level={levelDanger} className="no-margin"> {this.i18n('content.passwordPolicies.validation.' + PASSWORD_POLICIES_NAMES) + error.parameters[PASSWORD_POLICIES_NAMES]} </Basic.Alert> ); } // return validationMessage; } _pointList(field, secondFiled) { const listItems = field.map((number) => <li>{number}</li> ); let secondListItems; if (secondFiled !== undefined) { secondListItems = secondFiled.map((number) => <li>{number}</li> ); } return ( <ul style={{ paddingLeft: 20 }}>{listItems} {secondListItems}</ul> ); } _preparePreValidationMessage(error) { if (!error || !error.parameters) { return null; } const validationMessage = []; const lines = []; // every one of these rules must be met const rules = []; // one of two following rules must be met.... const charBase = []; // for shown special character base const forbiddenBase = []; // for shown forbidden character base const similar = []; // for merging pwd must not be similar to name, mail, username const bases = []; // iterate over all parameters in error for (const key in error.parameters) { // error prameters must contain key and VALIDATION_WARNINGS must also contain key if (error.parameters.hasOwnProperty(key) && _.indexOf(VALIDATION_WARNINGS, key) !== -1) { // enchanced control special message, minimal rules to fulfill if (key === MIN_RULES_TO_FULFILL) { // fill rules with not required messages rules.push(this.i18n('content.passwordPolicies.validation.' + MIN_RULES_TO_FULFILL, {'count': error.parameters[MIN_RULES_TO_FULFILL_COUNT]} )); const rule = []; for (const ruleKey in error.parameters[key]) { if (error.parameters[key].hasOwnProperty(ruleKey)) { rule.push(this.i18n('content.passwordPolicies.validation.' + ruleKey) + error.parameters[key][ruleKey]); } } rules.push(this._pointList(rule)); // to merge - pwd must not be similar to name, mail, username } else if (key === 'passwordSimilarUsernamePreValidate' || key === 'passwordSimilarEmailPreValidate' || key === 'passwordSimilarFirstNamePreValidate' || key === 'passwordSimilarLastNamePreValidate' || key === 'passwordSimilarTitlesBeforePreValidate' || key === 'passwordSimilarTitlesAfterPreValidate' || key === 'passwordSimilarExternalCodePreValidate') { similar.push(this.i18n('content.passwordPolicies.validation.' + key)); } else if ( key !== MIN_RULES_TO_FULFILL_COUNT ) { // other validation messages lines.push(this.i18n('content.passwordPolicies.validation.' + key, { 0: error.parameters[key] })); } } if (key === SPECIAL_CHARACTER_BASE) { if (_.size(error.parameters[key]) === 1) { for (const ruleKey in error.parameters[key]) { if (Object.prototype.hasOwnProperty.call(error.parameters[key], ruleKey)) { bases.push(this.i18n('content.passwordPolicies.validation.' + SPECIAL_CHARACTER_BASE + '.text') + error.parameters[key][ruleKey]); } } } else { charBase.push(this._showCharacterBase(error.parameters[key], SPECIAL_CHARACTER_BASE, validationMessage, `info`)); } } if (key === FORBIDDEN_CHARACTER_BASE) { if (_.size(error.parameters[key]) === 1) { for (const ruleKey in error.parameters[key]) { if (Object.prototype.hasOwnProperty.call(error.parameters[key], ruleKey)) { bases.push(this.i18n('content.passwordPolicies.validation.' + FORBIDDEN_CHARACTER_BASE + '.text') + error.parameters[key][ruleKey]); } } } else { forbiddenBase.push(this._showCharacterBase(error.parameters[key], FORBIDDEN_CHARACTER_BASE, validationMessage, `info`)); } } if (key === FORBIDDEN_BEGIN_CHARACTER_BASE) { if (_.size(error.parameters[key]) === 1) { for (const ruleKey in error.parameters[key]) { if (Object.prototype.hasOwnProperty.call(error.parameters[key], ruleKey)) { bases.push(this.i18n('content.passwordPolicies.validation.' + FORBIDDEN_BEGIN_CHARACTER_BASE + '.text') + error.parameters[key][ruleKey]); } } } else { forbiddenBase.push(this._showCharacterBase(error.parameters[key], FORBIDDEN_BEGIN_CHARACTER_BASE, validationMessage, `info`)); } } if (key === FORBIDDEN_END_CHARACTER_BASE) { if (_.size(error.parameters[key]) === 1) { for (const ruleKey in error.parameters[key]) { if (Object.prototype.hasOwnProperty.call(error.parameters[key], ruleKey)) { bases.push(this.i18n('content.passwordPolicies.validation.' + FORBIDDEN_END_CHARACTER_BASE + '.text') + error.parameters[key][ruleKey]); } } } else { forbiddenBase.push(this._showCharacterBase(error.parameters[key], FORBIDDEN_END_CHARACTER_BASE, validationMessage, `info`)); } } } if (similar.length > 0) { lines.push(this.i18n('content.passwordPolicies.validation.' + PWD_SIMILAR) + ' ' + similar.join(', ') + '.'); } const result = []; result.push(this._pointList(lines, bases)); result.push(rules); result.push(charBase); result.push(forbiddenBase); validationMessage.push( <span> { result } </span> ); return validationMessage; } _preparePreValidationComponent(errorMessage) { return ( <Basic.Alert style={{ margin: '15px 0' }}> <Basic.Popover ref="popover" trigger={['click']} value={ <Basic.Panel level="info"> <Basic.PanelHeader> {this.i18n('content.passwordPolicies.validation.passwordHintPreValidateHeader')} </Basic.PanelHeader> <Basic.PanelBody> {this._preparePreValidationMessage(errorMessage)} </Basic.PanelBody> </Basic.Panel> } className="abstract-entity-info-popover" placement="right"> { <a href="#" onClick={ (e) => e.preventDefault() } title={ this.i18n('content.passwordPolicies.validation.prevalidationLink.title') }> { this.i18n('content.passwordPolicies.validation.passwordHintPreValidate') } { this.i18n('content.passwordPolicies.validation.passwordHintPreValidatePwd') } </a> } </Basic.Popover> </Basic.Alert> ); } render() { const { rendered, error, validationDefinition } = this.props; if (!rendered || !error) { return null; } let validation; if (validationDefinition) { validation = this._preparePreValidationComponent(error); } else { validation = this._prepareValidationMessage(error); } return ( <div> {validation} </div> ); } } ValidationMessage.propTypes = { ...Basic.AbstractFormComponent.propTypes, error: PropTypes.object, validationDefinition: PropTypes.object }; ValidationMessage.defaultProps = { ...Basic.AbstractFormComponent.defaultProps };
src/server.js
chuntielin/yeoman_react_fullstack
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; const server = global.server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { /* eslint-disable no-console */ console.log('The server is running at http://localhost:' + server.get('port')); if (process.send) { process.send('online'); } });
ajax/libs/forerunnerdb/1.3.350/fdb-all.js
cdnjs/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), Grid = _dereq_('../lib/Grid'), Rest = _dereq_('../lib/Rest'), Odm = _dereq_('../lib/Odm'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":6,"../lib/Document":10,"../lib/Grid":11,"../lib/Highchart":12,"../lib/Odm":26,"../lib/Overview":29,"../lib/Persist":31,"../lib/Rest":35,"../lib/View":39,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":38}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof obj[sortType.key]; if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += obj[sortType.key]; } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Shared":37}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (!(index instanceof Array)) { // Convert the index object to an array of key val objects index = this.keys(index); } } return this.$super.call(this, index); }); BinaryTree.prototype.keys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return true; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._index.length; i++) { indexData = this._index[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return result; } } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._index.length; i++) { indexData = this._index[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._index[0].key]; }; BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (!this._data) { // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === -1) { // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === 1) { // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'key': resultArr.push(this._data); break; default: resultArr.push({ key: this._key, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Shared":37}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this._onChange(); this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value return new Path(query.substr(3, query.length - 3)).value(item)[0]; } return new Path(query).value(item)[0]; } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":8,"./IndexBinaryTree":13,"./IndexHashMap":14,"./KeyValueStore":15,"./Metrics":16,"./Overload":28,"./Path":30,"./ReactorIO":34,"./Shared":37}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":37}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } callback(); }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":16,"./Overload":28,"./Shared":37}],8:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":16,"./Overload":28,"./Shared":37}],10:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof Document * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function () { if (!this.isDropped()) { if (this._db && this._name) { if (this._db && this._db._document && this._db._document[this._name]) { this._state = 'dropped'; delete this._db._document[this._name]; delete this._data; this.emit('drop', this); return true; } } } else { return true; } return false; }; /** * Creates a new document instance. * @func document * @memberof Db * @param {String} documentName The name of the document to create. * @returns {*} */ Db.prototype.document = function (documentName) { if (documentName) { // Handle being passed an instance if (documentName instanceof FdbDocument) { if (documentName.state() !== 'droppped') { return documentName; } else { documentName = documentName.name(); } } this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this); return this._document[documentName]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":5,"./Shared":37}],11:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function () { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); delete this._selector; delete this._template; delete this._from; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener ); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { template: [ '<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">', '<input type="search" class="form-control gridFilterSearch" placeholder="Search...">', '<span class="input-group-btn">', '<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>', '</span>', '</li>', '<li role="presentation" class="divider"></li>', '<li role="presentation" data-val="$all">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox" checked>&nbsp;All', '</a>', '</li>', '<li role="presentation" class="divider"></li>', '{^{for options}}', '<li role="presentation" data-link="data-val{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":34,"./Shared":37,"./View":39}],12:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = { categories: [] }, seriesName, query, dataSearch, seriesValues, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } seriesData.push({ name: seriesName, data: seriesValues }); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self, arguments); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if(typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy ); self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":28,"./Shared":37}],13:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":30,"./Shared":37}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":30,"./Shared":37}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":37}],16:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":27,"./Shared":37}],17:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],18:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],19:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common; Common = { /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return Serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return Serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":28,"./Serialiser":36}],20:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":28}],22:[function(_dereq_,module,exports){ "use strict"; var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) { return true; } else if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; } return -1; } }; module.exports = Matching; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":28}],25:[function(_dereq_,module,exports){ "use strict"; var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection; Shared = _dereq_('./Shared'); var Odm = function () { this.init.apply(this, arguments); }; Odm.prototype.init = function (from, name) { var self = this; self.name(name); self._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; self.from(from); }; Shared.addModule('Odm', Odm); Shared.mixin(Odm.prototype, 'Mixin.Common'); Shared.mixin(Odm.prototype, 'Mixin.ChainReactor'); Shared.mixin(Odm.prototype, 'Mixin.Constants'); Shared.mixin(Odm.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Shared.synthesize(Odm.prototype, 'name'); Shared.synthesize(Odm.prototype, 'state'); Shared.synthesize(Odm.prototype, 'parent'); Shared.synthesize(Odm.prototype, 'query'); Shared.synthesize(Odm.prototype, 'from', function (val) { if (val !== undefined) { val.chain(this); val.on('drop', this._collectionDroppedWrap); } return this.$super(val); }); Odm.prototype._collectionDropped = function (collection) { this.drop(); }; Odm.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': //this._refresh(); break; default: break; } }; Odm.prototype.drop = function () { if (!this.isDropped()) { this.state('dropped'); this.emit('drop', this); if (this._from) { delete this._from._odm; } delete this._name; } return true; }; /** * Queries the current object and returns a result that can * also be queried in the same way. * @param {String} prop The property to delve into. * @param {Object=} query Optional query that limits the returned documents. * @returns {Odm} */ Odm.prototype.$ = function (prop, query) { var data, tmpQuery, tmpColl, tmpOdm; if (prop === this._from.primaryKey()) { // Query is against a specific PK id tmpQuery = {}; tmpQuery[prop] = query; data = this._from.find(tmpQuery, {$decouple: false}); tmpColl = new Collection(); tmpColl.setData(data, {$decouple: false}); tmpColl._linked = this._from._linked; } else { // Query is against an array of sub-documents tmpColl = new Collection(); data = this._from.find({}, {$decouple: false}); if (data[0] && data[0][prop]) { // Set the temp collection data to the array property tmpColl.setData(data[0][prop], {$decouple: false}); // Check if we need to filter this array further if (query) { data = tmpColl.find(query, {$decouple: false}); tmpColl.setData(data, {$decouple: false}); } } tmpColl._linked = this._from._linked; } tmpOdm = new Odm(tmpColl); tmpOdm.parent(this); tmpOdm.query(query); return tmpOdm; }; /** * Gets / sets a property on the current ODM document. * @param {String} prop The name of the property. * @param {*} val Optional value to set. * @returns {*} */ Odm.prototype.prop = function (prop, val) { var tmpQuery; if (prop !== undefined) { if (val !== undefined) { tmpQuery = {}; tmpQuery[prop] = val; return this._from.update({}, tmpQuery); } if (this._from._data[0]) { return this._from._data[0][prop]; } } return undefined; }; /** * Get the ODM instance for this collection. * @returns {Odm} */ Collection.prototype.odm = function (name) { if (!this._odm) { this._odm = new Odm(this, name); } return this._odm; }; Shared.finishModule('Odm'); module.exports = Odm; },{"./Collection":5,"./Shared":37}],27:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":30,"./Shared":37}],28:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],29:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } delete this._name; this.emit('drop', this); } return true; }; Db.prototype.overview = function (overviewName) { if (overviewName) { // Handle being passed an instance if (overviewName instanceof Overview) { return overviewName; } this._overview = this._overview || {}; this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this); return this._overview[overviewName]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":5,"./Document":10,"./Shared":37}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":37}],31:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { callback(false, val, {}); }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { callback(false, val, {}); }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '::' + this._name); this._db.persist.drop(this._db._name + '::' + this._name + '::metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.apply(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '::' + this._name, function () { self._db.persist.drop(self._db._name + '::' + self._name + '::metaData', callback); }); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } // Call the original method CollectionDrop.apply(this, callback); } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '::' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '::' + self._name + '::metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '::' + self._name, function (err, data, tableStats) { if (!err) { if (data) { self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '::' + self._name + '::metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Db.prototype.load = function (callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method obj[index].load(loadCallback); } } }; /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Db.prototype.save = function (callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method obj[index].save(saveCallback); } } }; Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":32,"./PersistCrypto":33,"./Shared":37,"async":40,"localforage":82}],32:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":37,"pako":84}],33:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":37,"crypto-js":49}],34:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactoreOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":37}],35:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), RestClient = _dereq_('rest'), mime = _dereq_('rest/interceptor/mime'), Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, Overload; var Rest = function () { this.init.apply(this, arguments); }; Rest.prototype.init = function (db) { this._endPoint = ''; this._client = RestClient.wrap(mime); }; /** * Convert a JSON object to url query parameter format. * @param {Object} obj The object to convert. * @returns {String} * @private */ Rest.prototype._params = function (obj) { var parts = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } } return parts.join('&'); }; Rest.prototype.get = function (path, data, callback) { var self= this, coll; path = path !== undefined ? path : ""; //console.log('Getting: ', this.endPoint() + path + '?' + this._params(data)); this._client({ method: 'get', path: this.endPoint() + path, params: data }).then(function (response) { if (response.entity && response.entity.error) { if (callback) { callback(response.entity.error, response.entity, response); } } else { // Check if we have a collection coll = self.collection(); if (coll) { // Upsert the records into the collection coll.upsert(response.entity); } if (callback) { callback(false, response.entity, response); } } }, function(response) { if (callback) { callback(true, response.entity, response); } }); }; Rest.prototype.post = function (path, data, callback) { this._client({ method: 'post', path: this.endPoint() + path, entity: data, headers: { 'Content-Type': 'application/json' } }).then(function (response) { if (response.entity && response.entity.error) { if (callback) { callback(response.entity.error, response.entity, response); } } else { if (callback) { callback(false, response.entity, response); } } }, function(response) { if (callback) { callback(true, response); } }); }; Shared.synthesize(Rest.prototype, 'sessionData'); Shared.synthesize(Rest.prototype, 'endPoint'); Shared.synthesize(Rest.prototype, 'collection'); Shared.addModule('Rest', Rest); Shared.mixin(Rest.prototype, 'Mixin.ChainReactor'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; Overload = Shared.overload; Collection.prototype.init = function () { this.rest = new Rest(); this.rest.collection(this); CollectionInit.apply(this, arguments); }; Db.prototype.init = function () { this.rest = new Rest(); DbInit.apply(this, arguments); }; Shared.finishModule('Rest'); module.exports = Rest; },{"./Collection":5,"./CollectionGroup":6,"./Shared":37,"rest":101,"rest/interceptor/mime":106}],36:[function(_dereq_,module,exports){ "use strict"; var Serialiser = function () { }; Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object') { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Handle special object types and restore them // Iterate through the object's keys and parse for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$') { // This is a special object type, restore it switch (i) { case '$date': return new Date(data[i]); default: target[i] = this._parse(data[i], target[i]); break; } } else { target[i] = this._parse(data[i], target[i]); } } } } else { target = data; } // The data is a basic type return target; }; Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; Serialiser.prototype._stringify = function (data, target) { var i; if (typeof data === 'object') { // Handle special object types so they can be restored if (data instanceof Date) { return { $date: data.toISOString() }; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = new Serialiser(); },{}],37:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.350', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":17,"./Mixin.ChainReactor":18,"./Mixin.Common":19,"./Mixin.Constants":20,"./Mixin.Events":21,"./Mixin.Matching":22,"./Mixin.Sorting":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":28}],38:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],39:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(source.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function () { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } else { return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":34,"./Shared":37}],40:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":75}],41:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":42,"./core":43,"./enc-base64":44,"./evpkdf":46,"./md5":51}],42:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":43}],43:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],44:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":43}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":43}],46:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":43,"./hmac":48,"./sha1":67}],47:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":42,"./core":43}],48:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":43}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":41,"./cipher-core":42,"./core":43,"./enc-base64":44,"./enc-utf16":45,"./evpkdf":46,"./format-hex":47,"./hmac":48,"./lib-typedarrays":50,"./md5":51,"./mode-cfb":52,"./mode-ctr":54,"./mode-ctr-gladman":53,"./mode-ecb":55,"./mode-ofb":56,"./pad-ansix923":57,"./pad-iso10126":58,"./pad-iso97971":59,"./pad-nopadding":60,"./pad-zeropadding":61,"./pbkdf2":62,"./rabbit":64,"./rabbit-legacy":63,"./rc4":65,"./ripemd160":66,"./sha1":67,"./sha224":68,"./sha256":69,"./sha3":70,"./sha384":71,"./sha512":72,"./tripledes":73,"./x64-core":74}],50:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":43}],51:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":43}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":42,"./core":43}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":42,"./core":43}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":42,"./core":43}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":42,"./core":43}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":42,"./core":43}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":42,"./core":43}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":42,"./core":43}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":42,"./core":43}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":42,"./core":43}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":42,"./core":43}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":43,"./hmac":48,"./sha1":67}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":42,"./core":43,"./enc-base64":44,"./evpkdf":46,"./md5":51}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":42,"./core":43,"./enc-base64":44,"./evpkdf":46,"./md5":51}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":42,"./core":43,"./enc-base64":44,"./evpkdf":46,"./md5":51}],66:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":43}],67:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":43}],68:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":43,"./sha256":69}],69:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":43}],70:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":43,"./x64-core":74}],71:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":43,"./sha512":72,"./x64-core":74}],72:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":43,"./x64-core":74}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":42,"./core":43,"./enc-base64":44,"./evpkdf":46,"./md5":51}],74:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":43}],75:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],76:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":78}],77:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":76,"asap":78}],78:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":75}],79:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({status: xhr.status, response: xhr.response}); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function(resolve, reject) { var blob = _createBlob([''], {type: 'image/png'}); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function() { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore( DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function(e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function(res) { resolve(!!(res && res.type === 'image/png')); }, function() { resolve(false); }).then(function() { URL.revokeObjectURL(url); }); }; }; })['catch'](function() { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function(value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function(e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type}); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function(e) { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // added when support for blob shims was added openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function() { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { var dbInfo; self.ready().then(function() { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function(blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function(value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function() { resolve(); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { resolve(req.result); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function() { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":77}],80:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), i + 1); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":83,"promise":77}],81:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":83,"promise":77}],82:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { var driverPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly switch (driverName) { case self.INDEXEDDB: resolve(_dereq_('./drivers/indexeddb')); break; case self.LOCALSTORAGE: resolve(_dereq_('./drivers/localstorage')); break; case self.WEBSQL: resolve(_dereq_('./drivers/websql')); break; } } else { resolve(globalObject[driverName]); } }); driverPromise.then(function(driver) { self._extend(driver); resolve(); }); } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); resolve(); } else { self._driverSet = Promise.reject(error); reject(error); } }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":79,"./drivers/localstorage":80,"./drivers/websql":81,"promise":77}],83:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], {type: blobType}); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}],84:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":85,"./lib/inflate":86,"./lib/utils/common":87,"./lib/zlib/constants":90}],85:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":87,"./utils/strings":88,"./zlib/deflate.js":92,"./zlib/messages":97,"./zlib/zstream":99}],86:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":87,"./utils/strings":88,"./zlib/constants":90,"./zlib/gzheader":93,"./zlib/inflate.js":95,"./zlib/messages":97,"./zlib/zstream":99}],87:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],88:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":87}],89:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],90:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],91:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],92:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":87,"./adler32":89,"./crc32":91,"./messages":97,"./trees":98}],93:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],94:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],95:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":87,"./adler32":89,"./crc32":91,"./inffast":94,"./inftrees":96}],96:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":87}],97:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],98:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":87}],99:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],100:[function(_dereq_,module,exports){ /* * Copyright 2012-2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define, location) { 'use strict'; var undef; define(function (_dereq_) { var mixin, origin, urlRE, absoluteUrlRE, fullyQualifiedUrlRE; mixin = _dereq_('./util/mixin'); urlRE = /([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i; absoluteUrlRE = /^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i; fullyQualifiedUrlRE = /([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i; /** * Apply params to the template to create a URL. * * Parameters that are not applied directly to the template, are appended * to the URL as query string parameters. * * @param {string} template the URI template * @param {Object} params parameters to apply to the template * @return {string} the resulting URL */ function buildUrl(template, params) { // internal builder to convert template with params. var url, name, queryStringParams, re; url = template; queryStringParams = {}; if (params) { for (name in params) { /*jshint forin:false */ re = new RegExp('\\{' + name + '\\}'); if (re.test(url)) { url = url.replace(re, encodeURIComponent(params[name]), 'g'); } else { queryStringParams[name] = params[name]; } } for (name in queryStringParams) { url += url.indexOf('?') === -1 ? '?' : '&'; url += encodeURIComponent(name); if (queryStringParams[name] !== null && queryStringParams[name] !== undefined) { url += '='; url += encodeURIComponent(queryStringParams[name]); } } } return url; } function startsWith(str, test) { return str.indexOf(test) === 0; } /** * Create a new URL Builder * * @param {string|UrlBuilder} template the base template to build from, may be another UrlBuilder * @param {Object} [params] base parameters * @constructor */ function UrlBuilder(template, params) { if (!(this instanceof UrlBuilder)) { // invoke as a constructor return new UrlBuilder(template, params); } if (template instanceof UrlBuilder) { this._template = template.template; this._params = mixin({}, this._params, params); } else { this._template = (template || '').toString(); this._params = params || {}; } } UrlBuilder.prototype = { /** * Create a new UrlBuilder instance that extends the current builder. * The current builder is unmodified. * * @param {string} [template] URL template to append to the current template * @param {Object} [params] params to combine with current params. New params override existing params * @return {UrlBuilder} the new builder */ append: function (template, params) { // TODO consider query strings and fragments return new UrlBuilder(this._template + template, mixin({}, this._params, params)); }, /** * Create a new UrlBuilder with a fully qualified URL based on the * window's location or base href and the current templates relative URL. * * Path variables are preserved. * * *Browser only* * * @return {UrlBuilder} the fully qualified URL template */ fullyQualify: function () { if (!location) { return this; } if (this.isFullyQualified()) { return this; } var template = this._template; if (startsWith(template, '//')) { template = origin.protocol + template; } else if (startsWith(template, '/')) { template = origin.origin + template; } else if (!this.isAbsolute()) { template = origin.origin + origin.pathname.substring(0, origin.pathname.lastIndexOf('/') + 1); } if (template.indexOf('/', 8) === -1) { // default the pathname to '/' template = template + '/'; } return new UrlBuilder(template, this._params); }, /** * True if the URL is absolute * * @return {boolean} */ isAbsolute: function () { return absoluteUrlRE.test(this.build()); }, /** * True if the URL is fully qualified * * @return {boolean} */ isFullyQualified: function () { return fullyQualifiedUrlRE.test(this.build()); }, /** * True if the URL is cross origin. The protocol, host and port must not be * the same in order to be cross origin, * * @return {boolean} */ isCrossOrigin: function () { if (!origin) { return true; } var url = this.parts(); return url.protocol !== origin.protocol || url.hostname !== origin.hostname || url.port !== origin.port; }, /** * Split a URL into its consituent parts following the naming convention of * 'window.location'. One difference is that the port will contain the * protocol default if not specified. * * @see https://developer.mozilla.org/en-US/docs/DOM/window.location * * @returns {Object} a 'window.location'-like object */ parts: function () { /*jshint maxcomplexity:20 */ var url, parts; url = this.fullyQualify().build().match(urlRE); parts = { href: url[0], protocol: url[1], host: url[3] || '', hostname: url[4] || '', port: url[6], pathname: url[7] || '', search: url[8] || '', hash: url[9] || '' }; parts.origin = parts.protocol + '//' + parts.host; parts.port = parts.port || (parts.protocol === 'https:' ? '443' : parts.protocol === 'http:' ? '80' : ''); return parts; }, /** * Expand the template replacing path variables with parameters * * @param {Object} [params] params to combine with current params. New params override existing params * @return {string} the expanded URL */ build: function (params) { return buildUrl(this._template, mixin({}, this._params, params)); }, /** * @see build */ toString: function () { return this.build(); } }; origin = location ? new UrlBuilder(location.href).parts() : undef; return UrlBuilder; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }, typeof window !== 'undefined' ? window.location : void 0 // Boilerplate for AMD and Node )); },{"./util/mixin":136}],101:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var rest = _dereq_('./client/default'), browser = _dereq_('./client/xhr'); rest.setPlatformDefaultClient(browser); return rest; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./client/default":103,"./client/xhr":104}],102:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { /** * Add common helper methods to a client impl * * @param {function} impl the client implementation * @param {Client} [target] target of this client, used when wrapping other clients * @returns {Client} the client impl with additional methods */ return function client(impl, target) { if (target) { /** * @returns {Client} the target client */ impl.skip = function skip() { return target; }; } /** * Allow a client to easily be wrapped by an interceptor * * @param {Interceptor} interceptor the interceptor to wrap this client with * @param [config] configuration for the interceptor * @returns {Client} the newly wrapped client */ impl.wrap = function wrap(interceptor, config) { return interceptor(impl, config); }; /** * @deprecated */ impl.chain = function chain() { if (typeof console !== 'undefined') { console.log('rest.js: client.chain() is deprecated, use client.wrap() instead'); } return impl.wrap.apply(this, arguments); }; return impl; }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],103:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; define(function (_dereq_) { /** * Plain JS Object containing properties that represent an HTTP request. * * Depending on the capabilities of the underlying client, a request * may be cancelable. If a request may be canceled, the client will add * a canceled flag and cancel function to the request object. Canceling * the request will put the response into an error state. * * @field {string} [method='GET'] HTTP method, commonly GET, POST, PUT, DELETE or HEAD * @field {string|UrlBuilder} [path=''] path template with optional path variables * @field {Object} [params] parameters for the path template and query string * @field {Object} [headers] custom HTTP headers to send, in addition to the clients default headers * @field [entity] the HTTP entity, common for POST or PUT requests * @field {boolean} [canceled] true if the request has been canceled, set by the client * @field {Function} [cancel] cancels the request if invoked, provided by the client * @field {Client} [originator] the client that first handled this request, provided by the interceptor * * @class Request */ /** * Plain JS Object containing properties that represent an HTTP response * * @field {Object} [request] the request object as received by the root client * @field {Object} [raw] the underlying request object, like XmlHttpRequest in a browser * @field {number} [status.code] status code of the response (i.e. 200, 404) * @field {string} [status.text] status phrase of the response * @field {Object] [headers] response headers hash of normalized name, value pairs * @field [entity] the response body * * @class Response */ /** * HTTP client particularly suited for RESTful operations. * * @field {function} wrap wraps this client with a new interceptor returning the wrapped client * * @param {Request} the HTTP request * @returns {ResponsePromise<Response>} a promise the resolves to the HTTP response * * @class Client */ /** * Extended when.js Promises/A+ promise with HTTP specific helpers *q * @method entity promise for the HTTP entity * @method status promise for the HTTP status code * @method headers promise for the HTTP response headers * @method header promise for a specific HTTP response header * * @class ResponsePromise * @extends Promise */ var client, target, platformDefault; client = _dereq_('../client'); /** * Make a request with the default client * @param {Request} the HTTP request * @returns {Promise<Response>} a promise the resolves to the HTTP response */ function defaultClient() { return target.apply(undef, arguments); } /** * Change the default client * @param {Client} client the new default client */ defaultClient.setDefaultClient = function setDefaultClient(client) { target = client; }; /** * Obtain a direct reference to the current default client * @returns {Client} the default client */ defaultClient.getDefaultClient = function getDefaultClient() { return target; }; /** * Reset the default client to the platform default */ defaultClient.resetDefaultClient = function resetDefaultClient() { target = platformDefault; }; /** * @private */ defaultClient.setPlatformDefaultClient = function setPlatformDefaultClient(client) { if (platformDefault) { throw new Error('Unable to redefine platformDefaultClient'); } target = platformDefault = client; }; return client(defaultClient); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../client":102}],104:[function(_dereq_,module,exports){ /* * Copyright 2012-2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define, global) { 'use strict'; define(function (_dereq_) { var when, UrlBuilder, normalizeHeaderName, responsePromise, client, headerSplitRE; when = _dereq_('when'); UrlBuilder = _dereq_('../UrlBuilder'); normalizeHeaderName = _dereq_('../util/normalizeHeaderName'); responsePromise = _dereq_('../util/responsePromise'); client = _dereq_('../client'); // according to the spec, the line break is '\r\n', but doesn't hold true in practice headerSplitRE = /[\r|\n]+/; function parseHeaders(raw) { // Note: Set-Cookie will be removed by the browser var headers = {}; if (!raw) { return headers; } raw.trim().split(headerSplitRE).forEach(function (header) { var boundary, name, value; boundary = header.indexOf(':'); name = normalizeHeaderName(header.substring(0, boundary).trim()); value = header.substring(boundary + 1).trim(); if (headers[name]) { if (Array.isArray(headers[name])) { // add to an existing array headers[name].push(value); } else { // convert single value to array headers[name] = [headers[name], value]; } } else { // new, single value headers[name] = value; } }); return headers; } function safeMixin(target, source) { Object.keys(source || {}).forEach(function (prop) { // make sure the property already exists as // IE 6 will blow up if we add a new prop if (source.hasOwnProperty(prop) && prop in target) { try { target[prop] = source[prop]; } catch (e) { // ignore, expected for some properties at some points in the request lifecycle } } }); return target; } return client(function xhr(request) { return responsePromise.promise(function (resolve, reject) { /*jshint maxcomplexity:20 */ var client, method, url, headers, entity, headerName, response, XMLHttpRequest; request = typeof request === 'string' ? { path: request } : request || {}; response = { request: request }; if (request.canceled) { response.error = 'precanceled'; reject(response); return; } XMLHttpRequest = request.engine || global.XMLHttpRequest; if (!XMLHttpRequest) { reject({ request: request, error: 'xhr-not-available' }); return; } entity = request.entity; request.method = request.method || (entity ? 'POST' : 'GET'); method = request.method; url = new UrlBuilder(request.path || '', request.params).build(); try { client = response.raw = new XMLHttpRequest(); // mixin extra request properties before and after opening the request as some properties require being set at different phases of the request safeMixin(client, request.mixin); client.open(method, url, true); safeMixin(client, request.mixin); headers = request.headers; for (headerName in headers) { /*jshint forin:false */ if (headerName === 'Content-Type' && headers[headerName] === 'multipart/form-data') { // XMLHttpRequest generates its own Content-Type header with the // appropriate multipart boundary when sending multipart/form-data. continue; } client.setRequestHeader(headerName, headers[headerName]); } request.canceled = false; request.cancel = function cancel() { request.canceled = true; client.abort(); reject(response); }; client.onreadystatechange = function (/* e */) { if (request.canceled) { return; } if (client.readyState === (XMLHttpRequest.DONE || 4)) { response.status = { code: client.status, text: client.statusText }; response.headers = parseHeaders(client.getAllResponseHeaders()); response.entity = client.responseText; if (response.status.code > 0) { // check status code as readystatechange fires before error event resolve(response); } else { // give the error callback a chance to fire before resolving // requests for file:// URLs do not have a status code setTimeout(function () { resolve(response); }, 0); } } }; try { client.onerror = function (/* e */) { response.error = 'loaderror'; reject(response); }; } catch (e) { // IE 6 will not support error handling } client.send(entity); } catch (e) { response.error = 'loaderror'; reject(response); } }); }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }, typeof window !== 'undefined' ? window : void 0 // Boilerplate for AMD and Node )); },{"../UrlBuilder":100,"../client":102,"../util/normalizeHeaderName":137,"../util/responsePromise":138,"when":133}],105:[function(_dereq_,module,exports){ /* * Copyright 2012-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var defaultClient, mixin, responsePromise, client, when; defaultClient = _dereq_('./client/default'); mixin = _dereq_('./util/mixin'); responsePromise = _dereq_('./util/responsePromise'); client = _dereq_('./client'); when = _dereq_('when'); /** * Interceptors have the ability to intercept the request and/org response * objects. They may augment, prune, transform or replace the * request/response as needed. Clients may be composed by wrapping * together multiple interceptors. * * Configured interceptors are functional in nature. Wrapping a client in * an interceptor will not affect the client, merely the data that flows in * and out of that client. A common configuration can be created once and * shared; specialization can be created by further wrapping that client * with custom interceptors. * * @param {Client} [target] client to wrap * @param {Object} [config] configuration for the interceptor, properties will be specific to the interceptor implementation * @returns {Client} A client wrapped with the interceptor * * @class Interceptor */ function defaultInitHandler(config) { return config; } function defaultRequestHandler(request /*, config, meta */) { return request; } function defaultResponseHandler(response /*, config, meta */) { return response; } function race(promisesOrValues) { // this function is different than when.any as the first to reject also wins return when.promise(function (resolve, reject) { promisesOrValues.forEach(function (promiseOrValue) { when(promiseOrValue, resolve, reject); }); }); } /** * Alternate return type for the request handler that allows for more complex interactions. * * @param properties.request the traditional request return object * @param {Promise} [properties.abort] promise that resolves if/when the request is aborted * @param {Client} [properties.client] override the defined client with an alternate client * @param [properties.response] response for the request, short circuit the request */ function ComplexRequest(properties) { if (!(this instanceof ComplexRequest)) { // in case users forget the 'new' don't mix into the interceptor return new ComplexRequest(properties); } mixin(this, properties); } /** * Create a new interceptor for the provided handlers. * * @param {Function} [handlers.init] one time intialization, must return the config object * @param {Function} [handlers.request] request handler * @param {Function} [handlers.response] response handler regardless of error state * @param {Function} [handlers.success] response handler when the request is not in error * @param {Function} [handlers.error] response handler when the request is in error, may be used to 'unreject' an error state * @param {Function} [handlers.client] the client to use if otherwise not specified, defaults to platform default client * * @returns {Interceptor} */ function interceptor(handlers) { var initHandler, requestHandler, successResponseHandler, errorResponseHandler; handlers = handlers || {}; initHandler = handlers.init || defaultInitHandler; requestHandler = handlers.request || defaultRequestHandler; successResponseHandler = handlers.success || handlers.response || defaultResponseHandler; errorResponseHandler = handlers.error || function () { // Propagate the rejection, with the result of the handler return when((handlers.response || defaultResponseHandler).apply(this, arguments), when.reject, when.reject); }; return function (target, config) { if (typeof target === 'object') { config = target; } if (typeof target !== 'function') { target = handlers.client || defaultClient; } config = initHandler(config || {}); function interceptedClient(request) { var context, meta; context = {}; meta = { 'arguments': Array.prototype.slice.call(arguments), client: interceptedClient }; request = typeof request === 'string' ? { path: request } : request || {}; request.originator = request.originator || interceptedClient; return responsePromise( requestHandler.call(context, request, config, meta), function (request) { var response, abort, next; next = target; if (request instanceof ComplexRequest) { // unpack request abort = request.abort; next = request.client || next; response = request.response; // normalize request, must be last request = request.request; } response = response || when(request, function (request) { return when( next(request), function (response) { return successResponseHandler.call(context, response, config, meta); }, function (response) { return errorResponseHandler.call(context, response, config, meta); } ); }); return abort ? race([response, abort]) : response; }, function (error) { return when.reject({ request: request, error: error }); } ); } return client(interceptedClient, target); }; } interceptor.ComplexRequest = ComplexRequest; return interceptor; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./client":102,"./client/default":103,"./util/mixin":136,"./util/responsePromise":138,"when":133}],106:[function(_dereq_,module,exports){ /* * Copyright 2012-2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var interceptor, mime, registry, noopConverter, when; interceptor = _dereq_('../interceptor'); mime = _dereq_('../mime'); registry = _dereq_('../mime/registry'); when = _dereq_('when'); noopConverter = { read: function (obj) { return obj; }, write: function (obj) { return obj; } }; /** * MIME type support for request and response entities. Entities are * (de)serialized using the converter for the MIME type. * * Request entities are converted using the desired converter and the * 'Accept' request header prefers this MIME. * * Response entities are converted based on the Content-Type response header. * * @param {Client} [client] client to wrap * @param {string} [config.mime='text/plain'] MIME type to encode the request * entity * @param {string} [config.accept] Accept header for the request * @param {Client} [config.client=<request.originator>] client passed to the * converter, defaults to the client originating the request * @param {Registry} [config.registry] MIME registry, defaults to the root * registry * @param {boolean} [config.permissive] Allow an unkown request MIME type * * @returns {Client} */ return interceptor({ init: function (config) { config.registry = config.registry || registry; return config; }, request: function (request, config) { var type, headers; headers = request.headers || (request.headers = {}); type = mime.parse(headers['Content-Type'] = headers['Content-Type'] || config.mime || 'text/plain'); headers.Accept = headers.Accept || config.accept || type.raw + ', application/json;q=0.8, text/plain;q=0.5, */*;q=0.2'; if (!('entity' in request)) { return request; } return config.registry.lookup(type).otherwise(function () { // failed to resolve converter if (config.permissive) { return noopConverter; } throw 'mime-unknown'; }).then(function (converter) { var client = config.client || request.originator; return when.attempt(converter.write, request.entity, { client: client, request: request, mime: type, registry: config.registry }) .otherwise(function() { throw 'mime-serialization'; }) .then(function(entity) { request.entity = entity; return request; }); }); }, response: function (response, config) { if (!(response.headers && response.headers['Content-Type'] && response.entity)) { return response; } var type = mime.parse(response.headers['Content-Type']); return config.registry.lookup(type).otherwise(function () { return noopConverter; }).then(function (converter) { var client = config.client || response.request && response.request.originator; return when.attempt(converter.read, response.entity, { client: client, response: response, mime: type, registry: config.registry }) .otherwise(function (e) { response.error = 'mime-deserialization'; response.cause = e; throw response; }) .then(function (entity) { response.entity = entity; return response; }); }); } }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../interceptor":105,"../mime":109,"../mime/registry":110,"when":133}],107:[function(_dereq_,module,exports){ /* * Copyright 2012-2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var interceptor, UrlBuilder; interceptor = _dereq_('../interceptor'); UrlBuilder = _dereq_('../UrlBuilder'); function startsWith(str, prefix) { return str.indexOf(prefix) === 0; } function endsWith(str, suffix) { return str.lastIndexOf(suffix) + suffix.length === str.length; } /** * Prefixes the request path with a common value. * * @param {Client} [client] client to wrap * @param {number} [config.prefix] path prefix * * @returns {Client} */ return interceptor({ request: function (request, config) { var path; if (config.prefix && !(new UrlBuilder(request.path).isFullyQualified())) { path = config.prefix; if (request.path) { if (!endsWith(path, '/') && !startsWith(request.path, '/')) { // add missing '/' between path sections path += '/'; } path += request.path; } request.path = path; } return request; } }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../UrlBuilder":100,"../interceptor":105}],108:[function(_dereq_,module,exports){ /* * Copyright 2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var interceptor, uriTemplate, mixin; interceptor = _dereq_('../interceptor'); uriTemplate = _dereq_('../util/uriTemplate'); mixin = _dereq_('../util/mixin'); /** * Applies request params to the path as a URI Template * * Params are removed from the request object, as they have been consumed. * * @param {Client} [client] client to wrap * @param {Object} [config.params] default param values * @param {string} [config.template] default template * * @returns {Client} */ return interceptor({ init: function (config) { config.params = config.params || {}; config.template = config.template || ''; return config; }, request: function (request, config) { var template, params; template = request.path || config.template; params = mixin({}, request.params, config.params); request.path = uriTemplate.expand(template, params); delete request.params; return request; } }); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../interceptor":105,"../util/mixin":136,"../util/uriTemplate":140}],109:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; define(function (/* require */) { /** * Parse a MIME type into it's constituent parts * * @param {string} mime MIME type to parse * @return {{ * {string} raw the original MIME type * {string} type the type and subtype * {string} [suffix] mime suffix, including the plus, if any * {Object} params key/value pair of attributes * }} */ function parse(mime) { var params, type; params = mime.split(';'); type = params[0].trim().split('+'); return { raw: mime, type: type[0], suffix: type[1] ? '+' + type[1] : '', params: params.slice(1).reduce(function (params, pair) { pair = pair.split('='); params[pair[0].trim()] = pair[1] ? pair[1].trim() : undef; return params; }, {}) }; } return { parse: parse }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],110:[function(_dereq_,module,exports){ /* * Copyright 2012-2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var mime, when, registry; mime = _dereq_('../mime'); when = _dereq_('when'); function Registry(mimes) { /** * Lookup the converter for a MIME type * * @param {string} type the MIME type * @return a promise for the converter */ this.lookup = function lookup(type) { var parsed; parsed = typeof type === 'string' ? mime.parse(type) : type; if (mimes[parsed.raw]) { return mimes[parsed.raw]; } if (mimes[parsed.type + parsed.suffix]) { return mimes[parsed.type + parsed.suffix]; } if (mimes[parsed.type]) { return mimes[parsed.type]; } if (mimes[parsed.suffix]) { return mimes[parsed.suffix]; } return when.reject(new Error('Unable to locate converter for mime "' + parsed.raw + '"')); }; /** * Create a late dispatched proxy to the target converter. * * Common when a converter is registered under multiple names and * should be kept in sync if updated. * * @param {string} type mime converter to dispatch to * @returns converter whose read/write methods target the desired mime converter */ this.delegate = function delegate(type) { return { read: function () { var args = arguments; return this.lookup(type).then(function (converter) { return converter.read.apply(this, args); }.bind(this)); }.bind(this), write: function () { var args = arguments; return this.lookup(type).then(function (converter) { return converter.write.apply(this, args); }.bind(this)); }.bind(this) }; }; /** * Register a custom converter for a MIME type * * @param {string} type the MIME type * @param converter the converter for the MIME type * @return a promise for the converter */ this.register = function register(type, converter) { mimes[type] = when(converter); return mimes[type]; }; /** * Create a child registry whoes registered converters remain local, while * able to lookup converters from its parent. * * @returns child MIME registry */ this.child = function child() { return new Registry(Object.create(mimes)); }; } registry = new Registry({}); // include provided serializers registry.register('application/hal', _dereq_('./type/application/hal')); registry.register('application/json', _dereq_('./type/application/json')); registry.register('application/x-www-form-urlencoded', _dereq_('./type/application/x-www-form-urlencoded')); registry.register('multipart/form-data', _dereq_('./type/multipart/form-data')); registry.register('text/plain', _dereq_('./type/text/plain')); registry.register('+json', registry.delegate('application/json')); return registry; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../mime":109,"./type/application/hal":111,"./type/application/json":112,"./type/application/x-www-form-urlencoded":113,"./type/multipart/form-data":114,"./type/text/plain":115,"when":133}],111:[function(_dereq_,module,exports){ /* * Copyright 2013-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var pathPrefix, template, find, lazyPromise, responsePromise, when; pathPrefix = _dereq_('../../../interceptor/pathPrefix'); template = _dereq_('../../../interceptor/template'); find = _dereq_('../../../util/find'); lazyPromise = _dereq_('../../../util/lazyPromise'); responsePromise = _dereq_('../../../util/responsePromise'); when = _dereq_('when'); function defineProperty(obj, name, value) { Object.defineProperty(obj, name, { value: value, configurable: true, enumerable: false, writeable: true }); } /** * Hypertext Application Language serializer * * Implemented to https://tools.ietf.org/html/draft-kelly-json-hal-06 * * As the spec is still a draft, this implementation will be updated as the * spec evolves * * Objects are read as HAL indexing links and embedded objects on to the * resource. Objects are written as plain JSON. * * Embedded relationships are indexed onto the resource by the relationship * as a promise for the related resource. * * Links are indexed onto the resource as a lazy promise that will GET the * resource when a handler is first registered on the promise. * * A `requestFor` method is added to the entity to make a request for the * relationship. * * A `clientFor` method is added to the entity to get a full Client for a * relationship. * * The `_links` and `_embedded` properties on the resource are made * non-enumerable. */ return { read: function (str, opts) { var client, console; opts = opts || {}; client = opts.client; console = opts.console || console; function deprecationWarning(relationship, deprecation) { if (deprecation && console && console.warn || console.log) { (console.warn || console.log).call(console, 'Relationship \'' + relationship + '\' is deprecated, see ' + deprecation); } } return opts.registry.lookup(opts.mime.suffix).then(function (converter) { return when(converter.read(str, opts)).then(function (root) { find.findProperties(root, '_embedded', function (embedded, resource, name) { Object.keys(embedded).forEach(function (relationship) { if (relationship in resource) { return; } var related = responsePromise({ entity: embedded[relationship] }); defineProperty(resource, relationship, related); }); defineProperty(resource, name, embedded); }); find.findProperties(root, '_links', function (links, resource, name) { Object.keys(links).forEach(function (relationship) { var link = links[relationship]; if (relationship in resource) { return; } defineProperty(resource, relationship, responsePromise.make(lazyPromise(function () { if (link.deprecation) { deprecationWarning(relationship, link.deprecation); } if (link.templated === true) { return template(client)({ path: link.href }); } return client({ path: link.href }); }))); }); defineProperty(resource, name, links); defineProperty(resource, 'clientFor', function (relationship, clientOverride) { var link = links[relationship]; if (!link) { throw new Error('Unknown relationship: ' + relationship); } if (link.deprecation) { deprecationWarning(relationship, link.deprecation); } if (link.templated === true) { return template( clientOverride || client, { template: link.href } ); } return pathPrefix( clientOverride || client, { prefix: link.href } ); }); defineProperty(resource, 'requestFor', function (relationship, request, clientOverride) { var client = this.clientFor(relationship, clientOverride); return client(request); }); }); return root; }); }); }, write: function (obj, opts) { return opts.registry.lookup(opts.mime.suffix).then(function (converter) { return converter.write(obj, opts); }); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"../../../interceptor/pathPrefix":107,"../../../interceptor/template":108,"../../../util/find":134,"../../../util/lazyPromise":135,"../../../util/responsePromise":138,"when":133}],112:[function(_dereq_,module,exports){ /* * Copyright 2012-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { /** * Create a new JSON converter with custom reviver/replacer. * * The extended converter must be published to a MIME registry in order * to be used. The existing converter will not be modified. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON * * @param {function} [reviver=undefined] custom JSON.parse reviver * @param {function|Array} [replacer=undefined] custom JSON.stringify replacer */ function createConverter(reviver, replacer) { return { read: function (str) { return JSON.parse(str, reviver); }, write: function (obj) { return JSON.stringify(obj, replacer); }, extend: createConverter }; } return createConverter(); }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],113:[function(_dereq_,module,exports){ /* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { var encodedSpaceRE, urlEncodedSpaceRE; encodedSpaceRE = /%20/g; urlEncodedSpaceRE = /\+/g; function urlEncode(str) { str = encodeURIComponent(str); // spec says space should be encoded as '+' return str.replace(encodedSpaceRE, '+'); } function urlDecode(str) { // spec says space should be encoded as '+' str = str.replace(urlEncodedSpaceRE, ' '); return decodeURIComponent(str); } function append(str, name, value) { if (Array.isArray(value)) { value.forEach(function (value) { str = append(str, name, value); }); } else { if (str.length > 0) { str += '&'; } str += urlEncode(name); if (value !== undefined && value !== null) { str += '=' + urlEncode(value); } } return str; } return { read: function (str) { var obj = {}; str.split('&').forEach(function (entry) { var pair, name, value; pair = entry.split('='); name = urlDecode(pair[0]); if (pair.length === 2) { value = urlDecode(pair[1]); } else { value = null; } if (name in obj) { if (!Array.isArray(obj[name])) { // convert to an array, perserving currnent value obj[name] = [obj[name]]; } obj[name].push(value); } else { obj[name] = value; } }); return obj; }, write: function (obj) { var str = ''; Object.keys(obj).forEach(function (name) { str = append(str, name, obj[name]); }); return str; } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],114:[function(_dereq_,module,exports){ /* * Copyright 2014 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Michael Jackson */ /* global FormData, File, Blob */ (function (define) { 'use strict'; define(function (/* require */) { function isFormElement(object) { return object && object.nodeType === 1 && // Node.ELEMENT_NODE object.tagName === 'FORM'; } function createFormDataFromObject(object) { var formData = new FormData(); var value; for (var property in object) { if (object.hasOwnProperty(property)) { value = object[property]; if (value instanceof File) { formData.append(property, value, value.name); } else if (value instanceof Blob) { formData.append(property, value); } else { formData.append(property, String(value)); } } } return formData; } return { write: function (object) { if (typeof FormData === 'undefined') { throw new Error('The multipart/form-data mime serializer requires FormData support'); } // Support FormData directly. if (object instanceof FormData) { return object; } // Support <form> elements. if (isFormElement(object)) { return new FormData(object); } // Support plain objects, may contain File/Blob as value. if (typeof object === 'object' && object !== null) { return createFormDataFromObject(object); } throw new Error('Unable to create FormData from object ' + object); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],115:[function(_dereq_,module,exports){ /* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { return { read: function (str) { return str; }, write: function (obj) { return obj.toString(); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],116:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function (_dereq_) { var makePromise = _dereq_('./makePromise'); var Scheduler = _dereq_('./Scheduler'); var async = _dereq_('./env').asap; return makePromise({ scheduler: new Scheduler(async) }); }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }); },{"./Scheduler":117,"./env":129,"./makePromise":131}],117:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { // Credit to Twisol (https://github.com/Twisol) for suggesting // this type of extensible queue + trampoline approach for next-tick conflation. /** * Async task scheduler * @param {function} async function to schedule a single async function * @constructor */ function Scheduler(async) { this._async = async; this._running = false; this._queue = this; this._queueLen = 0; this._afterQueue = {}; this._afterQueueLen = 0; var self = this; this.drain = function() { self._drain(); }; } /** * Enqueue a task * @param {{ run:function }} task */ Scheduler.prototype.enqueue = function(task) { this._queue[this._queueLen++] = task; this.run(); }; /** * Enqueue a task to run after the main task queue * @param {{ run:function }} task */ Scheduler.prototype.afterQueue = function(task) { this._afterQueue[this._afterQueueLen++] = task; this.run(); }; Scheduler.prototype.run = function() { if (!this._running) { this._running = true; this._async(this.drain); } }; /** * Drain the handler queue entirely, and then the after queue */ Scheduler.prototype._drain = function() { var i = 0; for (; i < this._queueLen; ++i) { this._queue[i].run(); this._queue[i] = void 0; } this._queueLen = 0; this._running = false; for (i = 0; i < this._afterQueueLen; ++i) { this._afterQueue[i].run(); this._afterQueue[i] = void 0; } this._afterQueueLen = 0; }; return Scheduler; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],118:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { /** * Custom error type for promises rejected by promise.timeout * @param {string} message * @constructor */ function TimeoutError (message) { Error.call(this); this.message = message; this.name = TimeoutError.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, TimeoutError); } } TimeoutError.prototype = Object.create(Error.prototype); TimeoutError.prototype.constructor = TimeoutError; return TimeoutError; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],119:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { makeApply.tryCatchResolve = tryCatchResolve; return makeApply; function makeApply(Promise, call) { if(arguments.length < 2) { call = tryCatchResolve; } return apply; function apply(f, thisArg, args) { var p = Promise._defer(); var l = args.length; var params = new Array(l); callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler); return p; } function callAndResolve(c, h) { if(c.i < 0) { return call(c.f, c.thisArg, c.params, h); } var handler = Promise._handler(c.args[c.i]); handler.fold(callAndResolveNext, c, void 0, h); } function callAndResolveNext(c, x, h) { c.params[c.i] = x; c.i -= 1; callAndResolve(c, h); } } function tryCatchResolve(f, thisArg, args, resolver) { try { resolver.resolve(f.apply(thisArg, args)); } catch(e) { resolver.reject(e); } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],120:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var state = _dereq_('../state'); var applier = _dereq_('../apply'); return function array(Promise) { var applyFold = applier(Promise); var toPromise = Promise.resolve; var all = Promise.all; var ar = Array.prototype.reduce; var arr = Array.prototype.reduceRight; var slice = Array.prototype.slice; // Additional array combinators Promise.any = any; Promise.some = some; Promise.settle = settle; Promise.map = map; Promise.filter = filter; Promise.reduce = reduce; Promise.reduceRight = reduceRight; /** * When this promise fulfills with an array, do * onFulfilled.apply(void 0, array) * @param {function} onFulfilled function to apply * @returns {Promise} promise for the result of applying onFulfilled */ Promise.prototype.spread = function(onFulfilled) { return this.then(all).then(function(array) { return onFulfilled.apply(this, array); }); }; return Promise; /** * One-winner competitive race. * Return a promise that will fulfill when one of the promises * in the input array fulfills, or will reject when all promises * have rejected. * @param {array} promises * @returns {Promise} promise for the first fulfilled value */ function any(promises) { var p = Promise._defer(); var resolver = p._handler; var l = promises.length>>>0; var pending = l; var errors = []; for (var h, x, i = 0; i < l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { --pending; continue; } h = Promise._handler(x); if(h.state() > 0) { resolver.become(h); Promise._visitRemaining(promises, i, h); break; } else { h.visit(resolver, handleFulfill, handleReject); } } if(pending === 0) { resolver.reject(new RangeError('any(): array must not be empty')); } return p; function handleFulfill(x) { /*jshint validthis:true*/ errors = null; this.resolve(x); // this === resolver } function handleReject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--pending === 0) { this.reject(errors); } } } /** * N-winner competitive race * Return a promise that will fulfill when n input promises have * fulfilled, or will reject when it becomes impossible for n * input promises to fulfill (ie when promises.length - n + 1 * have rejected) * @param {array} promises * @param {number} n * @returns {Promise} promise for the earliest n fulfillment values * * @deprecated */ function some(promises, n) { /*jshint maxcomplexity:7*/ var p = Promise._defer(); var resolver = p._handler; var results = []; var errors = []; var l = promises.length>>>0; var nFulfill = 0; var nReject; var x, i; // reused in both for() loops // First pass: count actual array items for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } ++nFulfill; } // Compute actual goals n = Math.max(n, 0); nReject = (nFulfill - n + 1); nFulfill = Math.min(n, nFulfill); if(n > nFulfill) { resolver.reject(new RangeError('some(): array must contain at least ' + n + ' item(s), but had ' + nFulfill)); } else if(nFulfill === 0) { resolver.resolve(results); } // Second pass: observe each array item, make progress toward goals for(i=0; i<l; ++i) { x = promises[i]; if(x === void 0 && !(i in promises)) { continue; } Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify); } return p; function fulfill(x) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } results.push(x); if(--nFulfill === 0) { errors = null; this.resolve(results); } } function reject(e) { /*jshint validthis:true*/ if(this.resolved) { // this === resolver return; } errors.push(e); if(--nReject === 0) { results = null; this.reject(errors); } } } /** * Apply f to the value of each promise in a list of promises * and return a new list containing the results. * @param {array} promises * @param {function(x:*, index:Number):*} f mapping function * @returns {Promise} */ function map(promises, f) { return Promise._traverse(f, promises); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { var a = slice.call(promises); return Promise._traverse(predicate, a).then(function(keep) { return filterSync(a, keep); }); } function filterSync(promises, keep) { // Safe because we know all promises have fulfilled if we've made it this far var l = keep.length; var filtered = new Array(l); for(var i=0, j=0; i<l; ++i) { if(keep[i]) { filtered[j++] = Promise._handler(promises[i]).value; } } filtered.length = j; return filtered; } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will never reject. * @param {Array} promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return all(promises.map(settleOne)); } function settleOne(p) { var h = Promise._handler(p); if(h.state() === 0) { return toPromise(p).then(state.fulfilled, state.rejected); } h._unreport(); return state.inspect(h); } /** * Traditional reduce function, similar to `Array.prototype.reduce()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduce(promises, f /*, initialValue */) { return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2]) : ar.call(promises, liftCombine(f)); } /** * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but * input may contain promises and/or values, and reduceFunc * may return either a value or a promise, *and* initialValue may * be a promise for the starting value. * @param {Array|Promise} promises array or promise for an array of anything, * may contain a mix of promises and values. * @param {function(accumulated:*, x:*, index:Number):*} f reduce function * @returns {Promise} that will resolve to the final reduced value */ function reduceRight(promises, f /*, initialValue */) { return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2]) : arr.call(promises, liftCombine(f)); } function liftCombine(f) { return function(z, x, i) { return applyFold(f, void 0, [z,x,i]); }; } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../apply":119,"../state":132}],121:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function flow(Promise) { var resolve = Promise.resolve; var reject = Promise.reject; var origCatch = Promise.prototype['catch']; /** * Handle the ultimate fulfillment value or rejection reason, and assume * responsibility for all errors. If an error propagates out of result * or handleFatalError, it will be rethrown to the host, resulting in a * loud stack track on most platforms and a crash on some. * @param {function?} onResult * @param {function?} onError * @returns {undefined} */ Promise.prototype.done = function(onResult, onError) { this._handler.visit(this._handler.receiver, onResult, onError); }; /** * Add Error-type and predicate matching to catch. Examples: * promise['catch'](TypeError, handleTypeError) * ['catch'](predicate, handleMatchedErrors) * ['catch'](handleRemainingErrors) * @param onRejected * @returns {*} */ Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) { if (arguments.length < 2) { return origCatch.call(this, onRejected); } if(typeof onRejected !== 'function') { return this.ensure(rejectInvalidPredicate); } return origCatch.call(this, createCatchFilter(arguments[1], onRejected)); }; /** * Wraps the provided catch handler, so that it will only be called * if the predicate evaluates truthy * @param {?function} handler * @param {function} predicate * @returns {function} conditional catch handler */ function createCatchFilter(handler, predicate) { return function(e) { return evaluatePredicate(e, predicate) ? handler.call(this, e) : reject(e); }; } /** * Ensures that onFulfilledOrRejected will be called regardless of whether * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT * receive the promises' value or reason. Any returned value will be disregarded. * onFulfilledOrRejected may throw or return a rejected promise to signal * an additional error. * @param {function} handler handler to be called regardless of * fulfillment or rejection * @returns {Promise} */ Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) { if(typeof handler !== 'function') { return this; } return this.then(function(x) { return runSideEffect(handler, this, identity, x); }, function(e) { return runSideEffect(handler, this, reject, e); }); }; function runSideEffect (handler, thisArg, propagate, value) { var result = handler.call(thisArg); return maybeThenable(result) ? propagateValue(result, propagate, value) : propagate(value); } function propagateValue (result, propagate, x) { return resolve(result).then(function () { return propagate(x); }); } /** * Recover from a failure by returning a defaultValue. If defaultValue * is a promise, it's fulfillment value will be used. If defaultValue is * a promise that rejects, the returned promise will reject with the * same reason. * @param {*} defaultValue * @returns {Promise} new promise */ Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) { return this.then(void 0, function() { return defaultValue; }); }; /** * Shortcut for .then(function() { return value; }) * @param {*} value * @return {Promise} a promise that: * - is fulfilled if value is not a promise, or * - if value is a promise, will fulfill with its value, or reject * with its reason. */ Promise.prototype['yield'] = function(value) { return this.then(function() { return value; }); }; /** * Runs a side effect when this promise fulfills, without changing the * fulfillment value. * @param {function} onFulfilledSideEffect * @returns {Promise} */ Promise.prototype.tap = function(onFulfilledSideEffect) { return this.then(onFulfilledSideEffect)['yield'](this); }; return Promise; }; function rejectInvalidPredicate() { throw new TypeError('catch predicate must be a function'); } function evaluatePredicate(e, predicate) { return isError(predicate) ? e instanceof predicate : predicate(e); } function isError(predicate) { return predicate === Error || (predicate != null && predicate.prototype instanceof Error); } function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function identity(x) { return x; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],122:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /** @author Jeff Escalante */ (function(define) { 'use strict'; define(function() { return function fold(Promise) { Promise.prototype.fold = function(f, z) { var promise = this._beget(); this._handler.fold(function(z, x, to) { Promise._handler(z).fold(function(x, z, to) { to.resolve(f.call(this, z, x)); }, x, this, to); }, z, promise._handler.receiver, promise._handler); return promise; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],123:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var inspect = _dereq_('../state').inspect; return function inspection(Promise) { Promise.prototype.inspect = function() { return inspect(Promise._handler(this)); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../state":132}],124:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function generate(Promise) { var resolve = Promise.resolve; Promise.iterate = iterate; Promise.unfold = unfold; return Promise; /** * @deprecated Use github.com/cujojs/most streams and most.iterate * Generate a (potentially infinite) stream of promised values: * x, f(x), f(f(x)), etc. until condition(x) returns true * @param {function} f function to generate a new x from the previous x * @param {function} condition function that, given the current x, returns * truthy when the iterate should stop * @param {function} handler function to handle the value produced by f * @param {*|Promise} x starting value, may be a promise * @return {Promise} the result of the last call to f before * condition returns true */ function iterate(f, condition, handler, x) { return unfold(function(x) { return [x, f(x)]; }, condition, handler, x); } /** * @deprecated Use github.com/cujojs/most streams and most.unfold * Generate a (potentially infinite) stream of promised values * by applying handler(generator(seed)) iteratively until * condition(seed) returns true. * @param {function} unspool function that generates a [value, newSeed] * given a seed. * @param {function} condition function that, given the current seed, returns * truthy when the unfold should stop * @param {function} handler function to handle the value produced by unspool * @param x {*|Promise} starting value, may be a promise * @return {Promise} the result of the last value produced by unspool before * condition returns true */ function unfold(unspool, condition, handler, x) { return resolve(x).then(function(seed) { return resolve(condition(seed)).then(function(done) { return done ? seed : resolve(unspool(seed)).spread(next); }); }); function next(item, newSeed) { return resolve(handler(item)).then(function() { return unfold(unspool, condition, handler, newSeed); }); } } }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],125:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function progress(Promise) { /** * @deprecated * Register a progress handler for this promise * @param {function} onProgress * @returns {Promise} */ Promise.prototype.progress = function(onProgress) { return this.then(void 0, void 0, onProgress); }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],126:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var env = _dereq_('../env'); var TimeoutError = _dereq_('../TimeoutError'); function setTimeout(f, ms, x, y) { return env.setTimer(function() { f(x, y, ms); }, ms); } return function timed(Promise) { /** * Return a new promise whose fulfillment value is revealed only * after ms milliseconds * @param {number} ms milliseconds * @returns {Promise} */ Promise.prototype.delay = function(ms) { var p = this._beget(); this._handler.fold(handleDelay, ms, void 0, p._handler); return p; }; function handleDelay(ms, x, h) { setTimeout(resolveDelay, ms, x, h); } function resolveDelay(x, h) { h.resolve(x); } /** * Return a new promise that rejects after ms milliseconds unless * this promise fulfills earlier, in which case the returned promise * fulfills with the same value. * @param {number} ms milliseconds * @param {Error|*=} reason optional rejection reason to use, defaults * to a TimeoutError if not provided * @returns {Promise} */ Promise.prototype.timeout = function(ms, reason) { var p = this._beget(); var h = p._handler; var t = setTimeout(onTimeout, ms, reason, p._handler); this._handler.visit(h, function onFulfill(x) { env.clearTimer(t); this.resolve(x); // this = h }, function onReject(x) { env.clearTimer(t); this.reject(x); // this = h }, h.notify); return p; }; function onTimeout(reason, h, ms) { var e = typeof reason === 'undefined' ? new TimeoutError('timed out after ' + ms + 'ms') : reason; h.reject(e); } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../TimeoutError":118,"../env":129}],127:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var setTimer = _dereq_('../env').setTimer; var format = _dereq_('../format'); return function unhandledRejection(Promise) { var logError = noop; var logInfo = noop; var localConsole; if(typeof console !== 'undefined') { // Alias console to prevent things like uglify's drop_console option from // removing console.log/error. Unhandled rejections fall into the same // category as uncaught exceptions, and build tools shouldn't silence them. localConsole = console; logError = typeof localConsole.error !== 'undefined' ? function (e) { localConsole.error(e); } : function (e) { localConsole.log(e); }; logInfo = typeof localConsole.info !== 'undefined' ? function (e) { localConsole.info(e); } : function (e) { localConsole.log(e); }; } Promise.onPotentiallyUnhandledRejection = function(rejection) { enqueue(report, rejection); }; Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) { enqueue(unreport, rejection); }; Promise.onFatalRejection = function(rejection) { enqueue(throwit, rejection.value); }; var tasks = []; var reported = []; var running = null; function report(r) { if(!r.handled) { reported.push(r); logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value)); } } function unreport(r) { var i = reported.indexOf(r); if(i >= 0) { reported.splice(i, 1); logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value)); } } function enqueue(f, x) { tasks.push(f, x); if(running === null) { running = setTimer(flush, 0); } } function flush() { running = null; while(tasks.length > 0) { tasks.shift()(tasks.shift()); } } return Promise; }; function throwit(e) { throw e; } function noop() {} }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"../env":129,"../format":130}],128:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function addWith(Promise) { /** * Returns a promise whose handlers will be called with `this` set to * the supplied receiver. Subsequent promises derived from the * returned promise will also have their handlers called with receiver * as `this`. Calling `with` with undefined or no arguments will return * a promise whose handlers will again be called in the usual Promises/A+ * way (no `this`) thus safely undoing any previous `with` in the * promise chain. * * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+ * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41) * * @param {object} receiver `this` value for all handlers attached to * the returned promise. * @returns {Promise} */ Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) { var p = this._beget(); var child = p._handler; child.receiver = receiver; this._handler.chain(child, receiver); return p; }; return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],129:[function(_dereq_,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/ (function(define) { 'use strict'; define(function(_dereq_) { /*jshint maxcomplexity:6*/ // Sniff "best" async scheduling option // Prefer process.nextTick or MutationObserver, then check for // setTimeout, and finally vertx, since its the only env that doesn't // have setTimeout var MutationObs; var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout; // Default env var setTimer = function(f, ms) { return setTimeout(f, ms); }; var clearTimer = function(t) { return clearTimeout(t); }; var asap = function (f) { return capturedSetTimeout(f, 0); }; // Detect specific env if (isNode()) { // Node asap = function (f) { return process.nextTick(f); }; } else if (MutationObs = hasMutationObserver()) { // Modern browser asap = initMutationObserver(MutationObs); } else if (!capturedSetTimeout) { // vert.x var vertxRequire = _dereq_; var vertx = vertxRequire('vertx'); setTimer = function (f, ms) { return vertx.setTimer(ms, f); }; clearTimer = vertx.cancelTimer; asap = vertx.runOnLoop || vertx.runOnContext; } return { setTimer: setTimer, clearTimer: clearTimer, asap: asap }; function isNode () { return typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]'; } function hasMutationObserver () { return (typeof MutationObserver === 'function' && MutationObserver) || (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver); } function initMutationObserver(MutationObserver) { var scheduled; var node = document.createTextNode(''); var o = new MutationObserver(run); o.observe(node, { characterData: true }); function run() { var f = scheduled; scheduled = void 0; f(); } var i = 0; return function (f) { scheduled = f; node.data = (i ^= 1); }; } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); }).call(this,_dereq_('_process')) },{"_process":75}],130:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { formatError: formatError, formatObject: formatObject, tryStringify: tryStringify }; /** * Format an error into a string. If e is an Error and has a stack property, * it's returned. Otherwise, e is formatted using formatObject, with a * warning added about e not being a proper Error. * @param {*} e * @returns {String} formatted string, suitable for output to developers */ function formatError(e) { var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e); return e instanceof Error ? s : s + ' (WARNING: non-Error used)'; } /** * Format an object, detecting "plain" objects and running them through * JSON.stringify if possible. * @param {Object} o * @returns {string} */ function formatObject(o) { var s = String(o); if(s === '[object Object]' && typeof JSON !== 'undefined') { s = tryStringify(o, s); } return s; } /** * Try to return the result of JSON.stringify(x). If that fails, return * defaultValue * @param {*} x * @param {*} defaultValue * @returns {String|*} JSON.stringify(x) or defaultValue */ function tryStringify(x, defaultValue) { try { return JSON.stringify(x); } catch(e) { return defaultValue; } } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],131:[function(_dereq_,module,exports){ (function (process){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function makePromise(environment) { var tasks = environment.scheduler; var emitRejection = initEmitRejection(); var objectCreate = Object.create || function(proto) { function Child() {} Child.prototype = proto; return new Child(); }; /** * Create a promise whose fate is determined by resolver * @constructor * @returns {Promise} promise * @name Promise */ function Promise(resolver, handler) { this._handler = resolver === Handler ? handler : init(resolver); } /** * Run the supplied resolver * @param resolver * @returns {Pending} */ function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * @deprecated * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } } // Creation Promise.resolve = resolve; Promise.reject = reject; Promise.never = never; Promise._defer = defer; Promise._handler = getHandler; /** * Returns a trusted promise. If x is already a trusted promise, it is * returned, otherwise returns a new trusted Promise which follows x. * @param {*} x * @return {Promise} promise */ function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); } /** * Return a reject promise with x as its reason (x is used verbatim) * @param {*} x * @returns {Promise} rejected promise */ function reject(x) { return new Promise(Handler, new Async(new Rejected(x))); } /** * Return a promise that remains pending forever * @returns {Promise} forever-pending promise. */ function never() { return foreverPendingPromise; // Should be frozen } /** * Creates an internal {promise, resolver} pair * @private * @returns {Promise} */ function defer() { return new Promise(Handler, new Pending()); } // Transformation and flow control /** * Transform this promise's fulfillment value, returning a new Promise * for the transformed result. If the promise cannot be fulfilled, onRejected * is called with the reason. onProgress *may* be called with updates toward * this promise's fulfillment. * @param {function=} onFulfilled fulfillment handler * @param {function=} onRejected rejection handler * @param {function=} onProgress @deprecated progress handler * @return {Promise} new promise */ Promise.prototype.then = function(onFulfilled, onRejected, onProgress) { var parent = this._handler; var state = parent.join().state(); if ((typeof onFulfilled !== 'function' && state > 0) || (typeof onRejected !== 'function' && state < 0)) { // Short circuit: value will not change, simply share handler return new this.constructor(Handler, parent); } var p = this._beget(); var child = p._handler; parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress); return p; }; /** * If this promise cannot be fulfilled due to an error, call onRejected to * handle the error. Shortcut for .then(undefined, onRejected) * @param {function?} onRejected * @return {Promise} */ Promise.prototype['catch'] = function(onRejected) { return this.then(void 0, onRejected); }; /** * Creates a new, pending promise of the same type as this promise * @private * @returns {Promise} */ Promise.prototype._beget = function() { return begetFrom(this._handler, this.constructor); }; function begetFrom(parent, Promise) { var child = new Pending(parent.receiver, parent.join().context); return new Promise(Handler, child); } // Array combinators Promise.all = all; Promise.race = race; Promise._traverse = traverse; /** * Return a promise that will fulfill when all promises in the * input array have fulfilled, or will reject when one of the * promises rejects. * @param {array} promises array of promises * @returns {Promise} promise for array of fulfillment values */ function all(promises) { return traverseWith(snd, null, promises); } /** * Array<Promise<X>> -> Promise<Array<f(X)>> * @private * @param {function} f function to apply to each promise's value * @param {Array} promises array of promises * @returns {Promise} promise for transformed values */ function traverse(f, promises) { return traverseWith(tryCatch2, f, promises); } function traverseWith(tryMap, f, promises) { var handler = typeof f === 'function' ? mapAt : settleAt; var resolver = new Pending(); var pending = promises.length >>> 0; var results = new Array(pending); for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { --pending; continue; } traverseAt(promises, handler, i, x, resolver); } if(pending === 0) { resolver.become(new Fulfilled(results)); } return new Promise(Handler, resolver); function mapAt(i, x, resolver) { if(!resolver.resolved) { traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver); } } function settleAt(i, x, resolver) { results[i] = x; if(--pending === 0) { resolver.become(new Fulfilled(results)); } } } function traverseAt(promises, handler, i, x, resolver) { if (maybeThenable(x)) { var h = getHandlerMaybeThenable(x); var s = h.state(); if (s === 0) { h.fold(handler, i, void 0, resolver); } else if (s > 0) { handler(i, h.value, resolver); } else { resolver.become(h); visitRemaining(promises, i+1, h); } } else { handler(i, x, resolver); } } Promise._visitRemaining = visitRemaining; function visitRemaining(promises, start, handler) { for(var i=start; i<promises.length; ++i) { markAsHandled(getHandler(promises[i]), handler); } } function markAsHandled(h, handler) { if(h === handler) { return; } var s = h.state(); if(s === 0) { h.visit(h, void 0, h._unreport); } else if(s < 0) { h._unreport(); } } /** * Fulfill-reject competitive race. Return a promise that will settle * to the same state as the earliest input promise to settle. * * WARNING: The ES6 Promise spec requires that race()ing an empty array * must return a promise that is pending forever. This implementation * returns a singleton forever-pending promise, the same singleton that is * returned by Promise.never(), thus can be checked with === * * @param {array} promises array of promises to race * @returns {Promise} if input is non-empty, a promise that will settle * to the same outcome as the earliest input promise to settle. if empty * is empty, returns a promise that will never settle. */ function race(promises) { if(typeof promises !== 'object' || promises === null) { return reject(new TypeError('non-iterable passed to race()')); } // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. return promises.length === 0 ? never() : promises.length === 1 ? resolve(promises[0]) : runRace(promises); } function runRace(promises) { var resolver = new Pending(); var i, x, h; for(i=0; i<promises.length; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { continue; } h = getHandler(x); if(h.state() !== 0) { resolver.become(h); visitRemaining(promises, i+1, h); break; } else { h.visit(resolver, resolver.resolve, resolver.reject); } } return new Promise(Handler, resolver); } // Promise internals // Below this, everything is @private /** * Get an appropriate handler for x, without checking for cycles * @param {*} x * @returns {object} handler */ function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); } /** * Get a handler for thenable x. * NOTE: You must only call this if maybeThenable(x) == true * @param {object|function|Promise} x * @returns {object} handler */ function getHandlerMaybeThenable(x) { return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x); } /** * Get a handler for potentially untrusted thenable x * @param {*} x * @returns {object} handler */ function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } } /** * Handler for a promise that is pending forever * @constructor */ function Handler() {} Handler.prototype.when = Handler.prototype.become = Handler.prototype.notify // deprecated = Handler.prototype.fail = Handler.prototype._unreport = Handler.prototype._report = noop; Handler.prototype._state = 0; Handler.prototype.state = function() { return this._state; }; /** * Recursively collapse handler chain to find the handler * nearest to the fully resolved value. * @returns {object} handler nearest the fully resolved value */ Handler.prototype.join = function() { var h = this; while(h.handler !== void 0) { h = h.handler; } return h; }; Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) { this.when({ resolver: to, receiver: receiver, fulfilled: fulfilled, rejected: rejected, progress: progress }); }; Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) { this.chain(failIfRejected, receiver, fulfilled, rejected, progress); }; Handler.prototype.fold = function(f, z, c, to) { this.when(new Fold(f, z, c, to)); }; /** * Handler that invokes fail() on any handler it becomes * @constructor */ function FailIfRejected() {} inherit(Handler, FailIfRejected); FailIfRejected.prototype.become = function(h) { h.fail(); }; var failIfRejected = new FailIfRejected(); /** * Handler that manages a queue of consumers waiting on a pending promise * @constructor */ function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; } inherit(Handler, Pending); Pending.prototype._state = 0; Pending.prototype.resolve = function(x) { this.become(getHandler(x)); }; Pending.prototype.reject = function(x) { if(this.resolved) { return; } this.become(new Rejected(x)); }; Pending.prototype.join = function() { if (!this.resolved) { return this; } var h = this; while (h.handler !== void 0) { h = h.handler; if (h === this) { return this.handler = cycle(); } } return h; }; Pending.prototype.run = function() { var q = this.consumers; var handler = this.handler; this.handler = this.handler.join(); this.consumers = void 0; for (var i = 0; i < q.length; ++i) { handler.when(q[i]); } }; Pending.prototype.become = function(handler) { if(this.resolved) { return; } this.resolved = true; this.handler = handler; if(this.consumers !== void 0) { tasks.enqueue(this); } if(this.context !== void 0) { handler._report(this.context); } }; Pending.prototype.when = function(continuation) { if(this.resolved) { tasks.enqueue(new ContinuationTask(continuation, this.handler)); } else { if(this.consumers === void 0) { this.consumers = [continuation]; } else { this.consumers.push(continuation); } } }; /** * @deprecated */ Pending.prototype.notify = function(x) { if(!this.resolved) { tasks.enqueue(new ProgressTask(x, this)); } }; Pending.prototype.fail = function(context) { var c = typeof context === 'undefined' ? this.context : context; this.resolved && this.handler.join().fail(c); }; Pending.prototype._report = function(context) { this.resolved && this.handler.join()._report(context); }; Pending.prototype._unreport = function() { this.resolved && this.handler.join()._unreport(); }; /** * Wrap another handler and force it into a future stack * @param {object} handler * @constructor */ function Async(handler) { this.handler = handler; } inherit(Handler, Async); Async.prototype.when = function(continuation) { tasks.enqueue(new ContinuationTask(continuation, this)); }; Async.prototype._report = function(context) { this.join()._report(context); }; Async.prototype._unreport = function() { this.join()._unreport(); }; /** * Handler that wraps an untrusted thenable and assimilates it in a future stack * @param {function} then * @param {{then: function}} thenable * @constructor */ function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); } inherit(Pending, Thenable); /** * Handler for a fulfilled promise * @param {*} x fulfillment value * @constructor */ function Fulfilled(x) { Promise.createContext(this); this.value = x; } inherit(Handler, Fulfilled); Fulfilled.prototype._state = 1; Fulfilled.prototype.fold = function(f, z, c, to) { runContinuation3(f, z, this, c, to); }; Fulfilled.prototype.when = function(cont) { runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver); }; var errorId = 0; /** * Handler for a rejected promise * @param {*} x rejection reason * @constructor */ function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); } inherit(Handler, Rejected); Rejected.prototype._state = -1; Rejected.prototype.fold = function(f, z, c, to) { to.become(this); }; Rejected.prototype.when = function(cont) { if(typeof cont.rejected === 'function') { this._unreport(); } runContinuation1(cont.rejected, this, cont.receiver, cont.resolver); }; Rejected.prototype._report = function(context) { tasks.afterQueue(new ReportTask(this, context)); }; Rejected.prototype._unreport = function() { if(this.handled) { return; } this.handled = true; tasks.afterQueue(new UnreportTask(this)); }; Rejected.prototype.fail = function(context) { this.reported = true; emitRejection('unhandledRejection', this); Promise.onFatalRejection(this, context === void 0 ? this.context : context); }; function ReportTask(rejection, context) { this.rejection = rejection; this.context = context; } ReportTask.prototype.run = function() { if(!this.rejection.handled && !this.rejection.reported) { this.rejection.reported = true; emitRejection('unhandledRejection', this.rejection) || Promise.onPotentiallyUnhandledRejection(this.rejection, this.context); } }; function UnreportTask(rejection) { this.rejection = rejection; } UnreportTask.prototype.run = function() { if(this.rejection.reported) { emitRejection('rejectionHandled', this.rejection) || Promise.onPotentiallyUnhandledRejectionHandled(this.rejection); } }; // Unhandled rejection hooks // By default, everything is a noop Promise.createContext = Promise.enterContext = Promise.exitContext = Promise.onPotentiallyUnhandledRejection = Promise.onPotentiallyUnhandledRejectionHandled = Promise.onFatalRejection = noop; // Errors and singletons var foreverPendingHandler = new Handler(); var foreverPendingPromise = new Promise(Handler, foreverPendingHandler); function cycle() { return new Rejected(new TypeError('Promise cycle')); } // Task runners /** * Run a single consumer * @constructor */ function ContinuationTask(continuation, handler) { this.continuation = continuation; this.handler = handler; } ContinuationTask.prototype.run = function() { this.handler.join().when(this.continuation); }; /** * Run a queue of progress handlers * @constructor */ function ProgressTask(value, handler) { this.handler = handler; this.value = value; } ProgressTask.prototype.run = function() { var q = this.handler.consumers; if(q === void 0) { return; } for (var c, i = 0; i < q.length; ++i) { c = q[i]; runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver); } }; /** * Assimilate a thenable, sending it's value to resolver * @param {function} then * @param {object|function} thenable * @param {object} resolver * @constructor */ function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; } AssimilateTask.prototype.run = function() { var h = this.resolver; tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify); function _resolve(x) { h.resolve(x); } function _reject(x) { h.reject(x); } function _notify(x) { h.notify(x); } }; function tryAssimilate(then, thenable, resolve, reject, notify) { try { then.call(thenable, resolve, reject, notify); } catch (e) { reject(e); } } /** * Fold a handler value with z * @constructor */ function Fold(f, z, c, to) { this.f = f; this.z = z; this.c = c; this.to = to; this.resolver = failIfRejected; this.receiver = this; } Fold.prototype.fulfilled = function(x) { this.f.call(this.c, this.z, x, this.to); }; Fold.prototype.rejected = function(x) { this.to.reject(x); }; Fold.prototype.progress = function(x) { this.to.notify(x); }; // Other helpers /** * @param {*} x * @returns {boolean} true iff x is a trusted Promise */ function isPromise(x) { return x instanceof Promise; } /** * Test just enough to rule out primitives, in order to take faster * paths in some code * @param {*} x * @returns {boolean} false iff x is guaranteed *not* to be a thenable */ function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function runContinuation1(f, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject(f, h.value, receiver, next); Promise.exitContext(); } function runContinuation3(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject3(f, x, h.value, receiver, next); Promise.exitContext(); } /** * @deprecated */ function runNotify(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.notify(x); } Promise.enterContext(h); tryCatchReturn(f, x, receiver, next); Promise.exitContext(); } function tryCatch2(f, a, b) { try { return f(a, b); } catch(e) { return reject(e); } } /** * Return f.call(thisArg, x), or if it throws return a rejected promise for * the thrown exception */ function tryCatchReject(f, x, thisArg, next) { try { next.become(getHandler(f.call(thisArg, x))); } catch(e) { next.become(new Rejected(e)); } } /** * Same as above, but includes the extra argument parameter. */ function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } } /** * @deprecated * Return f.call(thisArg, x), or if it throws, *return* the exception */ function tryCatchReturn(f, x, thisArg, next) { try { next.notify(f.call(thisArg, x)); } catch(e) { next.notify(e); } } function inherit(Parent, Child) { Child.prototype = objectCreate(Parent.prototype); Child.prototype.constructor = Child; } function snd(x, y) { return y; } function noop() {} function initEmitRejection() { /*global process, self, CustomEvent*/ if(typeof process !== 'undefined' && process !== null && typeof process.emit === 'function') { // Returning falsy here means to call the default // onPotentiallyUnhandledRejection API. This is safe even in // browserify since process.emit always returns falsy in browserify: // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46 return function(type, rejection) { return type === 'unhandledRejection' ? process.emit(type, rejection.value, rejection) : process.emit(type, rejection); }; } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') { return (function(noop, self, CustomEvent) { var hasCustomEvent = false; try { var ev = new CustomEvent('unhandledRejection'); hasCustomEvent = ev instanceof CustomEvent; } catch (e) {} return !hasCustomEvent ? noop : function(type, rejection) { var ev = new CustomEvent(type, { detail: { reason: rejection.value, key: rejection }, bubbles: false, cancelable: true }); return !self.dispatchEvent(ev); }; }(noop, self, CustomEvent)); } return noop; } return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); }).call(this,_dereq_('_process')) },{"_process":75}],132:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return { pending: toPendingState, fulfilled: toFulfilledState, rejected: toRejectedState, inspect: inspect }; function toPendingState() { return { state: 'pending' }; } function toRejectedState(e) { return { state: 'rejected', reason: e }; } function toFulfilledState(x) { return { state: 'fulfilled', value: x }; } function inspect(handler) { var state = handler.state(); return state === 0 ? toPendingState() : state > 0 ? toFulfilledState(handler.value) : toRejectedState(handler.value); } }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],133:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** * Promises/A+ and when() implementation * when is part of the cujoJS family of libraries (http://cujojs.com/) * @author Brian Cavalier * @author John Hann */ (function(define) { 'use strict'; define(function (_dereq_) { var timed = _dereq_('./lib/decorators/timed'); var array = _dereq_('./lib/decorators/array'); var flow = _dereq_('./lib/decorators/flow'); var fold = _dereq_('./lib/decorators/fold'); var inspect = _dereq_('./lib/decorators/inspect'); var generate = _dereq_('./lib/decorators/iterate'); var progress = _dereq_('./lib/decorators/progress'); var withThis = _dereq_('./lib/decorators/with'); var unhandledRejection = _dereq_('./lib/decorators/unhandledRejection'); var TimeoutError = _dereq_('./lib/TimeoutError'); var Promise = [array, flow, fold, generate, progress, inspect, withThis, timed, unhandledRejection] .reduce(function(Promise, feature) { return feature(Promise); }, _dereq_('./lib/Promise')); var apply = _dereq_('./lib/apply')(Promise); // Public API when.promise = promise; // Create a pending promise when.resolve = Promise.resolve; // Create a resolved promise when.reject = Promise.reject; // Create a rejected promise when.lift = lift; // lift a function to return promises when['try'] = attempt; // call a function and return a promise when.attempt = attempt; // alias for when.try when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises when.join = join; // Join 2 or more promises when.all = all; // Resolve a list of promises when.settle = settle; // Settle a list of promises when.any = lift(Promise.any); // One-winner race when.some = lift(Promise.some); // Multi-winner race when.race = lift(Promise.race); // First-to-settle race when.map = map; // Array.map() for promises when.filter = filter; // Array.filter() for promises when.reduce = lift(Promise.reduce); // Array.reduce() for promises when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable when.Promise = Promise; // Promise constructor when.defer = defer; // Create a {promise, resolve, reject} tuple // Error types when.TimeoutError = TimeoutError; /** * Get a trusted promise for x, or by transforming x with onFulfilled * * @param {*} x * @param {function?} onFulfilled callback to be called when x is * successfully fulfilled. If promiseOrValue is an immediate value, callback * will be invoked immediately. * @param {function?} onRejected callback to be called when x is * rejected. * @param {function?} onProgress callback to be called when progress updates * are issued for x. @deprecated * @returns {Promise} a new promise that will fulfill with the return * value of callback or errback or the completion value of promiseOrValue if * callback and/or errback is not supplied. */ function when(x, onFulfilled, onRejected, onProgress) { var p = Promise.resolve(x); if (arguments.length < 2) { return p; } return p.then(onFulfilled, onRejected, onProgress); } /** * Creates a new promise whose fate is determined by resolver. * @param {function} resolver function(resolve, reject, notify) * @returns {Promise} promise whose fate is determine by resolver */ function promise(resolver) { return new Promise(resolver); } /** * Lift the supplied function, creating a version of f that returns * promises, and accepts promises as arguments. * @param {function} f * @returns {Function} version of f that returns promises */ function lift(f) { return function() { for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) { a[i] = arguments[i]; } return apply(f, this, a); }; } /** * Call f in a future turn, with the supplied args, and return a promise * for the result. * @param {function} f * @returns {Promise} */ function attempt(f /*, args... */) { /*jshint validthis:true */ for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) { a[i] = arguments[i+1]; } return apply(f, this, a); } /** * Creates a {promise, resolver} pair, either or both of which * may be given out safely to consumers. * @return {{promise: Promise, resolve: function, reject: function, notify: function}} */ function defer() { return new Deferred(); } function Deferred() { var p = Promise._defer(); function resolve(x) { p._handler.resolve(x); } function reject(x) { p._handler.reject(x); } function notify(x) { p._handler.notify(x); } this.promise = p; this.resolve = resolve; this.reject = reject; this.notify = notify; this.resolver = { resolve: resolve, reject: reject, notify: notify }; } /** * Determines if x is promise-like, i.e. a thenable object * NOTE: Will return true for *any thenable object*, and isn't truly * safe, since it may attempt to access the `then` property of x (i.e. * clever/malicious getters may do weird things) * @param {*} x anything * @returns {boolean} true if x is promise-like */ function isPromiseLike(x) { return x && typeof x.then === 'function'; } /** * Return a promise that will resolve only once all the supplied arguments * have resolved. The resolution value of the returned promise will be an array * containing the resolution values of each of the arguments. * @param {...*} arguments may be a mix of promises and values * @returns {Promise} */ function join(/* ...promises */) { return Promise.all(arguments); } /** * Return a promise that will fulfill once all input promises have * fulfilled, or reject when any one input promise rejects. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} */ function all(promises) { return when(promises, Promise.all); } /** * Return a promise that will always fulfill with an array containing * the outcome states of all input promises. The returned promise * will only reject if `promises` itself is a rejected promise. * @param {array|Promise} promises array (or promise for an array) of promises * @returns {Promise} promise for array of settled state descriptors */ function settle(promises) { return when(promises, Promise.settle); } /** * Promise-aware array map function, similar to `Array.prototype.map()`, * but input array may contain promises or values. * @param {Array|Promise} promises array of anything, may contain promises and values * @param {function(x:*, index:Number):*} mapFunc map function which may * return a promise or value * @returns {Promise} promise that will fulfill with an array of mapped values * or reject if any input promise rejects. */ function map(promises, mapFunc) { return when(promises, function(promises) { return Promise.map(promises, mapFunc); }); } /** * Filter the provided array of promises using the provided predicate. Input may * contain promises and values * @param {Array|Promise} promises array of promises and values * @param {function(x:*, index:Number):boolean} predicate filtering predicate. * Must return truthy (or promise for truthy) for items to retain. * @returns {Promise} promise that will fulfill with an array containing all items * for which predicate returned truthy. */ function filter(promises, predicate) { return when(promises, function(promises) { return Promise.filter(promises, predicate); }); } return when; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }); },{"./lib/Promise":116,"./lib/TimeoutError":118,"./lib/apply":119,"./lib/decorators/array":120,"./lib/decorators/flow":121,"./lib/decorators/fold":122,"./lib/decorators/inspect":123,"./lib/decorators/iterate":124,"./lib/decorators/progress":125,"./lib/decorators/timed":126,"./lib/decorators/unhandledRejection":127,"./lib/decorators/with":128}],134:[function(_dereq_,module,exports){ /* * Copyright 2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { return { /** * Find objects within a graph the contain a property of a certain name. * * NOTE: this method will not discover object graph cycles. * * @param {*} obj object to search on * @param {string} prop name of the property to search for * @param {Function} callback function to receive the found properties and their parent */ findProperties: function findProperties(obj, prop, callback) { if (typeof obj !== 'object' || obj === null) { return; } if (prop in obj) { callback(obj[prop], obj, prop); } Object.keys(obj).forEach(function (key) { findProperties(obj[key], prop, callback); }); } }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],135:[function(_dereq_,module,exports){ /* * Copyright 2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var when; when = _dereq_('when'); /** * Create a promise whose work is started only when a handler is registered. * * The work function will be invoked at most once. Thrown values will result * in promise rejection. * * @param {Function} work function whose ouput is used to resolve the * returned promise. * @returns {Promise} a lazy promise */ function lazyPromise(work) { var defer, started, resolver, promise, then; defer = when.defer(); started = false; resolver = defer.resolver; promise = defer.promise; then = promise.then; promise.then = function () { if (!started) { started = true; when.attempt(work).then(resolver.resolve, resolver.reject); } return then.apply(promise, arguments); }; return promise; } return lazyPromise; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"when":133}],136:[function(_dereq_,module,exports){ /* * Copyright 2012-2013 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; // derived from dojo.mixin define(function (/* require */) { var empty = {}; /** * Mix the properties from the source object into the destination object. * When the same property occurs in more then one object, the right most * value wins. * * @param {Object} dest the object to copy properties to * @param {Object} sources the objects to copy properties from. May be 1 to N arguments, but not an Array. * @return {Object} the destination object */ function mixin(dest /*, sources... */) { var i, l, source, name; if (!dest) { dest = {}; } for (i = 1, l = arguments.length; i < l; i += 1) { source = arguments[i]; for (name in source) { if (!(name in dest) || (dest[name] !== source[name] && (!(name in empty) || empty[name] !== source[name]))) { dest[name] = source[name]; } } } return dest; // Object } return mixin; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],137:[function(_dereq_,module,exports){ /* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { /** * Normalize HTTP header names using the pseudo camel case. * * For example: * content-type -> Content-Type * accepts -> Accepts * x-custom-header-name -> X-Custom-Header-Name * * @param {string} name the raw header name * @return {string} the normalized header name */ function normalizeHeaderName(name) { return name.toLowerCase() .split('-') .map(function (chunk) { return chunk.charAt(0).toUpperCase() + chunk.slice(1); }) .join('-'); } return normalizeHeaderName; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],138:[function(_dereq_,module,exports){ /* * Copyright 2014-2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (_dereq_) { var when = _dereq_('when'), normalizeHeaderName = _dereq_('./normalizeHeaderName'); function property(promise, name) { return promise.then( function (value) { return value && value[name]; }, function (value) { return when.reject(value && value[name]); } ); } /** * Obtain the response entity * * @returns {Promise} for the response entity */ function entity() { /*jshint validthis:true */ return property(this, 'entity'); } /** * Obtain the response status * * @returns {Promise} for the response status */ function status() { /*jshint validthis:true */ return property(property(this, 'status'), 'code'); } /** * Obtain the response headers map * * @returns {Promise} for the response headers map */ function headers() { /*jshint validthis:true */ return property(this, 'headers'); } /** * Obtain a specific response header * * @param {String} headerName the header to retrieve * @returns {Promise} for the response header's value */ function header(headerName) { /*jshint validthis:true */ headerName = normalizeHeaderName(headerName); return property(this.headers(), headerName); } /** * Follow a related resource * * The relationship to follow may be define as a plain string, an object * with the rel and params, or an array containing one or more entries * with the previous forms. * * Examples: * response.follow('next') * * response.follow({ rel: 'next', params: { pageSize: 100 } }) * * response.follow([ * { rel: 'items', params: { projection: 'noImages' } }, * 'search', * { rel: 'findByGalleryIsNull', params: { projection: 'noImages' } }, * 'items' * ]) * * @param {String|Object|Array} rels one, or more, relationships to follow * @returns ResponsePromise<Response> related resource */ function follow(rels) { /*jshint validthis:true */ rels = [].concat(rels); return make(when.reduce(rels, function (response, rel) { if (typeof rel === 'string') { rel = { rel: rel }; } if (typeof response.entity.clientFor !== 'function') { throw new Error('Hypermedia response expected'); } var client = response.entity.clientFor(rel.rel); return client({ params: rel.params }); }, this)); } /** * Wrap a Promise as an ResponsePromise * * @param {Promise<Response>} promise the promise for an HTTP Response * @returns {ResponsePromise<Response>} wrapped promise for Response with additional helper methods */ function make(promise) { promise.status = status; promise.headers = headers; promise.header = header; promise.entity = entity; promise.follow = follow; return promise; } function responsePromise() { return make(when.apply(when, arguments)); } responsePromise.make = make; responsePromise.reject = function (val) { return make(when.reject(val)); }; responsePromise.promise = function (func) { return make(when.promise(func)); }; return responsePromise; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./normalizeHeaderName":137,"when":133}],139:[function(_dereq_,module,exports){ /* * Copyright 2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; define(function (/* require */) { var charMap; charMap = (function () { var strings = { alpha: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', digit: '0123456789' }; strings.genDelims = ':/?#[]@'; strings.subDelims = '!$&\'()*+,;='; strings.reserved = strings.genDelims + strings.subDelims; strings.unreserved = strings.alpha + strings.digit + '-._~'; strings.url = strings.reserved + strings.unreserved; strings.scheme = strings.alpha + strings.digit + '+-.'; strings.userinfo = strings.unreserved + strings.subDelims + ':'; strings.host = strings.unreserved + strings.subDelims; strings.port = strings.digit; strings.pchar = strings.unreserved + strings.subDelims + ':@'; strings.segment = strings.pchar; strings.path = strings.segment + '/'; strings.query = strings.pchar + '/?'; strings.fragment = strings.pchar + '/?'; return Object.keys(strings).reduce(function (charMap, set) { charMap[set] = strings[set].split('').reduce(function (chars, myChar) { chars[myChar] = true; return chars; }, {}); return charMap; }, {}); }()); function encode(str, allowed) { if (typeof str !== 'string') { throw new Error('String required for URL encoding'); } return str.split('').map(function (myChar) { if (allowed.hasOwnProperty(myChar)) { return myChar; } var code = myChar.charCodeAt(0); if (code <= 127) { return '%' + code.toString(16).toUpperCase(); } else { return encodeURIComponent(myChar).toUpperCase(); } }).join(''); } function makeEncoder(allowed) { allowed = allowed || charMap.unreserved; return function (str) { return encode(str, allowed); }; } function decode(str) { return decodeURIComponent(str); } return { /* * Decode URL encoded strings * * @param {string} URL encoded string * @returns {string} URL decoded string */ decode: decode, /* * URL encode a string * * All but alpha-numerics and a very limited set of punctuation - . _ ~ are * encoded. * * @param {string} string to encode * @returns {string} URL encoded string */ encode: makeEncoder(), /* * URL encode a URL * * All character permitted anywhere in a URL are left unencoded even * if that character is not permitted in that portion of a URL. * * Note: This method is typically not what you want. * * @param {string} string to encode * @returns {string} URL encoded string */ encodeURL: makeEncoder(charMap.url), /* * URL encode the scheme portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeScheme: makeEncoder(charMap.scheme), /* * URL encode the user info portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeUserInfo: makeEncoder(charMap.userinfo), /* * URL encode the host portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeHost: makeEncoder(charMap.host), /* * URL encode the port portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodePort: makeEncoder(charMap.port), /* * URL encode a path segment portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodePathSegment: makeEncoder(charMap.segment), /* * URL encode the path portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodePath: makeEncoder(charMap.path), /* * URL encode the query portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeQuery: makeEncoder(charMap.query), /* * URL encode the fragment portion of a URL * * @param {string} string to encode * @returns {string} URL encoded string */ encodeFragment: makeEncoder(charMap.fragment) }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{}],140:[function(_dereq_,module,exports){ /* * Copyright 2015 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; define(function (_dereq_) { var uriEncoder, operations, prefixRE; uriEncoder = _dereq_('./uriEncoder'); prefixRE = /^([^:]*):([0-9]+)$/; operations = { '': { first: '', separator: ',', named: false, empty: '', encoder: uriEncoder.encode }, '+': { first: '', separator: ',', named: false, empty: '', encoder: uriEncoder.encodeURL }, '#': { first: '#', separator: ',', named: false, empty: '', encoder: uriEncoder.encodeURL }, '.': { first: '.', separator: '.', named: false, empty: '', encoder: uriEncoder.encode }, '/': { first: '/', separator: '/', named: false, empty: '', encoder: uriEncoder.encode }, ';': { first: ';', separator: ';', named: true, empty: '', encoder: uriEncoder.encode }, '?': { first: '?', separator: '&', named: true, empty: '=', encoder: uriEncoder.encode }, '&': { first: '&', separator: '&', named: true, empty: '=', encoder: uriEncoder.encode }, '=': { reserved: true }, ',': { reserved: true }, '!': { reserved: true }, '@': { reserved: true }, '|': { reserved: true } }; function apply(operation, expression, params) { /*jshint maxcomplexity:11 */ return expression.split(',').reduce(function (result, variable) { var opts, value; opts = {}; if (variable.slice(-1) === '*') { variable = variable.slice(0, -1); opts.explode = true; } if (prefixRE.test(variable)) { var prefix = prefixRE.exec(variable); variable = prefix[1]; opts.maxLength = parseInt(prefix[2]); } variable = uriEncoder.decode(variable); value = params[variable]; if (value === undef || value === null) { return result; } if (Array.isArray(value)) { result += value.reduce(function (result, value) { if (result.length) { result += opts.explode ? operation.separator : ','; if (operation.named && opts.explode) { result += operation.encoder(variable); result += value.length ? '=' : operation.empty; } } else { result += operation.first; if (operation.named) { result += operation.encoder(variable); result += value.length ? '=' : operation.empty; } } result += operation.encoder(value); return result; }, ''); } else if (typeof value === 'object') { result += Object.keys(value).reduce(function (result, name) { if (result.length) { result += opts.explode ? operation.separator : ','; } else { result += operation.first; if (operation.named && !opts.explode) { result += operation.encoder(variable); result += value[name].length ? '=' : operation.empty; } } result += operation.encoder(name); result += opts.explode ? '=' : ','; result += operation.encoder(value[name]); return result; }, ''); } else { value = String(value); if (opts.maxLength) { value = value.slice(0, opts.maxLength); } result += result.length ? operation.separator : operation.first; if (operation.named) { result += operation.encoder(variable); result += value.length ? '=' : operation.empty; } result += operation.encoder(value); } return result; }, ''); } function expandExpression(expression, params) { var operation; operation = operations[expression.slice(0,1)]; if (operation) { expression = expression.slice(1); } else { operation = operations['']; } if (operation.reserved) { throw new Error('Reserved expression operations are not supported'); } return apply(operation, expression, params); } function expandTemplate(template, params) { var start, end, uri; uri = ''; end = 0; while (true) { start = template.indexOf('{', end); if (start === -1) { // no more expressions uri += template.slice(end); break; } uri += template.slice(end, start); end = template.indexOf('}', start) + 1; uri += expandExpression(template.slice(start + 1, end - 1), params); } return uri; } return { /** * Expand a URI Template with parameters to form a URI. * * Full implementation (level 4) of rfc6570. * @see https://tools.ietf.org/html/rfc6570 * * @param {string} template URI template * @param {Object} [params] params to apply to the template durring expantion * @returns {string} expanded URI */ expand: expandTemplate }; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); } // Boilerplate for AMD and Node )); },{"./uriEncoder":139}]},{},[1]);
packages/linkify-react/src/linkify-react.js
SoapBox/jQuery-linkify
import * as React from 'react'; import { tokenize, Options } from 'linkifyjs'; /** * Given a string, converts to an array of valid React components * (which may include strings) * @param {string} str * @param {any} opts * @returns {React.ReactNodeArray} */ function stringToElements(str, opts) { const tokens = tokenize(str); const elements = []; let linkId = 0; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; if (token.t === 'nl' && opts.nl2br) { elements.push(React.createElement('br', {key: `linkified-${++linkId}`})); continue; } else if (!token.isLink || !opts.check(token)) { // Regular text elements.push(token.toString()); continue; } const { formatted, formattedHref, tagName, className, target, rel, attributes } = opts.resolve(token); const props = { key: `linkified-${++linkId}`, href: formattedHref }; if (className) { props.className = className; } if (target) { props.target = target; } if (rel) { props.rel = rel; } // Build up additional attributes // Support for events via attributes hash if (attributes) { for (var attr in attributes) { props[attr] = attributes[attr]; } } elements.push(React.createElement(tagName, props, formatted)); } return elements; } // Recursively linkify the contents of the given React Element instance /** * @template P * @template {string | React.JSXElementConstructor<P>} T * @param {React.ReactElement<P, T>} element * @param {Object} opts * @param {number} elementId * @returns {React.ReactElement<P, T>} */ function linkifyReactElement(element, opts, elementId = 0) { if (React.Children.count(element.props.children) === 0) { // No need to clone if the element had no children return element; } const children = []; React.Children.forEach(element.props.children, (child) => { if (typeof child === 'string') { // ensure that we always generate unique element IDs for keys elementId = elementId + 1; children.push(...stringToElements(child, opts)); } else if (React.isValidElement(child)) { if (typeof child.type === 'string' && opts.ignoreTags.indexOf(child.type.toUpperCase()) >= 0 ) { // Don't linkify this element children.push(child); } else { children.push(linkifyReactElement(child, opts, ++elementId)); } } else { // Unknown element type, just push children.push(child); } }); // Set a default unique key, copy over remaining props const newProps = { key: `linkified-element-${elementId}` }; for (const prop in element.props) { newProps[prop] = element.props[prop]; } return React.cloneElement(element, newProps, children); } /** * @template P * @template {string | React.JSXElementConstructor<P>} T * @param {P & { tagName?: T, options?: any, children?: React.ReactNode}} props * @returns {React.ReactElement<P, T>} */ const Linkify = (props) => { // Copy over all non-linkify-specific props const newProps = { key: 'linkified-element-wrapper' }; for (const prop in props) { if (prop !== 'options' && prop !== 'tagName' && prop !== 'children') { newProps[prop] = props[prop]; } } const opts = new Options(props.options); const tagName = props.tagName || React.Fragment || 'span'; const children = props.children; const element = React.createElement(tagName, newProps, children); return linkifyReactElement(element, opts, 0); }; export default Linkify;
test/components/SidebarLogo.spec.js
datyayu/raji-react
/* eslint no-param-reassign: 0 */ import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import SidebarLogo from '../../client/components/SidebarLogo'; test.beforeEach(t => { t.context.logo = { img: '/assets/logo.svg', text: 'raji', }; }); test('SidebarLogo should use the SidebarLogo class', t => { const { logo } = t.context; const component = shallow(<SidebarLogo {...logo} />); t.true(component.hasClass('SidebarLogo'), 'You need to include the SidebarLogo class'); }); test('SidebarLogo should use the image given', t => { const { logo } = t.context; const component = shallow(<SidebarLogo {...logo} />); const imageUrl = component.render().find('img').attr('src'); t.is(imageUrl, '/assets/logo.svg', 'It should use the image given via `img` prop.'); }); test('SidebarLogo should use the title given', t => { const { logo } = t.context; const component = shallow(<SidebarLogo {...logo} />); const textNode = component.children().first(); t.is(textNode.text(), 'raji', 'It should use the title given via `text` prop.'); }); test('SidebarLogo should use the url given', t => { const { logo } = t.context; const component = shallow(<SidebarLogo url="/test" {...logo} />); const linkUrl = component.props().to; t.is(linkUrl, '/test', 'It should use the link given via `url` prop.'); }); test('SidebarLogo\'s link should default to home (/) if not url given', t => { const { logo } = t.context; const component = shallow(<SidebarLogo {...logo} />); const linkUrl = component.props().to; t.is(linkUrl, '/', 'It should default to /.'); });
lens-ui/app/components/AboutComponent.js
sushilmohanty/incubator-lens
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; class About extends React.Component { render() { return ( <div className="jumbotron"> <h1>Hey there!</h1> <p>Thanks for stopping by.</p> </div> ); } } export default About;
components/TransitionImage/index.js
samuelngs/px
import React, { Component } from 'react'; import { Image, InteractionManager } from 'react-native'; import { SharedView } from 'px/components/Navigation'; export default class TransitionImage extends Component { static defaultProps = { ...Image.defaultProps, name : null, route : null, mask : false, } static propTypes = { ...Image.propTypes, name : React.PropTypes.string.isRequired, route : React.PropTypes.string.isRequired, mask : React.PropTypes.bool, } setNativeProps(props) { this.node && this.node.setNativeProps(props); } render() { const { name, route, ...props } = this.props; return <SharedView ref={n => this.node = n} name={name} containerRouteName={route}> <Image {...props} /> </SharedView> } }
packages/benchmarks/react-inline-styles/client/index.js
A-gambit/CSS-IN-JS-Benchmarks
import ReactDOM from 'react-dom'; import React from 'react'; import App from 'benchmarks-utils'; import Table from './Table'; import './index.html'; ReactDOM.render(<App table={Table} />, document.getElementById('root'));
packages/material-ui-icons/src/SyncProblemTwoTone.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="M3 12c0 2.21.91 4.2 2.36 5.64L3 20h6v-6l-2.24 2.24C5.68 15.15 5 13.66 5 12c0-2.61 1.67-4.83 4-5.65V4.26C5.55 5.15 3 8.27 3 12zm8 5h2v-2h-2v2zM21 4h-6v6l2.24-2.24C18.32 8.85 19 10.34 19 12c0 2.61-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74 0-2.21-.91-4.2-2.36-5.64L21 4zm-10 9h2V7h-2v6z" /></g></React.Fragment> , 'SyncProblemTwoTone');
src/components/CommentSection.js
danielzy95/mechanic-finder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from './CommentSection.css'; import Comment from './Comment'; import CommentForm from './CommentForm'; const CommentSection = ({ className = '', comments = [], onNewComment = c => {} }) => ( <div className={`${styles.root} ${className}`}> <h2>Comentarios ({comments.length})</h2> { comments.map((c, i) => ( <Comment key={i} {...c} /> )) } <h2>Comenta tu Opinion</h2> <CommentForm onSubmit={onNewComment} /> </div> ); CommentSection.propTypes = { className: PropTypes.string, comments: PropTypes.arrayOf(PropTypes.object), onNewComment: PropTypes.func }; export default CommentSection;
ajax/libs/es6-shim/0.19.2/es6-shim.js
thejsj/cdnjs
/*! * https://github.com/paulmillr/es6-shim * @license es6-shim Copyright 2013-2014 by Paul Miller (http://paulmillr.com) * and contributors, MIT License * es6-shim: v0.19.2 * see https://github.com/paulmillr/es6-shim/blob/master/LICENSE * Details and documentation: * https://github.com/paulmillr/es6-shim/ */ (function (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 var defineProperty = function (object, name, value, force) { if (!force && name in object) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; // 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]; defineProperty(object, name, method, false); }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function (prototype, properties) { function Type() {} Type.prototype = prototype; var object = new Type(); if (typeof properties !== 'undefined') { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function (prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); /* jshint notypeof: true */ if (!prototype[$iterator$] && typeof $iterator$ === 'symbol') { // implementations are buggy when $iterator$ is a Symbol prototype[$iterator$] = impl; } }; // 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 (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }, ToLength: function (value) { var len = ES.ToInteger(value); if (len <= 0) { return 0; } // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) { return Number.MAX_SAFE_INTEGER; } return len; }, SameValue: function (a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) { return 1 / a === 1 / b; } return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function (a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function (o) { return ES.TypeIsObject(o) && (o[$iterator$] !== undefined || isArguments(o)); }, GetIterator: function (o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, 'value'); } var it = o[$iterator$](); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function (it) { var result = arguments.length > 1 ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function (C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C['@@create'])) { obj = C['@@create'](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = C.apply(obj, args); return ES.TypeIsObject(result) ? result : obj; } }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function (_) { // length = 1 var points = _slice.call(arguments, 0, arguments.length); var result = []; var next; for (var i = 0, length = points.length; i < length; i++) { next = Number(points[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function (callSite) { // raw.length===1 var substitutions = _slice.call(arguments, 1, arguments.length); var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var raw = ES.ToObject(rawValue, 'bad raw value'); var len = Object.keys(raw).length; var literalsegments = ES.ToLength(len); if (literalsegments === 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = raw[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = substitutions[nextKey]; if (next === undefined) { break; } nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); // Firefox 31 reports this function's length as 0 // https://bugzilla.mozilla.org/show_bug.cgi?id=1062484 if (String.fromCodePoint.length !== 1) { var originalFromCodePoint = String.fromCodePoint; defineProperty(String, 'fromCodePoint', function (_) { return originalFromCodePoint.apply(this, arguments); }, true); } 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; } 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 trimRegexp = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); defineProperties(String.prototype, { trim: function () { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + ' to object'); } return String(this).replace(trimRegexp, ''); } }); } // 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; } var ArrayShims = { from: function (iterable) { var mapFn = arguments.length > 1 ? arguments[1] : 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 hasThisArg = arguments.length > 2; var thisArg = hasThisArg ? arguments[2] : undefined; 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; var result, i, value; if (usingIterator) { i = 0; result = ES.IsCallable(this) ? Object(new this()) : []; var it = usingIterator ? ES.GetIterator(list) : null; var iterationValue; do { iterationValue = ES.IteratorNext(it); if (!iterationValue.done) { value = iterationValue.value; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } i += 1; } } while (!iterationValue.done); length = i; } else { length = ES.ToLength(list.length); result = ES.IsCallable(this) ? Object(new this(length)) : new Array(length); for (i = 0; i < length; ++i) { value = list[i]; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } } result.length = length; return result; }, of: function () { return Array.from(arguments); } }; defineProperties(Array, ArrayShims); var arrayFromSwallowsNegativeLengths = function () { try { return Array.from({ length: -1 }).length === 0; } catch (e) { return false; } }; // Fixes a Firefox bug in v32 // https://bugzilla.mozilla.org/show_bug.cgi?id=1063993 if (!arrayFromSwallowsNegativeLengths()) { defineProperty(Array, 'from', ArrayShims.from, true); } // 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 (!(this instanceof ArrayIterator)) { 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); var ArrayPrototypeShims = { copyWithin: function (target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = end === undefined ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty.call(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function (value) { var start = arguments.length > 1 ? arguments[1] : undefined; var end = arguments.length > 2 ? arguments[2] : undefined; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(start === undefined ? 0 : start); end = ES.ToInteger(end === undefined ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function find(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++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }, findIndex: function findIndex(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 (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'); } }; // Safari 7.1 defines Array#keys and Array#entries natively, // but the resulting ArrayIterator objects don't have a "next" method. if (Array.prototype.keys && !ES.IsCallable([1].keys().next)) { delete Array.prototype.keys; } if (Array.prototype.entries && !ES.IsCallable([1].entries().next)) { delete Array.prototype.entries; } defineProperties(Array.prototype, ArrayPrototypeShims); addIterator(Array.prototype, function () { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function (value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function (value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function (value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function (value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); // Work around bugs in Array#find and Array#findIndex -- early // implementations skipped holes in sparse arrays. (Note that the // implementations of find/findIndex indirectly use shimmed // methods of Number, so this test has to happen down here.) if (![, 1].find(function (item, idx) { return idx === 0; })) { defineProperty(Array.prototype, 'find', ArrayPrototypeShims.find, true); } if ([, 1].findIndex(function (item, idx) { return idx === 0; }) !== 0) { defineProperty(Array.prototype, 'findIndex', ArrayPrototypeShims.findIndex, true); } if (supportsDescriptors) { defineProperties(Object, { getPropertyDescriptor: function (subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (pd === undefined && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }, getPropertyNames: function (subject) { var result = Object.getOwnPropertyNames(subject); var proto = Object.getPrototypeOf(subject); var addProperty = function (property) { if (result.indexOf(property) === -1) { result.push(property); } }; while (proto !== null) { Object.getOwnPropertyNames(proto).forEach(addProperty); proto = Object.getPrototypeOf(proto); } return result; } }); defineProperties(Object, { // 19.1.3.1 assign: function (target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function (target, source) { return Object.keys(Object(source)).reduce(function (target, key) { target[key] = source[key]; return target; }, target); }); }, is: function (a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function (Object, magic) { var set; var checkArgs = function (O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto === null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null' + proto); } }; var setPrototypeOf = function (O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function (proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; })(Object, '__proto__') }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function () { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function (o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function (o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; })(); } try { Object.keys('foo'); } catch (e) { var originalObjectKeys = Object.keys; Object.keys = function (obj) { return originalObjectKeys(ES.ToObject(obj)); }; } var MathShims = { acosh: function (value) { value = Number(value); if (Number.isNaN(value) || value < 1) { return NaN; } if (value === 1) { return 0; } if (value === Infinity) { return value; } return Math.log(value + Math.sqrt(value * value - 1)); }, asinh: function (value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function (value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) { return -Infinity; } if (value === 1) { return Infinity; } if (value === 0) { return value; } return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function (value) { value = Number(value); if (value === 0) { return value; } var negate = value < 0, result; if (negate) { value = -value; } result = Math.pow(value, 1 / 3); return negate ? -result : result; }, clz32: function (value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function (value) { value = Number(value); if (value === 0) { return 1; } // +0 or -0 if (Number.isNaN(value)) { return NaN; } if (!global_isFinite(value)) { return Infinity; } if (value < 0) { value = -value; } if (value > 21) { return Math.exp(value) / 2; } return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function (value) { value = Number(value); if (value === -Infinity) { return -1; } if (!global_isFinite(value) || value === 0) { return value; } return Math.exp(value) - 1; }, hypot: function (x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function (arg) { var num = Number(arg); if (Number.isNaN(num)) { anyNaN = true; } else if (num === Infinity || num === -Infinity) { anyInfinity = true; } else if (num !== 0) { allZero = false; } if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) { return Infinity; } if (anyNaN) { return NaN; } if (allZero) { return 0; } numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0); return largest * Math.sqrt(sum); }, log2: function (value) { return Math.log(value) * Math.LOG2E; }, log10: function (value) { return Math.log(value) * Math.LOG10E; }, log1p: function (value) { value = Number(value); if (value < -1 || Number.isNaN(value)) { return NaN; } if (value === 0 || value === Infinity) { return value; } if (value === -1) { return -Infinity; } var result = 0; var n = 50; if (value < 0 || value > 1) { return Math.log(1 + value); } for (var i = 1; i < n; i++) { if ((i % 2) === 0) { result -= Math.pow(value, i) / i; } else { result += Math.pow(value, i) / i; } } return result; }, sign: function (value) { var number = +value; if (number === 0) { return number; } if (Number.isNaN(number)) { return number; } return number < 0 ? -1 : 1; }, sinh: function (value) { value = Number(value); if (!global_isFinite(value) || value === 0) { return value; } return (Math.exp(value) - Math.exp(-value)) / 2; }, tanh: function (value) { value = Number(value); if (Number.isNaN(value) || value === 0) { return value; } if (value === Infinity) { return 1; } if (value === -Infinity) { return -1; } return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value)); }, trunc: function (value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function (x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0); }, fround: function (x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function () { var Promise, Promise$prototype; ES.IsPromise = function (promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (promise._status === undefined) { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function (C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function () { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = 'zero-timeout-message'; var setZeroTimeout = function (fn) { timeouts.push(fn); window.postMessage(messageName, '*'); }; var handleMessage = function (event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener('message', handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function () { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function (task) { return P.resolve().then(task); }; }; var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function (task) { setTimeout(task, 0); }); // fallback var triggerPromiseReactions = function (reactions, x) { reactions.forEach(function (reaction) { enqueue(function () { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var updatePromiseFromPotentialThenable = function (x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch (e) { reject(e); } return true; }; var promiseResolutionHandler = function (promise, onFulfilled, onRejected) { return function (x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function (resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (promise._status !== undefined) { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function (resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function (reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; defineProperties(Promise, { '@@create': function (obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: undefined, _result: undefined, _resolveReactions: undefined, _rejectReactions: undefined, _promiseConstructor: undefined }); obj._promiseConstructor = constructor; return obj; } }); var _promiseAllResolver = function (index, values, capability, remaining) { var done = false; return function (x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; Promise.all = function (iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }; Promise.race = function (iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }; Promise.reject = function (reason) { var C = this; var capability = new PromiseCapability(C); var reject = capability.reject; reject(reason); // call with this===undefined return capability.promise; }; Promise.resolve = function (v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolve = capability.resolve; resolve(v); // call with this===undefined return capability.promise; }; Promise.prototype['catch'] = function (onRejected) { return this.then(undefined, onRejected); }; Promise.prototype.then = function (onFulfilled, onRejected) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function (e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function (x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; }; return Promise; })(); // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function (S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, function () {}); return true; } catch (ex) { return false; } }()); var promiseRequiresObjectContext = (function () { try { Promise.call(3, function () {}); } catch (e) { return true; } return false; }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks || !promiseRequiresObjectContext) { globals.Promise = PromiseShim; } // Map and Set require a true ES5 environment // Their fast path also requires that the environment preserve // property insertion order, which is not guaranteed by the spec. var testOrder = function (a) { var b = Object.keys(a.reduce(function (o, k) { o[k] = true; return o; }, {})); return a.join(':') === b.join(':'); }; var preservesInsertionOrder = testOrder(['z', 'a', 'bb']); // some engines (eg, Chrome) only preserve insertion order for string keys var preservesNumericInsertionOrder = testOrder(['z', 1, 'a', '3', 2]); if (supportsDescriptors) { var fastkey = function fastkey(key) { if (!preservesInsertionOrder) { return null; } 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 if (!preservesNumericInsertionOrder) { return 'n' + key; } return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function () { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function () { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function () { var i = this.i, kind = this.kind, head = this.head, result; if (this.i === undefined) { return { value: undefined, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === 'key') { result = i.key; } else if (kind === 'value') { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = undefined; return { value: undefined, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { _head: head, _storage: emptyObject(), _size: 0 }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperties(Map, { '@@create': function (obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; } }); Object.defineProperty(Map.prototype, 'size', { configurable: true, enumerable: false, get: function () { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; } }); defineProperties(Map.prototype, { get: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; return entry ? entry.value : undefined; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } return undefined; }, has: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function (key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; return this; }, 'delete': function (key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function () { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function () { return new MapIterator(this, 'key'); }, values: function () { return new MapIterator(this, 'value'); }, entries: function () { return new MapIterator(this, 'key+value'); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { callback.call(context, entry.value[1], entry.value[0], this); } } }); addIterator(Map.prototype, function () { return this.entries(); }); return Map; })(), Set: (function () { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, _storage: emptyObject() }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperties(SetShim, { '@@create': function (obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; } }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function (k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else if (k.charAt(0) === 'n') { k = +k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Object.defineProperty(SetShim.prototype, 'size', { configurable: true, enumerable: false, get: function () { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; } }); defineProperties(SetShim.prototype, { has: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey] = true; return; } ensureMap(this); this['[[SetData]]'].set(key, key); return this; }, 'delete': function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return delete this._storage[fkey]; } 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) { var m = new M([]); // Firefox 32 is ok with the instantiating the subclass but will // throw when the map is used. m.set(42, 42); return 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> } })();
apps/marketplace/components/Header/DashBoardLink.js
AusDTO/dto-digitalmarketplace-frontend
/* eslint-disable no-nested-ternary */ import React from 'react' import PropTypes from 'prop-types' import { rootPath } from 'marketplace/routes' const DashBoardLink = props => { const { userType, notificationCount } = props return ( <span> {userType === 'buyer' ? ( <a href={`${rootPath}/buyer-dashboard`}>Dashboard</a> ) : userType === 'applicant' ? ( <a href="/sellers/application">Continue application</a> ) : ( <span> <a href="/2/seller-dashboard">Dashboard</a> {notificationCount && notificationCount !== 0 ? <div className="notification">{notificationCount}</div> : ''} </span> )} </span> ) } DashBoardLink.propTypes = { userType: PropTypes.string.isRequired } export default DashBoardLink
files/core-js/0.9.1/library.js
evilangelmd/jsdelivr
/** * Core.js 0.9.1 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(undefined){ 'use strict'; var __e = null, __g = null; /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(2); __webpack_require__(3); __webpack_require__(4); __webpack_require__(5); __webpack_require__(6); __webpack_require__(7); __webpack_require__(8); __webpack_require__(9); __webpack_require__(10); __webpack_require__(11); __webpack_require__(12); __webpack_require__(13); __webpack_require__(14); __webpack_require__(15); __webpack_require__(16); __webpack_require__(17); __webpack_require__(18); __webpack_require__(19); __webpack_require__(20); __webpack_require__(21); __webpack_require__(22); __webpack_require__(23); __webpack_require__(24); __webpack_require__(25); __webpack_require__(26); __webpack_require__(27); __webpack_require__(28); __webpack_require__(29); __webpack_require__(30); __webpack_require__(31); __webpack_require__(32); __webpack_require__(33); __webpack_require__(34); __webpack_require__(35); __webpack_require__(36); __webpack_require__(37); __webpack_require__(38); __webpack_require__(39); __webpack_require__(40); __webpack_require__(41); __webpack_require__(42); __webpack_require__(43); __webpack_require__(44); __webpack_require__(45); __webpack_require__(46); __webpack_require__(47); __webpack_require__(48); __webpack_require__(49); __webpack_require__(50); __webpack_require__(51); __webpack_require__(52); __webpack_require__(53); __webpack_require__(54); __webpack_require__(55); __webpack_require__(56); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , cof = __webpack_require__(58) , $def = __webpack_require__(59) , invoke = __webpack_require__(60) , arrayMethod = __webpack_require__(61) , IE_PROTO = __webpack_require__(62).safe('__proto__') , assert = __webpack_require__(63) , assertObject = assert.obj , ObjectProto = Object.prototype , A = [] , slice = A.slice , indexOf = A.indexOf , classof = cof.classof , has = $.has , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , isFunction = $.isFunction , toObject = $.toObject , toLength = $.toLength , IE8_DOM_DEFINE = false; if(!$.DESC){ try { IE8_DOM_DEFINE = defineProperty(document.createElement('div'), 'x', {get: function(){ return 8; }} ).x == 8; } catch(e){ /* empty */ } $.setDesc = function(O, P, Attributes){ if(IE8_DOM_DEFINE)try { return defineProperty(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; $.getDesc = function(O, P){ if(IE8_DOM_DEFINE)try { return getOwnDescriptor(O, P); } catch(e){ /* empty */ } if(has(O, P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ assertObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $def($def.S + $def.F * !$.DESC, 'Object', { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $.getDesc, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: $.setDesc, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' + 'toLocaleString,toString,valueOf').split(',') // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', 'prototype') , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = document.createElement('iframe') , i = keysLen1 , gt = '>' , iframeDocument; iframe.style.display = 'none'; $.html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict.prototype[keys1[i]]; return createDict(); }; function createGetKeys(names, length){ return function(object){ var O = toObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; }; } function isPrimitive(it){ return !$.isObject(it); } function Empty(){} $def($def.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = Object(assert.def(O)); if(has(O, IE_PROTO))return O[IE_PROTO]; if(isFunction(O.constructor) && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: $.create = $.create || function(O, /*?*/Properties){ var result; if(O !== null){ Empty.prototype = assertObject(O); result = new Empty(); Empty.prototype = null; // add "__proto__" for Object.getPrototypeOf shim result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: $.it, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: $.it, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: $.it, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: $.isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $def($def.P, 'Function', { bind: function(that /*, args... */){ var fn = assert.fn(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return invoke(fn, args, this instanceof bound ? $.create(fn.prototype) : that); } if(fn.prototype)bound.prototype = fn.prototype; return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply($.ES5Object(this), arguments); }; } if(!(0 in Object('z') && 'z'[0] == 'z')){ $.ES5Object = function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; } $def($def.P + $def.F * ($.ES5Object != Object), 'Array', { slice: arrayMethodFix(slice), join: arrayMethodFix(A.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $def($def.S, 'Array', { isArray: function(arg){ return cof(arg) == 'Array'; } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assert.fn(callbackfn); var O = toObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(arguments.length < 2)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, 'Reduce of empty array with no initial value'); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; }; } $def($def.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || arrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: arrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: arrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: arrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: arrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || __webpack_require__(64)(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, $.toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $def($def.P, 'String', {trim: __webpack_require__(65)(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $def($def.S, 'Date', {now: function(){ return +new Date; }}); function lz(num){ return num > 9 ? num : '0' + num; } // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS and old webkit had a broken Date implementation. var date = new Date(-5e13 - 1) , brokenDate = !(date.toISOString && date.toISOString() == '0385-07-25T07:06:39.999Z'); $def($def.P + $def.F * brokenDate, 'Date', {toISOString: function(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; }}); if(classof(function(){ return arguments; }()) == 'Object')cof.classof = function(it){ var tag = classof(it); return tag == 'Object' && isFunction(it.callee) ? 'Arguments' : tag; }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var $ = __webpack_require__(57) , setTag = __webpack_require__(58).set , uid = __webpack_require__(62) , $def = __webpack_require__(59) , keyOf = __webpack_require__(66) , enumKeys = __webpack_require__(67) , assertObject = __webpack_require__(63).obj , has = $.has , $create = $.create , getDesc = $.getDesc , setDesc = $.setDesc , desc = $.desc , getNames = $.getNames , toObject = $.toObject , Symbol = $.g.Symbol , setter = false , TAG = uid('tag') , HIDDEN = uid('hidden') , SymbolRegistry = {} , AllSymbols = {} , useNative = $.isFunction(Symbol); function wrap(tag){ var sym = AllSymbols[tag] = $.set($create(Symbol.prototype), TAG, tag); $.DESC && setter && setDesc(Object.prototype, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setDesc(this, tag, desc(1, value)); } }); return sym; } function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, desc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D.enumerable = false; } } return setDesc(it, key, D); } function defineProperties(it, P){ assertObject(it); var keys = enumKeys(P = toObject(P)) , i = 0 , l = keys.length , key; while(l > i)defineProperty(it, key = keys[i++], P[key]); return it; } function create(it, P){ return P === undefined ? $create(it) : defineProperties($create(it), P); } function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; } function getOwnPropertyNames(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); return result; } function getOwnPropertySymbols(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); return result; } // 19.4.1.1 Symbol([description]) if(!useNative){ Symbol = function Symbol(description){ if(this instanceof Symbol)throw TypeError('Symbol is not a constructor'); return wrap(uid(description)); }; $.hide(Symbol.prototype, 'toString', function(){ return this[TAG]; }); $.create = create; $.setDesc = defineProperty; $.getDesc = getOwnPropertyDescriptor; $.setDescs = defineProperties; $.getNames = getOwnPropertyNames; $.getSymbols = getOwnPropertySymbols; } var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ return keyOf(SymbolRegistry, key); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.4 Symbol.iterator // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.13 Symbol.toStringTag // 19.4.2.14 Symbol.unscopables $.each.call(( 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + 'species,split,toPrimitive,toStringTag,unscopables' ).split(','), function(it){ var sym = __webpack_require__(68)(it); symbolStatics[it] = useNative ? sym : wrap(sym); } ); setter = true; $def($def.G + $def.W, {Symbol: Symbol}); $def($def.S, 'Symbol', symbolStatics); $def($def.S + $def.F * !useNative, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: getOwnPropertySymbols }); // 19.4.3.5 Symbol.prototype[@@toStringTag] setTag(Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setTag($.g.JSON, 'JSON', true); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $def = __webpack_require__(59); $def($def.S, 'Object', {assign: __webpack_require__(69)}); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.10 Object.is(value1, value2) var $def = __webpack_require__(59); $def($def.S, 'Object', { is: function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $def = __webpack_require__(59); $def($def.S, 'Object', {setPrototypeOf: __webpack_require__(70).set}); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 19.1.3.6 Object.prototype.toString() var $ = __webpack_require__(57) , cof = __webpack_require__(58) , tmp = {}; tmp[__webpack_require__(68)('toStringTag')] = 'z'; if($.FW && cof(tmp) != 'z')$.hide(Object.prototype, 'toString', function toString(){ return '[object ' + cof.classof(this) + ']'; }); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , isObject = $.isObject , toObject = $.toObject; function wrapObjectMethod(METHOD, MODE){ var fn = ($.core.Object || {})[METHOD] || Object[METHOD] , f = 0 , o = {}; o[METHOD] = MODE == 1 ? function(it){ return isObject(it) ? fn(it) : it; } : MODE == 2 ? function(it){ return isObject(it) ? fn(it) : true; } : MODE == 3 ? function(it){ return isObject(it) ? fn(it) : false; } : MODE == 4 ? function getOwnPropertyDescriptor(it, key){ return fn(toObject(it), key); } : MODE == 5 ? function getPrototypeOf(it){ return fn(Object($.assertDefined(it))); } : function(it){ return fn(toObject(it)); }; try { fn('z'); } catch(e){ f = 1; } $def($def.S + $def.F * f, 'Object', o); } wrapObjectMethod('freeze', 1); wrapObjectMethod('seal', 1); wrapObjectMethod('preventExtensions', 1); wrapObjectMethod('isFrozen', 2); wrapObjectMethod('isSealed', 2); wrapObjectMethod('isExtensible', 3); wrapObjectMethod('getOwnPropertyDescriptor', 4); wrapObjectMethod('getPrototypeOf', 5); wrapObjectMethod('keys'); wrapObjectMethod('getOwnPropertyNames'); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , NAME = 'name' , setDesc = $.setDesc , FunctionProto = Function.prototype; // 19.2.4.2 name NAME in FunctionProto || $.FW && $.DESC && setDesc(FunctionProto, NAME, { configurable: true, get: function(){ var match = String(this).match(/^\s*function ([^ (]*)/) , name = match ? match[1] : ''; $.has(this, NAME) || setDesc(this, NAME, $.desc(5, name)); return name; }, set: function(value){ $.has(this, NAME) || setDesc(this, NAME, $.desc(0, value)); } }); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , abs = Math.abs , floor = Math.floor , _isFinite = $.g.isFinite , MAX_SAFE_INTEGER = 0x1fffffffffffff; // pow(2, 53) - 1 == 9007199254740991; function isInteger(it){ return !$.isObject(it) && _isFinite(it) && floor(it) === it; } $def($def.S, 'Number', { // 20.1.2.1 Number.EPSILON EPSILON: Math.pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: function isNaN(number){ return number != number; }, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var Infinity = 1 / 0 , $def = __webpack_require__(59) , E = Math.E , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , ceil = Math.ceil , floor = Math.floor , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); function roundTiesToEven(n){ return n + 1 / EPSILON - 1 / EPSILON; } // 20.2.2.28 Math.sign(x) function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; } // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $def($def.S, 'Math', { // 20.2.2.3 Math.acosh(x) acosh: function acosh(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function atanh(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function cbrt(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function clz32(x){ return (x >>>= 0) ? 31 - floor(log(x + 0.5) * Math.LOG2E) : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) fround: function fround(x){ var $abs = abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , len1 = arguments.length , len2 = len1 , args = Array(len1) , larg = -Infinity , arg; while(len1--){ arg = args[len1] = +arguments[len1]; if(arg == Infinity || arg == -Infinity)return Infinity; if(arg > larg)larg = arg; } larg = arg || 1; while(len2--)sum += pow(args[len2] / larg, 2); return larg * sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function imul(x, y){ var UInt16 = 0xffff , xn = +x , yn = +y , xl = UInt16 & xn , yl = UInt16 & yn; return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function log10(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function log2(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function sinh(x){ return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: function trunc(it){ return (it > 0 ? floor : ceil)(it); } }); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59) , toIndex = __webpack_require__(57).toIndex , fromCharCode = String.fromCharCode; $def($def.S, 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , len = arguments.length , i = 0 , code; while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59); $def($def.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = $.toObject(callSite.raw) , len = $.toLength(tpl.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var set = __webpack_require__(57).set , at = __webpack_require__(71)(true) , ITER = __webpack_require__(62).safe('iter') , $iter = __webpack_require__(72) , step = $iter.step; // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(73)(String, 'String', function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return step(1); point = at.call(O, index); iter.i += point.length; return step(0, point); }); /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59); $def($def.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: __webpack_require__(71)(false) }); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , cof = __webpack_require__(58) , $def = __webpack_require__(59) , toLength = $.toLength; $def($def.P, 'String', { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function endsWith(searchString /*, endPosition = @length */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; } }); /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , cof = __webpack_require__(58) , $def = __webpack_require__(59); $def($def.P, 'String', { // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function includes(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); return !!~String($.assertDefined(this)).indexOf(searchString, arguments[1]); } }); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59); $def($def.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: function repeat(count){ var str = String($.assertDefined(this)) , res = '' , n = $.toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; } }); /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , cof = __webpack_require__(58) , $def = __webpack_require__(59); $def($def.P, 'String', { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function startsWith(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , index = $.toLength(Math.min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , ctx = __webpack_require__(74) , $def = __webpack_require__(59) , $iter = __webpack_require__(72) , call = __webpack_require__(75); $def($def.S + $def.F * !__webpack_require__(76)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object($.assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, step, iterator; if($iter.is(O)){ iterator = $iter.get(O); // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array); for(; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, f, [step.value, index], true) : step.value; } } else { // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array)(length = $.toLength(O.length)); for(; length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } } result.length = index; return result; } }); /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59); $def($def.S, 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , length = arguments.length // strange IE quirks mode bug -> use typeof instead of isFunction , result = new (typeof this == 'function' ? this : Array)(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , setUnscope = __webpack_require__(77) , ITER = __webpack_require__(62).safe('iter') , $iter = __webpack_require__(72) , step = $iter.step , Iterators = $iter.Iterators; // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() __webpack_require__(73)(Array, 'Array', function(iterated, kind){ $.set(this, ITER, {o: $.toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length){ iter.o = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; setUnscope('keys'); setUnscope('values'); setUnscope('entries'); /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(78)(Array); /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59) , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function copyWithin(target/* = 0 */, start /* = 0, end = @length */){ var O = Object($.assertDefined(this)) , len = $.toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = Math.min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; } }); __webpack_require__(77)('copyWithin'); /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59) , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function fill(value /*, start = 0, end = @length */){ var O = Object($.assertDefined(this)) , length = $.toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; } }); __webpack_require__(77)('fill'); /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59); $def($def.P, 'Array', { // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: __webpack_require__(61)(5) }); __webpack_require__(77)('find'); /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59); $def($def.P, 'Array', { // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: __webpack_require__(61)(6) }); __webpack_require__(77)('findIndex'); /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , ctx = __webpack_require__(74) , cof = __webpack_require__(58) , $def = __webpack_require__(59) , assert = __webpack_require__(63) , forOf = __webpack_require__(79) , setProto = __webpack_require__(70).set , species = __webpack_require__(78) , SPECIES = __webpack_require__(68)('species') , RECORD = __webpack_require__(62).safe('record') , PROMISE = 'Promise' , global = $.g , process = global.process , asap = process && process.nextTick || __webpack_require__(80).set , P = global[PROMISE] , isFunction = $.isFunction , isObject = $.isObject , assertFunction = assert.fn , assertObject = assert.obj , test; var useNative = isFunction(P) && isFunction(P.resolve) && P.resolve(test = new P(function(){})) == test; // actual Firefox has broken subclass support, test that function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } if(useNative){ try { // protect against bad/buggy Object.setPrototype setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); if(!(P2.resolve(5).then(function(){}) instanceof P2)){ useNative = false; } } catch(e){ useNative = false; } } // helpers function getConstructor(C){ var S = assertObject(C)[SPECIES]; return S != undefined ? S : C; } function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function isUnhandled(promise){ var record = promise[RECORD] , chain = record.c , i = 0 , react; if(record.h)return false; while(chain.length > i){ react = chain[i++]; if(react.fail || !isUnhandled(react.P))return false; } return true; } function notify(record, isReject){ var chain = record.c; if(isReject || chain.length)asap(function(){ var promise = record.p , value = record.v , ok = record.s == 1 , i = 0; if(isReject && isUnhandled(promise)){ setTimeout(function(){ if(isUnhandled(promise)){ if(cof(process) == 'process'){ process.emit('unhandledRejection', value, promise); } else if(global.console && isFunction(console.error)){ console.error('Unhandled promise rejection', value); } } }, 1e3); } else while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function $reject(value){ var record = this; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; notify(record, true); } function $resolve(value){ var record = this , then, wrapper; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ wrapper = {r: record, d: false}; // wrap then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } else { record.v = value; record.s = 1; notify(record); } } catch(err){ $reject.call(wrapper || {r: record, d: false}, err); // wrap } } // constructor polyfill if(!useNative){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ assertFunction(executor); var record = { p: assert.inst(this, P, PROMISE), // <- promise c: [], // <- chain s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false // <- handled rejection }; $.hide(this, RECORD, record); try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; $.mix(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var S = assertObject(assertObject(this).constructor)[SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false }; var promise = react.P = new (S != undefined ? S : P)(function(res, rej){ react.res = assertFunction(res); react.rej = assertFunction(rej); }); var record = this[RECORD]; record.c.push(react); record.s && notify(record); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } // export $def($def.G + $def.W + $def.F * !useNative, {Promise: P}); cof.set(P, PROMISE); species(P); species($.core[PROMISE]); // for wrapper // statics $def($def.S + $def.F * !useNative, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ return new (getConstructor(this))(function(res, rej){ rej(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ return isObject(x) && RECORD in x && $.getProto(x) === this.prototype ? x : new (getConstructor(this))(function(res){ res(x); }); } }); $def($def.S + $def.F * !(useNative && __webpack_require__(76)(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , values = []; return new C(function(res, rej){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ C.resolve(promise).then(function(value){ results[index] = value; --remaining || res(results); }, rej); }); else res(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this); return new C(function(res, rej){ forOf(iterable, false, function(promise){ C.resolve(promise).then(res, rej); }); }); } }); /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(81); // 23.1 Map Objects __webpack_require__(82)('Map', { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(81); // 23.2 Set Objects __webpack_require__(82)('Set', { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , weak = __webpack_require__(83) , leakStore = weak.leakStore , ID = weak.ID , WEAK = weak.WEAK , has = $.has , isObject = $.isObject , isFrozen = Object.isFrozen || $.core.Object.isFrozen , tmp = {}; // 23.3 WeakMap Objects var WeakMap = __webpack_require__(82)('WeakMap', { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[ID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }, weak, true, true); // IE11 WeakMap frozen keys fix if($.FW && new WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ $.each.call(['delete', 'has', 'get', 'set'], function(key){ var method = WeakMap.prototype[key]; WeakMap.prototype[key] = function(a, b){ // store frozen objects on leaky map if(isObject(a) && isFrozen(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }; }); } /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var weak = __webpack_require__(83); // 23.4 WeakSet Objects __webpack_require__(82)('WeakSet', { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , setProto = __webpack_require__(70) , $iter = __webpack_require__(72) , ITER = __webpack_require__(62).safe('iter') , step = $iter.step , assert = __webpack_require__(63) , isObject = $.isObject , getDesc = $.getDesc , setDesc = $.setDesc , getProto = $.getProto , apply = Function.apply , assertObject = assert.obj , _isExtensible = Object.isExtensible || $.it; function Enumerate(iterated){ $.set(this, ITER, {o: iterated, k: undefined, i: 0}); } $iter.create(Enumerate, 'Object', function(){ var iter = this[ITER] , keys = iter.k , key; if(keys == undefined){ iter.k = keys = []; for(key in iter.o)keys.push(key); } do { if(iter.i >= keys.length)return step(1); } while(!((key = keys[iter.i++]) in iter.o)); return step(0, key); }); function wrap(fn){ return function(it){ assertObject(it); try { fn.apply(undefined, arguments); return true; } catch(e){ return false; } }; } function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = getDesc(assertObject(target), propertyKey), proto; if(desc)return $.has(desc, 'value') ? desc.value : desc.get === undefined ? undefined : desc.get.call(receiver); return isObject(proto = getProto(target)) ? get(proto, propertyKey, receiver) : undefined; } function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = getDesc(assertObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = $.desc(0); } if($.has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = getDesc(receiver, propertyKey) || $.desc(0); existingDescriptor.value = V; setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: __webpack_require__(74)(Function.call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: function construct(target, argumentsList /*, newTarget*/){ var proto = assert.fn(arguments.length < 3 ? target : arguments[2]).prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; }, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(setDesc), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function deleteProperty(target, propertyKey){ var desc = getDesc(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function enumerate(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: get, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return getDesc(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function getPrototypeOf(target){ return getProto(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function has(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function isExtensible(target){ return !!_isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: __webpack_require__(84), // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || $.it), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: set }; // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setProto)reflect.setPrototypeOf = function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } }; $def($def.G, {Reflect: {}}); $def($def.S, 'Reflect', reflect); /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/domenic/Array.prototype.includes var $def = __webpack_require__(59); $def($def.P, 'Array', { includes: __webpack_require__(64)(true) }); __webpack_require__(77)('includes'); /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/mathiasbynens/String.prototype.at var $def = __webpack_require__(59); $def($def.P, 'String', { at: __webpack_require__(71)(true) }); /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/kangax/9698100 var $def = __webpack_require__(59); $def($def.S, 'RegExp', { escape: __webpack_require__(65)(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/WebReflection/9353781 var $ = __webpack_require__(57) , $def = __webpack_require__(59) , ownKeys = __webpack_require__(84); $def($def.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = $.toObject(object) , result = {}; $.each.call(ownKeys(O), function(key){ $.setDesc(result, key, $.desc(0, $.getDesc(O, key))); }); return result; } }); /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $ = __webpack_require__(57) , $def = __webpack_require__(59); function createObjectToArray(isEntries){ return function(object){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; }; } $def($def.S, 'Object', { values: createObjectToArray(false), entries: createObjectToArray(true) }); /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON __webpack_require__(85)('Map'); /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON __webpack_require__(85)('Set'); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59) , $task = __webpack_require__(80); $def($def.G + $def.B, { setImmediate: $task.set, clearImmediate: $task.clear }); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(21); var $ = __webpack_require__(57) , Iterators = __webpack_require__(72).Iterators , ITERATOR = __webpack_require__(68)('iterator') , ArrayValues = Iterators.Array , NodeList = $.g.NodeList; if($.FW && NodeList && !(ITERATOR in NodeList.prototype)){ $.hide(NodeList.prototype, ITERATOR, ArrayValues); } Iterators.NodeList = ArrayValues; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { // ie9- setTimeout & setInterval additional parameters fix var $ = __webpack_require__(57) , $def = __webpack_require__(59) , invoke = __webpack_require__(60) , partial = __webpack_require__(86) , navigator = $.g.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), $.isFunction(fn) ? fn : Function(fn) ), time); } : set; } $def($def.G + $def.B + $def.F * MSIE, { setTimeout: wrap($.g.setTimeout), setInterval: wrap($.g.setInterval) }); /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , ctx = __webpack_require__(74) , $def = __webpack_require__(59) , assign = __webpack_require__(69) , keyOf = __webpack_require__(66) , ITER = __webpack_require__(62).safe('iter') , assert = __webpack_require__(63) , $iter = __webpack_require__(72) , forOf = __webpack_require__(79) , step = $iter.step , getKeys = $.getKeys , toObject = $.toObject , has = $.has; function Dict(iterable){ var dict = $.create(null); if(iterable != undefined){ if($iter.is(iterable)){ forOf(iterable, true, function(key, value){ dict[key] = value; }); } else assign(dict, iterable); } return dict; } Dict.prototype = null; function DictIterator(iterated, kind){ $.set(this, ITER, {o: toObject(iterated), a: getKeys(iterated), i: 0, k: kind}); } $iter.create(DictIterator, 'Dict', function(){ var iter = this[ITER] , O = iter.o , keys = iter.a , kind = iter.k , key; do { if(iter.i >= keys.length){ iter.o = undefined; return step(1); } } while(!has(O, key = keys[iter.i++])); if(kind == 'keys' )return step(0, key); if(kind == 'values')return step(0, O[key]); return step(0, [key, O[key]]); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); }; } function generic(A, B){ // strange IE quirks mode bug -> use typeof instead of isFunction return typeof A == 'function' ? A : B; } // 0 -> Dict.forEach // 1 -> Dict.map // 2 -> Dict.filter // 3 -> Dict.some // 4 -> Dict.every // 5 -> Dict.find // 6 -> Dict.findKey // 7 -> Dict.mapPairs function createDictMethod(TYPE){ var IS_MAP = TYPE == 1 , IS_EVERY = TYPE == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = toObject(object) , result = IS_MAP || TYPE == 7 || TYPE == 2 ? new (generic(this, Dict)) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(TYPE){ if(IS_MAP)result[key] = res; // map else if(res)switch(TYPE){ case 2: result[key] = val; break; // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(IS_EVERY)return false; // every } } return TYPE == 3 || IS_EVERY ? IS_EVERY : result; }; } // true -> Dict.turn // false -> Dict.reduce function createDictReduce(IS_TURN){ return function(object, mapfn, init){ assert.fn(mapfn); var O = toObject(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(IS_TURN){ memo = init == undefined ? new (generic(this, Dict)) : Object(init); } else if(arguments.length < 3){ assert(length, 'Reduce of empty object with no initial value'); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ result = mapfn(memo, O[key], key, object); if(IS_TURN){ if(result === false)break; } else memo = result; } return memo; }; } var findKey = createDictMethod(6); $def($def.G + $def.F, {Dict: $.mix(Dict, { keys: createDictIter('keys'), values: createDictIter('values'), entries: createDictIter('entries'), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs: createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes: function(object, el){ return (el == el ? keyOf(object, el) : findKey(object, function(it){ return it != it; })) !== undefined; }, // Has / get / set own property has: has, get: function(object, key){ if(has(object, key))return object[key]; }, set: $.def, isDict: function(it){ return $.isObject(it) && $.getProto(it) === Dict.prototype; } })}); /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var core = __webpack_require__(57).core , $iter = __webpack_require__(72); core.isIterable = $iter.is; core.getIterator = $iter.get; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , ctx = __webpack_require__(74) , safe = __webpack_require__(62).safe , $def = __webpack_require__(59) , $iter = __webpack_require__(72) , forOf = __webpack_require__(79) , ENTRIES = safe('entries') , FN = safe('fn') , ITER = safe('iter') , call = __webpack_require__(75) , getIterator = $iter.get , setIterator = $iter.set , createIterator = $iter.create; function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for.prototype; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iterator(iter, fn, that){ this[ITER] = getIterator(iter); this[ENTRIES] = iter[ENTRIES]; this[FN] = ctx(fn, that, iter[ENTRIES] ? 2 : 1); } createIterator(Iterator, 'Chain', next, $forProto); setIterator(Iterator.prototype, $.that); // override $forProto iterator return Iterator; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : $iter.step(0, call(this[ITER], this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || call(this[ITER], this[FN], step.value, this[ENTRIES]))return step; } }); $.mix($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, result.push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = $iter.is; $for.getIterator = getIterator; $def($def.G + $def.F, {$for: $for}); /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , partial = __webpack_require__(86); // https://esdiscuss.org/topic/promise-returning-delay-function $def($def.G + $def.F, { delay: function(time){ return new ($.core.Promise || $.g.Promise)(function(resolve){ setTimeout(partial.call(resolve, true), time); }); } }); /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59); // Placeholder $.core._ = $.path._ = $.path._ || {}; $def($def.P + $def.F, 'Function', { part: __webpack_require__(86) }); /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , ownKeys = __webpack_require__(84); function define(target, mixin){ var keys = ownKeys($.toObject(mixin)) , length = keys.length , i = 0, key; while(length > i)$.setDesc(target, key = keys[i++], $.getDesc(mixin, key)); return target; } $def($def.S + $def.F, 'Object', { isObject: $.isObject, classof: __webpack_require__(58).classof, define: define, make: function(proto, mixin){ return define($.create(proto), mixin); } }); /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59) , assertFunction = __webpack_require__(63).fn; $def($def.P + $def.F, 'Array', { turn: function(fn, target /* = [] */){ assertFunction(fn); var memo = target == undefined ? [] : Object(target) , O = $.ES5Object(this) , length = $.toLength(O.length) , index = 0; while(length > index)if(fn(memo, O[index], index++, this) === false)break; return memo; } }); __webpack_require__(77)('turn'); /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , ITER = __webpack_require__(62).safe('iter'); __webpack_require__(73)(Number, 'Number', function(iterated){ $.set(this, ITER, {l: $.toLength(iterated), i: 0}); }, function(){ var iter = this[ITER] , i = iter.i++ , done = i >= iter.l; return {done: done, value: done ? undefined : i}; }); /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59) , invoke = __webpack_require__(60) , methods = {}; methods.random = function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = Math.min(a, b); return Math.random() * (Math.max(a, b) - m) + m; }; if($.FW)$.each.call(( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ).split(','), function(key){ var fn = Math[key]; if(fn)methods[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); }; } ); $def($def.P + $def.F, 'Number', methods); /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59) , replacer = __webpack_require__(65); var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $def($def.P + $def.F, 'String', { escapeHTML: replacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: replacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , core = $.core , formatRegExp = /\b\w\w?\b/g , flexioRegExp = /:(.*)\|(.*)$/ , locales = {} , current = 'en' , SECONDS = 'Seconds' , MINUTES = 'Minutes' , HOURS = 'Hours' , DATE = 'Date' , MONTH = 'Month' , YEAR = 'FullYear'; function lz(num){ return num > 9 ? num : '0' + num; } function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[$.has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); }; } function addLocale(lang, locale){ function split(index){ var result = []; $.each.call(locale.months.split(','), function(it){ result.push(it.replace(flexioRegExp, '$' + index)); }); return result; } locales[lang] = [locale.weekdays.split(','), split(1), split(2)]; return core; } $def($def.P + $def.F, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return $.has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59); $def($def.G + $def.F, {global: __webpack_require__(57).g}); /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , $def = __webpack_require__(59) , log = {} , enabled = true; // Methods from https://github.com/DeveloperToolsWG/console-object/blob/master/api.md $.each.call(('assert,clear,count,debug,dir,dirxml,error,exception,' + 'group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,' + 'markTimeline,profile,profileEnd,table,time,timeEnd,timeline,' + 'timelineEnd,timeStamp,trace,warn').split(','), function(key){ log[key] = function(){ if(enabled && $.g.console && $.isFunction(console[key])){ return Function.apply.call(console[key], console, arguments); } }; }); $def($def.G + $def.F, {log: __webpack_require__(69)(log.log, log, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } })}); /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { // JavaScript 1.6 / Strawman array statics shim var $ = __webpack_require__(57) , $def = __webpack_require__(59) , $Array = $.core.Array || Array , statics = {}; function setStatics(keys, length){ $.each.call(keys.split(','), function(key){ if(length == undefined && key in $Array)statics[key] = $Array[key]; else if(key in [])statics[key] = __webpack_require__(74)(Function.call, [][key], length); }); } setStatics('pop,reverse,shift,keys,values,entries', 1); setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $def($def.S, 'Array', statics); /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = typeof self != 'undefined' ? self : Function('return this')() , core = {} , defineProperty = Object.defineProperty , hasOwnProperty = {}.hasOwnProperty , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min; // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){ try { return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2; } catch(e){ /* empty */ } }(); var hide = createDefiner(1); // 7.1.4 ToInteger function toInteger(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); } function desc(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return $.setDesc(object, key, desc(bitmap, value)); } : simpleSet; } function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } function assertDefined(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; } var $ = module.exports = __webpack_require__(87)({ g: global, core: core, html: global.document && document.documentElement, // http://jsperf.com/core-js-isobject isObject: isObject, isFunction: isFunction, it: function(it){ return it; }, that: function(){ return this; }, // 7.1.4 ToInteger toInteger: toInteger, // 7.1.15 ToLength toLength: function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }, toIndex: function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }, has: function(it, key){ return hasOwnProperty.call(it, key); }, create: Object.create, getProto: Object.getPrototypeOf, DESC: DESC, desc: desc, getDesc: Object.getOwnPropertyDescriptor, setDesc: defineProperty, setDescs: Object.defineProperties, getKeys: Object.keys, getNames: Object.getOwnPropertyNames, getSymbols: Object.getOwnPropertySymbols, assertDefined: assertDefined, // Dummy, fix for not array-like ES3 string in es5 module ES5Object: Object, toObject: function(it){ return $.ES5Object(assertDefined(it)); }, hide: hide, def: createDefiner(0), set: global.Symbol ? simpleSet : hide, mix: function(target, src){ for(var key in src)hide(target, key, src[key]); return target; }, each: [].forEach }); /* eslint-disable no-undef */ if(typeof __e != 'undefined')__e = core; if(typeof __g != 'undefined')__g = global; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , TAG = __webpack_require__(68)('toStringTag') , toString = {}.toString; function cof(it){ return toString.call(it).slice(8, -1); } cof.classof = function(it){ var O, T; return it == undefined ? it === undefined ? 'Undefined' : 'Null' : typeof (T = (O = Object(it))[TAG]) == 'string' ? T : cof(O); }; cof.set = function(it, tag, stat){ if(it && !$.has(it = stat ? it : it.prototype, TAG))$.hide(it, TAG, tag); }; module.exports = cof; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , global = $.g , core = $.core , isFunction = $.isFunction; function ctx(fn, that){ return function(){ return fn.apply(that, arguments); }; } // type bitmap $def.F = 1; // forced $def.G = 2; // global $def.S = 4; // static $def.P = 8; // proto $def.B = 16; // bind $def.W = 32; // wrap function $def(type, name, source){ var key, own, out, exp , isGlobal = type & $def.G , target = isGlobal ? global : type & $def.S ? global[name] : (global[name] || {}).prototype , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // contains in native own = !(type & $def.F) && target && key in target; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces if(isGlobal && !isFunction(target[key]))exp = source[key]; // bind timers to global for call from export context else if(type & $def.B && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & $def.W && target[key] == out)!function(C){ exp = function(param){ return this instanceof C ? new C(param) : C(param); }; exp.prototype = C.prototype; }(out); else exp = type & $def.P && isFunction(out) ? ctx(Function.call, out) : out; // export $.hide(exports, key, exp); } } module.exports = $def; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // Fast apply // http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); }; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var $ = __webpack_require__(57) , ctx = __webpack_require__(74); module.exports = function(TYPE){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function(callbackfn/*, that = undefined */){ var O = Object($.assertDefined(this)) , self = $.ES5Object(O) , f = ctx(callbackfn, arguments[1], 3) , length = $.toLength(self.length) , index = 0 , result = IS_MAP ? Array(length) : IS_FILTER ? [] : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var sid = 0; function uid(key){ return 'Symbol(' + key + ')_' + (++sid + Math.random()).toString(36); } uid.safe = __webpack_require__(57).g.Symbol || uid; module.exports = uid; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57); function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } assert.def = $.assertDefined; assert.fn = function(it){ if(!$.isFunction(it))throw TypeError(it + ' is not a function!'); return it; }; assert.obj = function(it){ if(!$.isObject(it))throw TypeError(it + ' is not an object!'); return it; }; assert.inst = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; module.exports = assert; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // false -> Array#indexOf // true -> Array#includes var $ = __webpack_require__(57); module.exports = function(IS_INCLUDES){ return function(el /*, fromIndex = 0 */){ var O = $.toObject(this) , length = $.toLength(O.length) , index = $.toIndex(arguments[1], length) , value; if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = function(regExp, replace, isStatic){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); }; }; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57); module.exports = function(object, el){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57); module.exports = function(it){ var keys = $.getKeys(it) , getDesc = $.getDesc , getSymbols = $.getSymbols; if(getSymbols)$.each.call(getSymbols(it), function(key){ if(getDesc(it, key).enumerable)keys.push(key); }); return keys; }; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(57).g , store = {}; module.exports = function(name){ return store[name] || (store[name] = global.Symbol && global.Symbol[name] || __webpack_require__(62).safe('Symbol.' + name)); }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , enumKeys = __webpack_require__(67); // 19.1.2.1 Object.assign(target, source, ...) /* eslint-disable no-unused-vars */ module.exports = Object.assign || function assign(target, source){ /* eslint-enable no-unused-vars */ var T = Object($.assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = $.ES5Object(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var $ = __webpack_require__(57) , assert = __webpack_require__(63); function check(O, proto){ assert.obj(O); assert(proto === null || $.isObject(proto), proto, ": can't set as prototype!"); } module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} // eslint-disable-line ? function(buggy, set){ try { set = __webpack_require__(74)(Function.call, $.getDesc(Object.prototype, '__proto__').set, 2); set({}, []); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }() : undefined), check: check }; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // true -> String#at // false -> String#codePointAt var $ = __webpack_require__(57); module.exports = function(TO_STRING){ return function(pos){ var s = String($.assertDefined(this)) , i = $.toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , cof = __webpack_require__(58) , assertObject = __webpack_require__(63).obj , SYMBOL_ITERATOR = __webpack_require__(68)('iterator') , FF_ITERATOR = '@@iterator' , Iterators = {} , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, $.that); function setIterator(O, value){ $.hide(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol if(FF_ITERATOR in [])$.hide(O, FF_ITERATOR, value); } module.exports = { // Safari has buggy iterators w/o `next` BUGGY: 'keys' in [] && !('next' in [].keys()), Iterators: Iterators, step: function(done, value){ return {value: value, done: !!done}; }, is: function(it){ var O = Object(it) , Symbol = $.g.Symbol , SYM = Symbol && Symbol.iterator || FF_ITERATOR; return SYM in O || SYMBOL_ITERATOR in O || $.has(Iterators, cof.classof(O)); }, get: function(it){ var Symbol = $.g.Symbol , ext = it[Symbol && Symbol.iterator || FF_ITERATOR] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[cof.classof(it)]; return assertObject(getIter.call(it)); }, set: setIterator, create: function(Constructor, NAME, next, proto){ Constructor.prototype = $.create(proto || IteratorPrototype, {next: $.desc(1, next)}); cof.set(Constructor, NAME + ' Iterator'); } }; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { var $def = __webpack_require__(59) , $ = __webpack_require__(57) , cof = __webpack_require__(58) , $iter = __webpack_require__(72) , SYMBOL_ITERATOR = __webpack_require__(68)('iterator') , FF_ITERATOR = '@@iterator' , VALUES = 'values' , Iterators = $iter.Iterators; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){ $iter.create(Constructor, NAME, next); function createMethod(kind){ return function(){ return new Constructor(this, kind); }; } var TAG = NAME + ' Iterator' , proto = Base.prototype , _native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , _default = _native || createMethod(DEFAULT) , methods, key; // Fix native if(_native){ var IteratorPrototype = $.getProto(_default.call(new Base)); // Set @@toStringTag to native iterators cof.set(IteratorPrototype, TAG, true); // FF fix if($.FW && $.has(proto, FF_ITERATOR))$iter.set(IteratorPrototype, $.that); } // Define iterator if($.FW)$iter.set(proto, _default); // Plug for library Iterators[NAME] = _default; Iterators[TAG] = $.that; if(DEFAULT){ methods = { keys: IS_SET ? _default : createMethod('keys'), values: DEFAULT == VALUES ? _default : createMethod(VALUES), entries: DEFAULT != VALUES ? _default : createMethod('entries') }; if(FORCE)for(key in methods){ if(!(key in proto))$.hide(proto, key, methods[key]); } else $def($def.P + $def.F * $iter.BUGGY, NAME, methods); } }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { // Optional / simple context binding var assertFunction = __webpack_require__(63).fn; module.exports = function(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { var assertObject = __webpack_require__(63).obj; function close(iterator){ var ret = iterator['return']; if(ret !== undefined)assertObject(ret.call(iterator)); } function call(iterator, fn, value, entries){ try { return entries ? fn(assertObject(value)[0], value[1]) : fn(value); } catch(e){ close(iterator); throw e; } } call.close = close; module.exports = call; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { var SYMBOL_ITERATOR = __webpack_require__(68)('iterator') , SAFE_CLOSING = false; try { var riter = [7][SYMBOL_ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec){ if(!SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[SYMBOL_ITERATOR](); iter.next = function(){ safe = true; }; arr[SYMBOL_ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.31 Array.prototype[@@unscopables] var $ = __webpack_require__(57) , UNSCOPABLES = __webpack_require__(68)('unscopables'); if($.FW && !(UNSCOPABLES in []))$.hide(Array.prototype, UNSCOPABLES, {}); module.exports = function(key){ if($.FW)[][UNSCOPABLES][key] = true; }; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , SPECIES = __webpack_require__(68)('species'); module.exports = function(C){ if($.DESC && !(SPECIES in C))$.setDesc(C, SPECIES, { configurable: true, get: $.that }); }; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(74) , get = __webpack_require__(72).get , call = __webpack_require__(75); module.exports = function(iterable, entries, fn, that){ var iterator = get(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done){ if(call(iterator, f, step.value, entries) === false){ return call.close(iterator); } } }; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , ctx = __webpack_require__(74) , cof = __webpack_require__(58) , invoke = __webpack_require__(60) , global = $.g , isFunction = $.isFunction , html = $.html , document = global.document , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; function run(){ var id = +this; if($.has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run.call(event.data); } // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!isFunction(setTask) || !isFunction(clearTask)){ setTask = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function(id){ delete queue[id]; }; // Node.js 0.8- if(cof(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); }; addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document.createElement('script')){ defer = function(id){ html.appendChild(document.createElement('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , ctx = __webpack_require__(74) , safe = __webpack_require__(62).safe , assert = __webpack_require__(63) , forOf = __webpack_require__(79) , step = __webpack_require__(72).step , has = $.has , set = $.set , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , ID = safe('id') , O1 = safe('O1') , LAST = safe('last') , FIRST = safe('first') , ITER = safe('iter') , SIZE = $.DESC ? safe('size') : 'size' , id = 0; function fastKey(it, create){ // return primitive with prefix if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // can't set id to frozen object if(isFrozen(it))return 'F'; if(!has(it, ID)){ // not necessary to add id if(!create)return 'E'; // add missing object id hide(it, ID, ++id); // return object id with prefix } return 'O' + it[ID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index != 'F')return that[O1][index]; // frozen object case for(entry = that[FIRST]; entry; entry = entry.n){ if(entry.k == key)return entry; } } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ var that = assert.inst(this, C, NAME) , iterable = arguments[0]; set(that, O1, $.create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); } $.mix(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that[FIRST] = that[LAST] = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that[O1][entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if($.DESC)$.setDesc(C.prototype, 'size', { get: function(){ return assert.def(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index != 'F')that[O1][index] = entry; } return that; }, getEntry: getEntry, // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 setIter: function(C, NAME, IS_MAP){ __webpack_require__(73)(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , kind = iter.k , entry = iter.l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); } }; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , $def = __webpack_require__(59) , BUGGY = __webpack_require__(72).BUGGY , forOf = __webpack_require__(79) , species = __webpack_require__(78) , assertInstance = __webpack_require__(63).inst; module.exports = function(NAME, methods, common, IS_MAP, IS_WEAK){ var Base = $.g[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; function fixMethod(KEY, CHAIN){ var method = proto[KEY]; if($.FW)proto[KEY] = function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return CHAIN ? this : result; }; } if(!$.isFunction(C) || !(IS_WEAK || !BUGGY && proto.forEach && proto.entries)){ // create collection constructor C = common.getConstructor(NAME, IS_MAP, ADDER); $.mix(C.prototype, methods); } else { var inst = new C , chain = inst[ADDER](IS_WEAK ? {} : -0, 1) , buggyZero; // wrap for init collections from iterable if(!__webpack_require__(76)(function(iter){ new C(iter); })){ // eslint-disable-line no-new C = function(){ assertInstance(this, C, NAME); var that = new Base , iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }; C.prototype = proto; if($.FW)proto.constructor = C; } IS_WEAK || inst.forEach(function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixMethod(ADDER, true); } __webpack_require__(58).set(C, NAME); O[NAME] = C; $def($def.G + $def.W + $def.F * (C != Base), O); species(C); species($.core[NAME]); // for wrapper if(!IS_WEAK)common.setIter(C, NAME, IS_MAP); return C; }; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , safe = __webpack_require__(62).safe , assert = __webpack_require__(63) , forOf = __webpack_require__(79) , _has = $.has , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , id = 0 , ID = safe('id') , WEAK = safe('weak') , LEAK = safe('leak') , method = __webpack_require__(61) , find = method(5) , findIndex = method(6); function findFrozen(store, key){ return find.call(store.array, function(it){ return it[0] === key; }); } // fallback for frozen keys function leakStore(that){ return that[LEAK] || hide(that, LEAK, { array: [], get: function(key){ var entry = findFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findFrozen(this, key); }, set: function(key, value){ var entry = findFrozen(this, key); if(entry)entry[1] = value; else this.array.push([key, value]); }, 'delete': function(key){ var index = findIndex.call(this.array, function(it){ return it[0] === key; }); if(~index)this.array.splice(index, 1); return !!~index; } })[LEAK]; } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ $.set(assert.inst(this, C, NAME), ID, id++); var iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, this[ADDER], this); } $.mix(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this)['delete'](key); return _has(key, WEAK) && _has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this).has(key); return _has(key, WEAK) && _has(key[WEAK], this[ID]); } }); return C; }, def: function(that, key, value){ if(isFrozen(assert.obj(key))){ leakStore(that).set(key, value); } else { _has(key, WEAK) || hide(key, WEAK, {}); key[WEAK][that[ID]] = value; } return that; }, leakStore: leakStore, WEAK: WEAK, ID: ID }; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(57) , assertObject = __webpack_require__(63).obj; module.exports = function ownKeys(it){ assertObject(it); var keys = $.getNames(it) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $def = __webpack_require__(59) , forOf = __webpack_require__(79); module.exports = function(NAME){ $def($def.P, NAME, { toJSON: function toJSON(){ var arr = []; forOf(this, false, arr.push, arr); return arr; } }); }; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(57) , invoke = __webpack_require__(60) , assertFunction = __webpack_require__(63).fn; module.exports = function(/* ...pargs */){ var fn = assertFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = $.path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , _length = arguments.length , j = 0, k = 0, args; if(!holder && !_length)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(_length > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { module.exports = function($){ $.FW = false; $.path = $.core; return $; }; /***/ } /******/ ]); // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = __e; // RequireJS export else if(typeof define == 'function' && define.amd)define(function(){return __e}); // Export to global object else __g.core = __e; }();
ajax/libs/angular-data/1.0.0-beta.1/angular-data.js
sympmarc/cdnjs
/** * @author Jason Dobry <[email protected]> * @file angular-data.js * @version 1.0.0-beta.1 - Homepage <http://angular-data.pseudobry.com/> * @copyright (c) 2014 Jason Dobry <https://github.com/jmdobry/> * @license MIT <https://github.com/jmdobry/angular-data/blob/master/LICENSE> * * @overview Data store for Angular.js. */ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // Copyright 2012 Google 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. // Modifications // Copyright 2014 Jason Dobry // // Summary of modifications: // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; // Detect and do basic sanity checking on Object/Array.observe. 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(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); 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 (global.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 diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) 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(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (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); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ 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; // TODO(rafaelw): Should be WeakRef 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; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); 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 (global.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; } // type = 'delete' 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; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })((exports.Number = { isNaN: window.isNaN }) ? exports : exports); },{}],2:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":5}],3:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Array filter */ function filter(arr, callback, thisObj) { callback = makeIterator(callback, thisObj); var results = []; if (arr == null) { return results; } var i = -1, len = arr.length, value; while (++i < len) { value = arr[i]; if (callback(value, i, arr)) { results.push(value); } } return results; } module.exports = filter; },{"../function/makeIterator_":11}],4:[function(require,module,exports){ /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; },{}],5:[function(require,module,exports){ /** * Array.indexOf */ 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) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],6:[function(require,module,exports){ var filter = require('./filter'); function isValidString(val) { return (val != null && val !== ''); } /** * Joins strings with the specified separator inserted between each value. * Null values and empty strings will be excluded. */ function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } module.exports = join; },{"./filter":3}],7:[function(require,module,exports){ /** * Create slice of source array or array-like object */ 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; },{}],8:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ 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) { // if 0 it should preserve same order (stable) 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; },{}],9:[function(require,module,exports){ var isFunction = require('../lang/isFunction'); /** * Creates an object that holds a lookup for the objects in the array. */ function toLookup(arr, key) { var result = {}; if (arr == null) { return result; } var i = -1, len = arr.length, value; if (isFunction(key)) { while (++i < len) { value = arr[i]; result[key(value)] = value; } } else { while (++i < len) { value = arr[i]; result[value[key]] = value; } } return result; } module.exports = toLookup; },{"../lang/isFunction":16}],10:[function(require,module,exports){ /** * Returns the first argument provided to it. */ function identity(val){ return val; } module.exports = identity; },{}],11:[function(require,module,exports){ var identity = require('./identity'); var prop = require('./prop'); var deepMatches = require('../object/deepMatches'); /** * Converts argument into a valid iterator. * Used internally on most array/object/collection methods that receives a * callback/iterator providing a shortcut syntax. */ function makeIterator(src, thisObj){ if (src == null) { return identity; } switch(typeof src) { case 'function': // function is the first to improve perf (most common case) // also avoid using `Function#call` if not needed, which boosts // perf a lot in some cases return (typeof thisObj !== 'undefined')? function(val, i, arr){ return src.call(thisObj, val, i, arr); } : src; case 'object': return function(val){ return deepMatches(val, src); }; case 'string': case 'number': return prop(src); } } module.exports = makeIterator; },{"../object/deepMatches":21,"./identity":10,"./prop":12}],12:[function(require,module,exports){ /** * Returns a function that gets a property of the passed object */ function prop(name){ return function(obj){ return obj[name]; }; } module.exports = prop; },{}],13:[function(require,module,exports){ var isKind = require('./isKind'); /** */ var isArray = Array.isArray || function (val) { return isKind(val, 'Array'); }; module.exports = isArray; },{"./isKind":17}],14:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isBoolean(val) { return isKind(val, 'Boolean'); } module.exports = isBoolean; },{"./isKind":17}],15:[function(require,module,exports){ var forOwn = require('../object/forOwn'); var isArray = require('./isArray'); function isEmpty(val){ if (val == null) { // typeof null == 'object' so we check it first return false; } else if ( typeof val === 'string' || isArray(val) ) { return !val.length; } else if ( typeof val === 'object' || typeof val === 'function' ) { var result = true; forOwn(val, function(){ result = false; return false; // break loop }); return result; } else { return false; } } module.exports = isEmpty; },{"../object/forOwn":24,"./isArray":13}],16:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isFunction(val) { return isKind(val, 'Function'); } module.exports = isFunction; },{"./isKind":17}],17:[function(require,module,exports){ var kindOf = require('./kindOf'); /** * Check if value is from a specific "kind". */ function isKind(val, kind){ return kindOf(val) === kind; } module.exports = isKind; },{"./kindOf":19}],18:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],19:[function(require,module,exports){ var _rKind = /^\[object (.*)\]$/, _toString = Object.prototype.toString, UNDEF; /** * Gets the "kind" of value. (e.g. "String", "Number", etc) */ function kindOf(val) { if (val === null) { return 'Null'; } else if (val === UNDEF) { return 'Undefined'; } else { return _rKind.exec( _toString.call(val) )[1]; } } module.exports = kindOf; },{}],20:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],21:[function(require,module,exports){ var forOwn = require('./forOwn'); var isArray = require('../lang/isArray'); function containsMatch(array, pattern) { var i = -1, length = array.length; while (++i < length) { if (deepMatches(array[i], pattern)) { return true; } } return false; } function matchArray(target, pattern) { var i = -1, patternLength = pattern.length; while (++i < patternLength) { if (!containsMatch(target, pattern[i])) { return false; } } return true; } function matchObject(target, pattern) { var result = true; forOwn(pattern, function(val, key) { if (!deepMatches(target[key], val)) { // Return false to break out of forOwn early return (result = false); } }); return result; } /** * Recursively check if the objects match. */ function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } } module.exports = deepMatches; },{"../lang/isArray":13,"./forOwn":24}],22:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ 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; },{"../lang/isPlainObject":18,"./forOwn":24}],23:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed 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++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. 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; },{"./hasOwn":25}],24:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ 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; },{"./forIn":23,"./hasOwn":25}],25:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],26:[function(require,module,exports){ var forEach = require('../array/forEach'); /** * Create nested object if non-existent */ 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; },{"../array/forEach":4}],27:[function(require,module,exports){ var slice = require('../array/slice'); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ 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; },{"../array/slice":7}],28:[function(require,module,exports){ var namespace = require('./namespace'); /** * set "nested" object property */ 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; },{"./namespace":26}],29:[function(require,module,exports){ var toString = require('../lang/toString'); var replaceAccents = require('./replaceAccents'); var removeNonWord = require('./removeNonWord'); var upperCase = require('./upperCase'); var lowerCase = require('./lowerCase'); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; },{"../lang/toString":20,"./lowerCase":30,"./removeNonWord":33,"./replaceAccents":34,"./upperCase":35}],30:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; },{"../lang/toString":20}],31:[function(require,module,exports){ var join = require('../array/join'); var slice = require('../array/slice'); /** * Group arguments as path segments, if any of the args is `null` or an * empty string it will be ignored from resulting path. */ function makePath(var_args){ var result = join(slice(arguments), '/'); // need to disconsider duplicate '/' after protocol (eg: 'http://') return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } module.exports = makePath; },{"../array/join":6,"../array/slice":7}],32:[function(require,module,exports){ var toString = require('../lang/toString'); var camelCase = require('./camelCase'); var upperCase = require('./upperCase'); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; },{"../lang/toString":20,"./camelCase":29,"./upperCase":35}],33:[function(require,module,exports){ var toString = require('../lang/toString'); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; },{"../lang/toString":20}],34:[function(require,module,exports){ var toString = require('../lang/toString'); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them 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; },{"../lang/toString":20}],35:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":20}],36:[function(require,module,exports){ /** * @doc function * @id DSHttpAdapterProvider * @name DSHttpAdapterProvider */ function DSHttpAdapterProvider() { /** * @doc property * @id DSHttpAdapterProvider.properties:defaults * @name defaults * @description * Default configuration for this adapter. * * Properties: * * - `{function}` - `queryTransform` - See [the guide](/documentation/guide/adapters/index). Default: No-op. */ var defaults = this.defaults = { /** * @doc property * @id DSHttpAdapterProvider.properties:defaults.queryTransform * @name defaults.queryTransform * @description * Transform the angular-data query to something your server understands. You might just do this on the server instead. * * ## Example: * ```js * DSHttpAdapterProvider.defaults.queryTransform = function (resourceName, params) { * if (params && params.userId) { * params.user_id = params.userId; * delete params.userId; * } * return params; * }; * ``` * * @param {string} resourceName The name of the resource. * @param {object} params Params that will be passed to `$http`. * @returns {*} By default just returns `params` as-is. */ queryTransform: function (resourceName, params) { return params; }, /** * @doc property * @id DSHttpAdapterProvider.properties:defaults.$httpConfig * @name defaults.$httpConfig * @description * Default `$http` configuration options used whenever `DSHttpAdapter` uses `$http`. * * ## Example: * ```js * angular.module('myApp').config(function (DSHttpAdapterProvider) { * angular.extend(DSHttpAdapterProvider.defaults.$httpConfig, { * interceptor: [...], * headers: { * Authorization: 'Basic YmVlcDpib29w' * }, * timeout: 20000 * }); * }); * ``` */ $httpConfig: {} }; this.$get = ['$http', '$log', 'DSUtils', function ($http, $log, DSUtils) { /** * @doc interface * @id DSHttpAdapter * @name DSHttpAdapter * @description * Default adapter used by angular-data. This adapter uses AJAX and JSON to send/retrieve data to/from a server. * Developers may provide custom adapters that implement the adapter interface. */ return { /** * @doc property * @id DSHttpAdapter.properties:defaults * @name defaults * @description * Reference to [DSHttpAdapterProvider.defaults](/documentation/api/api/DSHttpAdapterProvider.properties:defaults). */ defaults: defaults, /** * @doc method * @id DSHttpAdapter.methods:HTTP * @name HTTP * @description * A wrapper for `$http()`. * * ## Signature: * ```js * DSHttpAdapter.HTTP(config) * ``` * * @param {object} config Configuration object. * @returns {Promise} Promise. */ HTTP: function (config) { var start = new Date().getTime(); config = DSUtils.deepMixIn(config, defaults.$httpConfig); return $http(config).then(function (data) { $log.debug(data.config.method + ' request:' + data.config.url + ' Time taken: ' + (new Date().getTime() - start) + 'ms', arguments); return data; }); }, /** * @doc method * @id DSHttpAdapter.methods:GET * @name GET * @description * A wrapper for `$http.get()`. * * ## Signature: * ```js * DSHttpAdapter.GET(url[, config]) * ``` * * @param {string} url The url of the request. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ GET: function (url, config) { config = config || {}; return this.HTTP(DSUtils.deepMixIn(config, { url: url, method: 'GET' })); }, /** * @doc method * @id DSHttpAdapter.methods:POST * @name POST * @description * A wrapper for `$http.post()`. * * ## Signature: * ```js * DSHttpAdapter.POST(url[, attrs][, config]) * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ POST: function (url, attrs, config) { config = config || {}; return this.HTTP(DSUtils.deepMixIn(config, { url: url, data: attrs, method: 'POST' })); }, /** * @doc method * @id DSHttpAdapter.methods:PUT * @name PUT * @description * A wrapper for `$http.put()`. * * ## Signature: * ```js * DSHttpAdapter.PUT(url[, attrs][, config]) * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ PUT: function (url, attrs, config) { config = config || {}; return this.HTTP(DSUtils.deepMixIn(config, { url: url, data: attrs || {}, method: 'PUT' })); }, /** * @doc method * @id DSHttpAdapter.methods:DEL * @name DEL * @description * A wrapper for `$http.delete()`. * * ## Signature: * ```js * DSHttpAdapter.DEL(url[, config]) * ``` * * @param {string} url The url of the request. * @param {object=} config Optional configuration. * @returns {Promise} Promise. */ DEL: function (url, config) { config = config || {}; return this.HTTP(DSUtils.deepMixIn(config, { url: url, method: 'DELETE' })); }, /** * @doc method * @id DSHttpAdapter.methods:find * @name find * @description * Retrieve a single entity from the server. * * Makes a `GET` request. * * ## Signature: * ```js * DSHttpAdapter.find(resourceConfig, id[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to update. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ find: function (resourceConfig, id, options) { options = options || {}; return this.GET( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(id, options), id), options ); }, /** * @doc method * @id DSHttpAdapter.methods:findAll * @name findAll * @description * Retrieve a collection of entities from the server. * * Makes a `GET` request. * * ## Signature: * ```js * DSHttpAdapter.findAll(resourceConfig[, params][, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object=} params Search query parameters. See the [query guide](/documentation/guide/queries/index). * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ findAll: function (resourceConfig, params, options) { options = options || {}; options.params = options.params || {}; if (params) { params = defaults.queryTransform(resourceConfig.name, params); DSUtils.deepMixIn(options.params, params); } return this.GET( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(null, options)), options ); }, /** * @doc method * @id DSHttpAdapter.methods:create * @name create * @description * Create a new entity on the server. * * Makes a `POST` request. * * ## Signature: * ```js * DSHttpAdapter.create(resourceConfig, attrs[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs The attribute payload. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ create: function (resourceConfig, attrs, options) { options = options || {}; return this.POST( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(attrs, options)), attrs, options ); }, /** * @doc method * @id DSHttpAdapter.methods:update * @name update * @description * Update an entity on the server. * * Makes a `PUT` request. * * ## Signature: * ```js * DSHttpAdapter.update(resourceConfig, id, attrs[, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to update. * @param {object} attrs The attribute payload. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ update: function (resourceConfig, id, attrs, options) { options = options || {}; return this.PUT( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(id, options), id), attrs, options ); }, /** * @doc method * @id DSHttpAdapter.methods:updateAll * @name updateAll * @description * Update a collection of entities on the server. * * Makes a `PUT` request. * * ## Signature: * ```js * DSHttpAdapter.updateAll(resourceConfig, attrs[, params][, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs The attribute payload. * @param {object=} params Search query parameters. See the [query guide](/documentation/guide/queries/index). * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ updateAll: function (resourceConfig, attrs, params, options) { options = options || {}; options.params = options.params || {}; if (params) { params = defaults.queryTransform(resourceConfig.name, params); DSUtils.deepMixIn(options.params, params); } return this.PUT( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(null, options)), attrs, options ); }, /** * @doc method * @id DSHttpAdapter.methods:destroy * @name destroy * @description * Delete an entity on the server. * * Makes a `DELETE` request. * * ## Signature: * ```js * DSHttpAdapter.destroy(resourceConfig, id[, options) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to update. * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ destroy: function (resourceConfig, id, options) { options = options || {}; return this.DEL( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(id, options), id), options ); }, /** * @doc method * @id DSHttpAdapter.methods:destroyAll * @name destroyAll * @description * Delete a collection of entities on the server. * * Makes `DELETE` request. * * ## Signature: * ```js * DSHttpAdapter.destroyAll(resourceConfig[, params][, options]) * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object=} params Search query parameters. See the [query guide](/documentation/guide/queries/index). * @param {object=} options Optional configuration. Also passed along to `$http([config])`. Properties: * * - `{string=}` - `baseUrl` - Base url to use. * - `{object=}` - `params` - Additional query string parameters to add to the url. * * @returns {Promise} Promise. */ destroyAll: function (resourceConfig, params, options) { options = options || {}; options.params = options.params || {}; if (params) { params = defaults.queryTransform(resourceConfig.name, params); DSUtils.deepMixIn(options.params, params); } return this.DEL( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(null, options)), options ); } }; }]; } module.exports = DSHttpAdapterProvider; },{}],37:[function(require,module,exports){ /*! * @doc function * @id DSLocalStorageAdapterProvider * @name DSLocalStorageAdapterProvider */ function DSLocalStorageAdapterProvider() { this.$get = ['$q', 'DSUtils', 'DSErrors', function ($q, DSUtils, DSErrors) { /** * @doc interface * @id DSLocalStorageAdapter * @name DSLocalStorageAdapter * @description * Adapter that uses `localStorage` as its persistence layer. The localStorage adapter does not support operations * on collections because localStorage itself is a key-value store. */ return { /** * @doc method * @id DSLocalStorageAdapter.methods:GET * @name GET * @description * An asynchronous wrapper for `localStorage.getItem(key)`. * * ## Signature: * ```js * DSLocalStorageAdapter.GET(key) * ``` * * @param {string} key The key path of the item to retrieve. * @returns {Promise} Promise. */ GET: function (key) { var deferred = $q.defer(); try { var item = localStorage.getItem(key); deferred.resolve(item ? angular.fromJson(item) : undefined); } catch (err) { deferred.reject(err); } return deferred.promise; }, /** * @doc method * @id DSLocalStorageAdapter.methods:PUT * @name PUT * @description * An asynchronous wrapper for `localStorage.setItem(key, value)`. * * ## Signature: * ```js * DSLocalStorageAdapter.PUT(key, value) * ``` * * @param {string} key The key to update. * @param {object} value Attributes to put. * @returns {Promise} Promise. */ PUT: function (key, value) { var DSLocalStorageAdapter = this; return DSLocalStorageAdapter.GET(key).then(function (item) { if (item) { DSUtils.deepMixIn(item, value); } localStorage.setItem(key, angular.toJson(item || value)); return DSLocalStorageAdapter.GET(key); }); }, /** * @doc method * @id DSLocalStorageAdapter.methods:DEL * @name DEL * @description * An asynchronous wrapper for `localStorage.removeItem(key)`. * * ## Signature: * ```js * DSLocalStorageAdapter.DEL(key) * ``` * * @param {string} key The key to remove. * @returns {Promise} Promise. */ DEL: function (key) { var deferred = $q.defer(); try { localStorage.removeItem(key); deferred.resolve(); } catch (err) { deferred.reject(err); } return deferred.promise; }, /** * @doc method * @id DSLocalStorageAdapter.methods:find * @name find * @description * Retrieve a single entity from localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.find(resourceConfig, id[, options]) * ``` * * ## Example: * ```js * DS.find('user', 5, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 5, ... } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to retrieve. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ find: function find(resourceConfig, id, options) { options = options || {}; return this.GET(DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.endpoint, id)); }, /** * @doc method * @id DSLocalStorageAdapter.methods:findAll * @name findAll * @description * Not supported. */ findAll: function () { throw new Error('DSLocalStorageAdapter.findAll is not supported!'); }, /** * @doc method * @id DSLocalStorageAdapter.methods:create * @name create * @description * Create an entity in `localStorage`. You must generate the primary key and include it in the `attrs` object. * * ## Signature: * ```js * DSLocalStorageAdapter.create(resourceConfig, attrs[, options]) * ``` * * ## Example: * ```js * DS.create('user', { * id: 1, * name: 'john' * }, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 1, name: 'john' } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {object} attrs Attributes to create in localStorage. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ create: function (resourceConfig, attrs, options) { if (!(resourceConfig.idAttribute in attrs)) { throw new DSErrors.IA('DSLocalStorageAdapter.create: You must provide a primary key in the attrs object!'); } options = options || {}; return this.PUT( DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(attrs, options), attrs[resourceConfig.idAttribute]), attrs ); }, /** * @doc method * @id DSLocalStorageAdapter.methods:update * @name update * @description * Update an entity in localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.update(resourceConfig, id, attrs[, options]) * ``` * * ## Example: * ```js * DS.update('user', 5, { * name: 'john' * }, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 5, ... } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to retrieve. * @param {object} attrs Attributes with which to update the entity. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ update: function (resourceConfig, id, attrs, options) { options = options || {}; return this.PUT(DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(id, options), id), attrs); }, /** * @doc method * @id DSLocalStorageAdapter.methods:updateAll * @name updateAll * @description * Not supported. */ updateAll: function () { throw new Error('DSLocalStorageAdapter.updateAll is not supported!'); }, /** * @doc method * @id DSLocalStorageAdapter.methods:destroy * @name destroy * @description * Destroy an entity from localStorage. * * ## Signature: * ```js * DSLocalStorageAdapter.destroy(resourceConfig, id[, options]) * ``` * * ## Example: * ```js * DS.destroy('user', 5, { * name: '' * }, { * adapter: 'DSLocalStorageAdapter' * }).then(function (user) { * user; // { id: 5, ... } * }); * ``` * * @param {object} resourceConfig DS resource definition object: * @param {string|number} id Primary key of the entity to destroy. * @param {object=} options Optional configuration. Properties: * * - `{string=}` - `baseUrl` - Base path to use. * * @returns {Promise} Promise. */ destroy: function (resourceConfig, id, options) { options = options || {}; return this.DEL(DSUtils.makePath(options.baseUrl || resourceConfig.baseUrl, resourceConfig.getEndpoint(id, options), id)); }, /** * @doc method * @id DSLocalStorageAdapter.methods:destroyAll * @name destroyAll * @description * Not supported. */ destroyAll: function () { throw new Error('Not supported!'); } }; }]; } module.exports = DSLocalStorageAdapterProvider; },{}],38:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.create(' + resourceName + ', attrs[, options]): '; } /** * @doc method * @id DS.async methods:create * @name create * @description * The "C" in "CRUD". Delegate to the `create` method of whichever adapter is being used (http by default) and inject the * result into the data store. * * ## Signature: * ```js * DS.create(resourceName, attrs[, options]) * ``` * * ## Example: * * ```js * DS.create('document', { * author: 'John Anderson' * }).then(function (document) { * document; // { id: 5, author: 'John Anderson' } * * // The new document is already in the data store * DS.get('document', document.id); // { id: 5, author: 'John Anderson' } * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} attrs The attributes with which to create the item of the type specified by `resourceName`. * @param {object=} options Configuration options. Also passed along to the adapter's `create` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * - `{boolean=}` - `upsert` - If `attrs` already contains a primary key, then attempt to call `DS.update` instead. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - A reference to the newly created item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function create(resourceName, attrs, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; var definition = DS.definitions[resourceName]; try { options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(attrs)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'attrs: Must be an object!'); } var resource = DS.store[resourceName]; if (!('cacheResponse' in options)) { options.cacheResponse = true; } if (!('upsert' in options)) { options.upsert = true; } if (options.upsert && attrs[definition.idAttribute]) { promise = DS.update(resourceName, attrs[definition.idAttribute], attrs, options); } else { promise = promise .then(function (attrs) { return DS.$q.promisify(definition.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.validate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.beforeCreate)(resourceName, attrs); }) .then(function (attrs) { return DS.adapters[options.adapter || definition.defaultAdapter].create(definition, definition.serialize(resourceName, attrs), options); }) .then(function (res) { return DS.$q.promisify(definition.afterCreate)(resourceName, definition.deserialize(resourceName, res)); }) .then(function (data) { if (options.cacheResponse) { var created = DS.inject(definition.name, data); var id = created[definition.idAttribute]; resource.completedQueries[id] = new Date().getTime(); resource.previousAttributes[id] = DS.utils.deepMixIn({}, created); resource.saved[id] = DS.utils.updateTimestamp(resource.saved[id]); return DS.get(definition.name, id); } else { return data; } }); } deferred.resolve(attrs); } catch (err) { deferred.reject(err); } return promise; } module.exports = create; },{}],39:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.destroy(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:destroy * @name destroy * @description * The "D" in "CRUD". Delegate to the `destroy` method of whichever adapter is being used (http by default) and eject the * appropriate item from the data store. * * ## Signature: * ```js * DS.destroy(resourceName, id[, options]); * ``` * * ## Example: * * ```js * DS.destroy('document', 5).then(function (id) { * id; // 5 * * // The document is gone * DS.get('document', 5); // undefined * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to remove. * @param {object=} options Configuration options. Also passed along to the adapter's `destroy` method. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{string|number}` - `id` - The primary key of the destroyed item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{NonexistentResourceError}` */ function destroy(resourceName, id, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; var definition = DS.definitions[resourceName]; try { options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } var item = DS.get(resourceName, id); if (!item) { throw new DS.errors.R(errorPrefix(resourceName, id) + 'id: "' + id + '" not found!'); } promise = promise .then(function (attrs) { return DS.$q.promisify(definition.beforeDestroy)(resourceName, attrs); }) .then(function () { return DS.adapters[options.adapter || definition.defaultAdapter].destroy(definition, id, options); }) .then(function () { return DS.$q.promisify(definition.afterDestroy)(resourceName, item); }) .then(function () { DS.eject(resourceName, id); return id; }); deferred.resolve(item); } catch (err) { deferred.reject(err); } return promise; } module.exports = destroy; },{}],40:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.destroyAll(' + resourceName + ', params[, options]): '; } /** * @doc method * @id DS.async methods:destroyAll * @name destroyAll * @description * The "D" in "CRUD". Delegate to the `destroyAll` method of whichever adapter is being used (http by default) and eject * the appropriate items from the data store. * * ## Signature: * ```js * DS.destroyAll(resourceName, params[, options]) * ``` * * ## Example: * * ```js * var params = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.destroyAll('document', params).then(function (documents) { * // The documents are gone from the data store * DS.filter('document', params); // [] * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is serialized into the query string. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Also passed along to the adapter's `destroyAll` method. Properties: * * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function destroyAll(resourceName, params, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; var definition = DS.definitions[resourceName]; try { var IA = DS.errors.IA; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } promise = promise .then(function () { return DS.adapters[options.adapter || definition.defaultAdapter].destroyAll(definition, params, options); }) .then(function () { return DS.ejectAll(resourceName, params); }); deferred.resolve(); } catch (err) { deferred.reject(err); } return promise; } module.exports = destroyAll; },{}],41:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.find(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:find * @name find * @description * The "R" in "CRUD". Delegate to the `find` method of whichever adapter is being used (http by default) and inject the * resulting item into the data store. * * ## Signature: * ```js * DS.find(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5); // undefined * DS.find('document', 5).then(function (document) { * document; // { id: 5, author: 'John Anderson' } * * // the document is now in the data store * DS.get('document', 5); // { id: 5, author: 'John Anderson' } * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Also passed along to the adapter's `find` method. Properties: * * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function find(resourceName, id, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; try { var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } if (!('cacheResponse' in options)) { options.cacheResponse = true; } var definition = DS.definitions[resourceName]; var resource = DS.store[resourceName]; if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (!(id in resource.completedQueries)) { if (!(id in resource.pendingQueries)) { promise = resource.pendingQueries[id] = DS.adapters[options.adapter || definition.defaultAdapter].find(definition, id, options) .then(function (res) { var data = definition.deserialize(resourceName, res); if (options.cacheResponse) { // Query is no longer pending delete resource.pendingQueries[id]; resource.completedQueries[id] = new Date().getTime(); return DS.inject(resourceName, data); } else { return data; } }, function (err) { delete resource.pendingQueries[id]; return DS.$q.reject(err); }); } return resource.pendingQueries[id]; } else { deferred.resolve(DS.get(resourceName, id)); } } catch (err) { deferred.reject(err); } return promise; } module.exports = find; },{}],42:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.findAll(' + resourceName + ', params[, options]): '; } function processResults(data, resourceName, queryHash) { var DS = this; var resource = DS.store[resourceName]; var idAttribute = DS.definitions[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DS.utils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = DS.inject(resourceName, data); // Make sure each object is added to completedQueries if (DS.utils.isArray(injected)) { angular.forEach(injected, function (item) { if (item && item[idAttribute]) { resource.completedQueries[item[idAttribute]] = date; } }); } else { DS.$log.warn(errorPrefix(resourceName) + 'response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function _findAll(resourceName, params, options) { var DS = this; var definition = DS.definitions[resourceName]; var resource = DS.store[resourceName]; var queryHash = DS.utils.toJson(params); if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; } if (!(queryHash in resource.completedQueries)) { // This particular query has never been completed if (!(queryHash in resource.pendingQueries)) { // This particular query has never even been made resource.pendingQueries[queryHash] = DS.adapters[options.adapter || definition.defaultAdapter].findAll(definition, params, options) .then(function (res) { var data = definition.deserialize(resourceName, res); if (options.cacheResponse) { try { return processResults.apply(DS, [data, resourceName, queryHash]); } catch (err) { return DS.$q.reject(err); } } else { return data; } }, function (err) { delete resource.pendingQueries[queryHash]; return DS.$q.reject(err); }); } return resource.pendingQueries[queryHash]; } else { return DS.filter(resourceName, params, options); } } /** * @doc method * @id DS.async methods:findAll * @name findAll * @description * The "R" in "CRUD". Delegate to the `findAll` method of whichever adapter is being used (http by default) and inject * the resulting collection into the data store. * * ## Signature: * ```js * DS.findAll(resourceName, params[, options]) * ``` * * ## Example: * * ```js * var params = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.filter('document', params); // [] * DS.findAll('document', params).then(function (documents) { * documents; // [{ id: '1', author: 'John Anderson', title: 'How to cook' }, * // { id: '2', author: 'John Anderson', title: 'How NOT to cook' }] * * // The documents are now in the data store * DS.filter('document', params); // [{ id: '1', author: 'John Anderson', title: 'How to cook' }, * // { id: '2', author: 'John Anderson', title: 'How NOT to cook' }] * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} params Parameter object that is serialized into the query string. Default properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Also passed along to the adapter's `findAll` method. Properties: * * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{array}` - `items` - The collection of items returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function findAll(resourceName, params, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; try { var IA = DS.errors.IA; options = options || {}; params = params || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } if (!('cacheResponse' in options)) { options.cacheResponse = true; } promise = promise.then(function () { return _findAll.apply(DS, [resourceName, params, options]); }); deferred.resolve(); } catch (err) { deferred.reject(err); } return promise; } module.exports = findAll; },{}],43:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.async methods:create * @name create * @methodOf DS * @description * See [DS.create](/documentation/api/api/DS.async methods:create). */ create: require('./create'), /** * @doc method * @id DS.async methods:destroy * @name destroy * @methodOf DS * @description * See [DS.destroy](/documentation/api/api/DS.async methods:destroy). */ destroy: require('./destroy'), /** * @doc method * @id DS.async methods:destroyAll * @name destroyAll * @methodOf DS * @description * See [DS.destroyAll](/documentation/api/api/DS.async methods:destroyAll). */ destroyAll: require('./destroyAll'), /** * @doc method * @id DS.async methods:find * @name find * @methodOf DS * @description * See [DS.find](/documentation/api/api/DS.async methods:find). */ find: require('./find'), /** * @doc method * @id DS.async methods:findAll * @name findAll * @methodOf DS * @description * See [DS.findAll](/documentation/api/api/DS.async methods:findAll). */ findAll: require('./findAll'), /** * @doc method * @id DS.async methods:loadRelations * @name loadRelations * @methodOf DS * @description * See [DS.loadRelations](/documentation/api/api/DS.async methods:loadRelations). */ loadRelations: require('./loadRelations'), /** * @doc method * @id DS.async methods:refresh * @name refresh * @methodOf DS * @description * See [DS.refresh](/documentation/api/api/DS.async methods:refresh). */ refresh: require('./refresh'), /** * @doc method * @id DS.async methods:save * @name save * @methodOf DS * @description * See [DS.save](/documentation/api/api/DS.async methods:save). */ save: require('./save'), /** * @doc method * @id DS.async methods:update * @name update * @methodOf DS * @description * See [DS.update](/documentation/api/api/DS.async methods:update). */ update: require('./update'), /** * @doc method * @id DS.async methods:updateAll * @name updateAll * @methodOf DS * @description * See [DS.updateAll](/documentation/api/api/DS.async methods:updateAll). */ updateAll: require('./updateAll') }; },{"./create":38,"./destroy":39,"./destroyAll":40,"./find":41,"./findAll":42,"./loadRelations":44,"./refresh":45,"./save":46,"./update":47,"./updateAll":48}],44:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.loadRelations(' + resourceName + ', instance(Id), relations[, options]): '; } /** * @doc method * @id DS.async methods:loadRelations * @name loadRelations * @description * Asynchronously load the indicated relations of the given instance. * * ## Signature: * ```js * DS.loadRelations(resourceName, instance|id, relations[, options]) * ``` * * ## Examples: * * ```js * DS.loadRelations('user', 10, ['profile']).then(function (user) { * user.profile; // object * assert.deepEqual(user.profile, DS.filter('profile', { userId: 10 })[0]); * }); * ``` * * ```js * var user = DS.get('user', 10); * * DS.loadRelations('user', user, ['profile']).then(function (user) { * user.profile; // object * assert.deepEqual(user.profile, DS.filter('profile', { userId: 10 })[0]); * }); * ``` * * ```js * DS.loadRelations('user', 10, ['profile'], { cacheResponse: false }).then(function (user) { * user.profile; // object * assert.equal(DS.filter('profile', { userId: 10 }).length, 0); * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number|object} instance The instance or the id of the instance for which relations are to be loaded. * @param {string|array=} relations The relation(s) to load. * @param {object=} options Optional configuration. Also passed along to the adapter's `find` or `findAll` methods. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The instance with its loaded relations. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function loadRelations(resourceName, instance, relations, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; var definition = DS.definitions[resourceName]; try { var IA = DS.errors.IA; options = options || {}; if (angular.isString(instance) || angular.isNumber(instance)) { instance = DS.get(resourceName, instance); } if (angular.isString(relations)) { relations = [relations]; } if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(instance)) { throw new IA(errorPrefix(resourceName) + 'instance(Id): Must be a string, number or object!'); } else if (!DS.utils.isArray(relations)) { throw new IA(errorPrefix(resourceName) + 'relations: Must be a string or an array!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } var tasks = []; var fields = []; DS.utils.forOwn(definition.relations, function (relatedModels, type) { DS.utils.forOwn(relatedModels, function (defs, relationName) { if (!DS.utils.isArray(defs)) { defs = [defs]; } defs.forEach(function (def) { if (DS.utils.contains(relations, relationName)) { var task; var params = {}; params[def.foreignKey] = instance[definition.idAttribute]; if (type === 'hasMany') { task = DS.findAll(relationName, params, options); } else if (type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = DS.find(relationName, instance[def.localKey], options); } else if (def.foreignKey) { task = DS.findAll(relationName, params, options); } } else { task = DS.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); }); }); promise = promise .then(function () { return DS.$q.all(tasks); }) .then(function (loadedRelations) { angular.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); deferred.resolve(); } catch (err) { deferred.reject(err); } return promise; } module.exports = loadRelations; },{}],45:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.refresh(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:refresh * @name refresh * @description * Like `DS.find`, except the resource is only refreshed from the adapter if it already exists in the data store. * * ## Signature: * ```js * DS.refresh(resourceName, id[, options]) * ``` * ## Example: * * ```js * // Exists in the data store, but we want a fresh copy * DS.get('document', 5); * * DS.refresh('document', 5).then(function (document) { * document; // The fresh copy * }); * * // Does not exist in the data store * DS.get('document', 6); // undefined * * DS.refresh('document', 6).then(function (document) { * document; // undefined * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to refresh from the adapter. * @param {object=} options Optional configuration. Also passed along to the adapter's `find` method. * @returns {Promise} A Promise created by the $q service. * * ## Resolves with: * * - `{object|undefined}` - `item` - The item returned by the adapter or `undefined` if the item wasn't already in the * data store. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function refresh(resourceName, id, options) { var DS = this; var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } else { options.bypassCache = true; if (DS.get(resourceName, id)) { return DS.find(resourceName, id, options); } else { var deferred = DS.$q.defer(); deferred.resolve(); return deferred.promise; } } } module.exports = refresh; },{}],46:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.save(' + resourceName + ', ' + id + '[, options]): '; } /** * @doc method * @id DS.async methods:save * @name save * @description * The "U" in "CRUD". Persist a single item already in the store and in it's current form to whichever adapter is being * used (http by default) and inject the resulting item into the data store. * * ## Signature: * ```js * DS.save(resourceName, id[, options]) * ``` * * ## Example: * * ```js * var document = DS.get('document', 5); * * document.title = 'How to cook in style'; * * DS.save('document', 5).then(function (document) { * document; // A reference to the document that's been persisted via an adapter * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to save. * @param {object=} options Optional configuration. Also passed along to the adapter's `update` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * - `{boolean=}` - `changesOnly` - Only send changed and added values to the adapter. Default: `false`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{NonexistentResourceError}` */ function save(resourceName, id, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; var definition = DS.definitions[resourceName]; try { var IA = DS.errors.IA; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } var item = DS.get(resourceName, id); if (!item) { throw new DS.errors.R(errorPrefix(resourceName, id) + 'id: "' + id + '" not found!'); } var resource = DS.store[resourceName]; if (!('cacheResponse' in options)) { options.cacheResponse = true; } promise = promise .then(function (attrs) { return DS.$q.promisify(definition.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.validate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.beforeUpdate)(resourceName, attrs); }) .then(function (attrs) { if (options.changesOnly) { resource.observers[id].deliver(); var toKeep = [], changes = DS.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DS.utils.pick(attrs, toKeep); if (DS.utils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return DS.adapters[options.adapter || definition.defaultAdapter].update(definition, id, definition.serialize(resourceName, attrs), options); }) .then(function (res) { return DS.$q.promisify(definition.afterUpdate)(resourceName, definition.deserialize(resourceName, res)); }) .then(function (data) { if (options.cacheResponse) { var saved = DS.inject(definition.name, data, options); resource.previousAttributes[id] = DS.utils.deepMixIn({}, saved); resource.saved[id] = DS.utils.updateTimestamp(resource.saved[id]); return DS.get(resourceName, id); } else { return data; } }); deferred.resolve(item); } catch (err) { deferred.reject(err); } return promise; } module.exports = save; },{}],47:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.update(' + resourceName + ', ' + id + ', attrs[, options]): '; } /** * @doc method * @id DS.async methods:update * @name update * @description * The "U" in "CRUD". Update the item of type `resourceName` and primary key `id` with `attrs`. This is useful when you * want to update an item that isn't already in the data store, or you don't want to update the item that's in the data * store until the adapter operation succeeds. This differs from `DS.save` which simply saves items in their current * form that already exist in the data store. The resulting item (by default) will be injected into the data store. * * ## Signature: * ```js * DS.update(resourceName, id, attrs[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5); // undefined * * DS.update('document', 5, { * title: 'How to cook in style' * }).then(function (document) { * document; // A reference to the document that's been saved via an adapter * // and now resides in the data store * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to update. * @param {object} attrs The attributes with which to update the item. * @param {object=} options Optional configuration. Also passed along to the adapter's `update` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the data returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function update(resourceName, id, attrs, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; try { var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DS.utils.isObject(attrs)) { throw new IA(errorPrefix(resourceName, id) + 'attrs: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } var definition = DS.definitions[resourceName]; var resource = DS.store[resourceName]; if (!('cacheResponse' in options)) { options.cacheResponse = true; } promise = promise .then(function (attrs) { return DS.$q.promisify(definition.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.validate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.beforeUpdate)(resourceName, attrs); }) .then(function (attrs) { return DS.adapters[options.adapter || definition.defaultAdapter].update(definition, id, definition.serialize(resourceName, attrs), options); }) .then(function (res) { return DS.$q.promisify(definition.afterUpdate)(resourceName, definition.deserialize(resourceName, res)); }) .then(function (data) { if (options.cacheResponse) { var updated = DS.inject(definition.name, data, options); var id = updated[definition.idAttribute]; resource.previousAttributes[id] = DS.utils.deepMixIn({}, updated); resource.saved[id] = DS.utils.updateTimestamp(resource.saved[id]); return DS.get(definition.name, id); } else { return data; } }); deferred.resolve(attrs); } catch (err) { deferred.reject(err); } return promise; } module.exports = update; },{}],48:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.updateAll(' + resourceName + ', attrs, params[, options]): '; } /** * @doc method * @id DS.async methods:updateAll * @name updateAll * @description * The "U" in "CRUD". Update items of type `resourceName` with `attrs` according to the criteria specified by `params`. * This is useful when you want to update multiple items with the same attributes or you don't want to update the items * in the data store until the adapter operation succeeds. The resulting items (by default) will be injected into the * data store. * * ## Signature: * ```js * DS.updateAll(resourceName, attrs, params[, options]) * ``` * * ## Example: * * ```js * var params = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.filter('document', params); // [] * * DS.updateAll('document', 5, { * author: 'Sally' * }, params).then(function (documents) { * documents; // The documents that were updated via an adapter * // and now reside in the data store * * documents[0].author; // "Sally" * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} attrs The attributes with which to update the items. * @param {object} params Parameter object that is serialized into the query string. Default properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Also passed along to the adapter's `updateAll` method. Properties: * * - `{boolean=}` - `cacheResponse` - Inject the items returned by the adapter into the data store. Default: `true`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{array}` - `items` - The items returned by the adapter. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` */ function updateAll(resourceName, attrs, params, options) { var DS = this; var deferred = DS.$q.defer(); var promise = deferred.promise; try { var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(attrs)) { throw new IA(errorPrefix(resourceName) + 'attrs: Must be an object!'); } else if (!DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } var definition = DS.definitions[resourceName]; if (!('cacheResponse' in options)) { options.cacheResponse = true; } promise = promise .then(function (attrs) { return DS.$q.promisify(definition.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.validate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return DS.$q.promisify(definition.beforeUpdate)(resourceName, attrs); }) .then(function (attrs) { return DS.adapters[options.adapter || definition.defaultAdapter].updateAll(definition, definition.serialize(resourceName, attrs), params, options); }) .then(function (res) { return DS.$q.promisify(definition.afterUpdate)(resourceName, definition.deserialize(resourceName, res)); }) .then(function (data) { if (options.cacheResponse) { return DS.inject(definition.name, data, options); } else { return data; } }); deferred.resolve(attrs); } catch (err) { deferred.reject(err); } return promise; } module.exports = updateAll; },{}],49:[function(require,module,exports){ var utils = require('../utils')[0](); function lifecycleNoop(resourceName, attrs, cb) { cb(null, attrs); } function Defaults() { } Defaults.prototype.idAttribute = 'id'; Defaults.prototype.defaultAdapter = 'DSHttpAdapter'; Defaults.prototype.defaultFilter = function (collection, resourceName, params, options) { var _this = this; var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; if (this.utils.isObject(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { this.utils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (this.utils.isEmpty(where)) { where = null; } if (where) { filtered = this.utils.filter(filtered, function (attrs) { var first = true; var keep = true; _this.utils.forOwn(where, function (clause, field) { if (_this.utils.isString(clause)) { clause = { '===': clause }; } else if (_this.utils.isNumber(clause) || _this.utils.isBoolean(clause)) { clause = { '==': clause }; } if (_this.utils.isObject(clause)) { _this.utils.forOwn(clause, function (val, op) { if (op === '==') { keep = first ? (attrs[field] == val) : keep && (attrs[field] == val); } else if (op === '===') { keep = first ? (attrs[field] === val) : keep && (attrs[field] === val); } else if (op === '!=') { keep = first ? (attrs[field] != val) : keep && (attrs[field] != val); } else if (op === '!==') { keep = first ? (attrs[field] !== val) : keep && (attrs[field] !== val); } else if (op === '>') { keep = first ? (attrs[field] > val) : keep && (attrs[field] > val); } else if (op === '>=') { keep = first ? (attrs[field] >= val) : keep && (attrs[field] >= val); } else if (op === '<') { keep = first ? (attrs[field] < val) : keep && (attrs[field] < val); } else if (op === '<=') { keep = first ? (attrs[field] <= val) : keep && (attrs[field] <= val); } else if (op === 'in') { keep = first ? _this.utils.contains(val, attrs[field]) : keep && _this.utils.contains(val, attrs[field]); } else if (op === '|==') { keep = first ? (attrs[field] == val) : keep || (attrs[field] == val); } else if (op === '|===') { keep = first ? (attrs[field] === val) : keep || (attrs[field] === val); } else if (op === '|!=') { keep = first ? (attrs[field] != val) : keep || (attrs[field] != val); } else if (op === '|!==') { keep = first ? (attrs[field] !== val) : keep || (attrs[field] !== val); } else if (op === '|>') { keep = first ? (attrs[field] > val) : keep || (attrs[field] > val); } else if (op === '|>=') { keep = first ? (attrs[field] >= val) : keep || (attrs[field] >= val); } else if (op === '|<') { keep = first ? (attrs[field] < val) : keep || (attrs[field] < val); } else if (op === '|<=') { keep = first ? (attrs[field] <= val) : keep || (attrs[field] <= val); } else if (op === '|in') { keep = first ? _this.utils.contains(val, attrs[field]) : keep || _this.utils.contains(val, attrs[field]); } first = false; }); } }); return keep; }); } var orderBy = null; if (this.utils.isString(params.orderBy)) { orderBy = [ [params.orderBy, 'ASC'] ]; } else if (this.utils.isArray(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && this.utils.isString(params.sort)) { orderBy = [ [params.sort, 'ASC'] ]; } else if (!orderBy && this.utils.isArray(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { angular.forEach(orderBy, function (def) { if (_this.utils.isString(def)) { def = [def, 'ASC']; } else if (!_this.utils.isArray(def)) { throw new _this.errors.IllegalArgumentError('DS.filter(resourceName[, params][, options]): ' + angular.toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } filtered = _this.utils.sort(filtered, function (a, b) { var cA = a[def[0]], cB = b[def[0]]; if (_this.utils.isString(cA)) { cA = _this.utils.upperCase(cA); } if (_this.utils.isString(cB)) { cB = _this.utils.upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { return 0; } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { return 0; } } }); }); } var limit = angular.isNumber(params.limit) ? params.limit : null; var skip = null; if (angular.isNumber(params.skip)) { skip = params.skip; } else if (angular.isNumber(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = this.utils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (this.utils.isNumber(limit)) { filtered = this.utils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (this.utils.isNumber(skip)) { if (skip < filtered.length) { filtered = this.utils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; Defaults.prototype.baseUrl = ''; Defaults.prototype.endpoint = ''; Defaults.prototype.useClass = false; /** * @doc property * @id DSProvider.properties:defaults.beforeValidate * @name defaults.beforeValidate * @description * Called before the `validate` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeValidate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeValidate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeValidate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.validate * @name defaults.validate * @description * Called before the `afterValidate` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * validate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.validate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.validate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterValidate * @name defaults.afterValidate * @description * Called before the `beforeCreate` or `beforeUpdate` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterValidate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterValidate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterValidate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeCreate * @name defaults.beforeCreate * @description * Called before the `create` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeCreate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeCreate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeCreate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterCreate * @name defaults.afterCreate * @description * Called after the `create` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterCreate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterCreate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterCreate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeUpdate * @name defaults.beforeUpdate * @description * Called before the `update` or `save` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeUpdate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeUpdate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeUpdate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterUpdate * @name defaults.afterUpdate * @description * Called after the `update` or `save` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterUpdate(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterUpdate = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterUpdate = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeDestroy * @name defaults.beforeDestroy * @description * Called before the `destroy` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeDestroy(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.beforeDestroy = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeDestroy = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.afterDestroy * @name defaults.afterDestroy * @description * Called after the `destroy` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterDestroy(resourceName, attrs, cb) * ``` * * ## Callback signature: * ```js * cb(err, attrs) * ``` * Remember to pass the attributes along to the next step. Passing a first argument to the callback will abort the * lifecycle and reject the promise. * * ## Example: * ```js * DSProvider.defaults.afterDestroy = function (resourceName, attrs, cb) { * // do somthing/inspect attrs * cb(null, attrs); * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterDestroy = lifecycleNoop; /** * @doc property * @id DSProvider.properties:defaults.beforeInject * @name defaults.beforeInject * @description * Called before the `inject` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * beforeInject(resourceName, attrs) * ``` * * Throwing an error inside this step will cancel the injection. * * ## Example: * ```js * DSProvider.defaults.beforeInject = function (resourceName, attrs) { * // do somthing/inspect/modify attrs * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.beforeInject = function (resourceName, attrs) { return attrs; }; /** * @doc property * @id DSProvider.properties:defaults.afterInject * @name defaults.afterInject * @description * Called after the `inject` lifecycle step. Can be overridden per resource as well. * * ## Signature: * ```js * afterInject(resourceName, attrs) * ``` * * Throwing an error inside this step will cancel the injection. * * ## Example: * ```js * DSProvider.defaults.afterInject = function (resourceName, attrs) { * // do somthing/inspect/modify attrs * }; * ``` * * @param {string} resourceName The name of the resource moving through the lifecycle. * @param {object} attrs Attributes of the item moving through the lifecycle. */ Defaults.prototype.afterInject = function (resourceName, attrs) { return attrs; }; /** * @doc property * @id DSProvider.properties:defaults.serialize * @name defaults.serialize * @description * Your server might expect a custom request object rather than the plain POJO payload. Use `serialize` to * create your custom request object. * * ## Example: * ```js * DSProvider.defaults.serialize = function (resourceName, data) { * return { * payload: data * }; * }; * ``` * * @param {string} resourceName The name of the resource to serialize. * @param {object} data Data to be sent to the server. * @returns {*} By default returns `data` as-is. */ Defaults.prototype.serialize = function (resourceName, data) { return data; }; /** * @doc property * @id DSProvider.properties:defaults.deserialize * @name DSProvider.properties:defaults.deserialize * @description * Your server might return a custom response object instead of the plain POJO payload. Use `deserialize` to * pull the payload out of your response object so angular-data can use it. * * ## Example: * ```js * DSProvider.defaults.deserialize = function (resourceName, data) { * return data ? data.payload : data; * }; * ``` * * @param {string} resourceName The name of the resource to deserialize. * @param {object} data Response object from `$http()`. * @returns {*} By default returns `data.data`. */ Defaults.prototype.deserialize = function (resourceName, data) { return data.data; }; /** * @doc property * @id DSProvider.properties:defaults.events * @name DSProvider.properties:defaults.events * @description * Whether to broadcast, emit, or disable DS events on the `$rootScope`. * * Possible values are: `"broadcast"`, `"emit"`, `"none"`. * * `"broadcast"` events will be [broadcasted](https://code.angularjs.org/1.2.22/docs/api/ng/type/$rootScope.Scope#$broadcast) on the `$rootScope`. * * `"emit"` events will be [emitted](https://code.angularjs.org/1.2.22/docs/api/ng/type/$rootScope.Scope#$emit) on the `$rootScope`. * * `"none"` events will be will neither be broadcasted nor emitted. * * Current events are `"DS.inject"` and `"DS.eject"`. * * Overridable per resource. */ Defaults.prototype.events = 'broadcast'; /** * @doc function * @id DSProvider * @name DSProvider */ function DSProvider() { /** * @doc property * @id DSProvider.properties:defaults * @name defaults * @description * See the [configuration guide](/documentation/guide/configure/global). * * Properties: * * - `{string}` - `baseUrl` - The url relative to which all AJAX requests will be made. * - `{string}` - `idAttribute` - Default: `"id"` - The attribute that specifies the primary key for resources. * - `{string}` - `defaultAdapter` - Default: `"DSHttpAdapter"` * - `{string}` - `events` - Default: `"broadcast"` [DSProvider.defaults.events](/documentation/api/angular-data/DSProvider.properties:defaults.events) * - `{function}` - `filter` - Default: See [angular-data query language](/documentation/guide/queries/custom). * - `{function}` - `beforeValidate` - See [DSProvider.defaults.beforeValidate](/documentation/api/angular-data/DSProvider.properties:defaults.beforeValidate). Default: No-op * - `{function}` - `validate` - See [DSProvider.defaults.validate](/documentation/api/angular-data/DSProvider.properties:defaults.validate). Default: No-op * - `{function}` - `afterValidate` - See [DSProvider.defaults.afterValidate](/documentation/api/angular-data/DSProvider.properties:defaults.afterValidate). Default: No-op * - `{function}` - `beforeCreate` - See [DSProvider.defaults.beforeCreate](/documentation/api/angular-data/DSProvider.properties:defaults.beforeCreate). Default: No-op * - `{function}` - `afterCreate` - See [DSProvider.defaults.afterCreate](/documentation/api/angular-data/DSProvider.properties:defaults.afterCreate). Default: No-op * - `{function}` - `beforeUpdate` - See [DSProvider.defaults.beforeUpdate](/documentation/api/angular-data/DSProvider.properties:defaults.beforeUpdate). Default: No-op * - `{function}` - `afterUpdate` - See [DSProvider.defaults.afterUpdate](/documentation/api/angular-data/DSProvider.properties:defaults.afterUpdate). Default: No-op * - `{function}` - `beforeDestroy` - See [DSProvider.defaults.beforeDestroy](/documentation/api/angular-data/DSProvider.properties:defaults.beforeDestroy). Default: No-op * - `{function}` - `afterDestroy` - See [DSProvider.defaults.afterDestroy](/documentation/api/angular-data/DSProvider.properties:defaults.afterDestroy). Default: No-op * - `{function}` - `afterInject` - See [DSProvider.defaults.afterInject](/documentation/api/angular-data/DSProvider.properties:defaults.afterInject). Default: No-op * - `{function}` - `beforeInject` - See [DSProvider.defaults.beforeInject](/documentation/api/angular-data/DSProvider.properties:defaults.beforeInject). Default: No-op * - `{function}` - `serialize` - See [DSProvider.defaults.serialize](/documentation/api/angular-data/DSProvider.properties:defaults.serialize). Default: No-op * - `{function}` - `deserialize` - See [DSProvider.defaults.deserialize](/documentation/api/angular-data/DSProvider.properties:defaults.deserialize). Default: No-op */ var defaults = this.defaults = new Defaults(); this.$get = [ '$rootScope', '$log', '$q', 'DSHttpAdapter', 'DSLocalStorageAdapter', 'DSUtils', 'DSErrors', function ($rootScope, $log, $q, DSHttpAdapter, DSLocalStorageAdapter, DSUtils, DSErrors) { var syncMethods = require('./sync_methods'), asyncMethods = require('./async_methods'), cache; try { cache = angular.injector(['angular-data.DSCacheFactory']).get('DSCacheFactory'); } catch (err) { $log.warn(err); $log.warn('DSCacheFactory is unavailable. Resorting to the lesser capabilities of $cacheFactory.'); cache = angular.injector(['ng']).get('$cacheFactory'); } /** * @doc interface * @id DS * @name DS * @description * Public data store interface. Consists of several properties and a number of methods. Injectable as `DS`. * * See the [guide](/documentation/guide/overview/index). */ var DS = { notify: function (definition, event) { var args = Array.prototype.slice.call(arguments, 2); args.unshift(definition.name); args.unshift('DS.' + event); if (definition.events === 'broadcast') { $rootScope.$broadcast.apply($rootScope, args); } else if (definition.events === 'emit') { $rootScope.$emit.apply($rootScope, args); } }, $rootScope: $rootScope, $log: $log, $q: $q, cacheFactory: cache, /** * @doc property * @id DS.properties:defaults * @name defaults * @description * Reference to [DSProvider.defaults](/documentation/api/api/DSProvider.properties:defaults). */ defaults: defaults, /*! * @doc property * @id DS.properties:store * @name store * @description * Meta data for each registered resource. */ store: {}, /*! * @doc property * @id DS.properties:definitions * @name definitions * @description * Registered resource definitions available to the data store. */ definitions: {}, /** * @doc property * @id DS.properties:adapters * @name adapters * @description * Registered adapters available to the data store. Object consists of key-values pairs where the key is * the name of the adapter and the value is the adapter itself. */ adapters: { DSHttpAdapter: DSHttpAdapter, DSLocalStorageAdapter: DSLocalStorageAdapter }, /** * @doc property * @id DS.properties:errors * @name errors * @description * References to the various [error types](/documentation/api/api/errors) used by angular-data. */ errors: DSErrors, /*! * @doc property * @id DS.properties:utils * @name utils * @description * Utility functions used internally by angular-data. */ utils: DSUtils }; DSUtils.deepFreeze(syncMethods); DSUtils.deepFreeze(asyncMethods); DSUtils.deepMixIn(DS, syncMethods); DSUtils.deepMixIn(DS, asyncMethods); DSUtils.deepFreeze(DS.errors); DSUtils.deepFreeze(DS.utils); if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { $rootScope.$watch(function () { // Throttle angular-data's digest loop to tenths of a second return new Date().getTime() / 100 | 0; }, function () { DS.digest(); }); } return DS; } ]; } module.exports = DSProvider; },{"../utils":68,"./async_methods":43,"./sync_methods":61}],50:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.bindAll(scope, expr, ' + resourceName + ', params[, cb]): '; } /** * @doc method * @id DS.sync methods:bindAll * @name bindAll * @description * Bind a collection of items in the data store to `scope` under the property specified by `expr` filtered by `params`. * * ## Signature: * ```js * DS.bindAll(scope, expr, resourceName, params[, cb]) * ``` * * ## Example: * * ```js * // bind the documents with ownerId of 5 to the 'docs' property of the $scope * var deregisterFunc = DS.bindAll($scope, 'docs', 'document', { * where: { * ownerId: 5 * } * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {object} scope The scope to bind to. * @param {string} expr An expression used to bind to the scope. Can be used to set nested keys, i.e. `"user.comments"`. * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is used in filtering the collection. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {function=} cb Optional callback executed on change. Signature: `cb(err, items)`. * * @returns {function} Scope $watch deregistration function. */ function bindAll(scope, expr, resourceName, params, cb) { var DS = this; var IA = DS.errors.IA; if (!DS.utils.isObject(scope)) { throw new IA(errorPrefix(resourceName) + 'scope: Must be an object!'); } else if (!DS.utils.isString(expr)) { throw new IA(errorPrefix(resourceName) + 'expr: Must be a string!'); } else if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } try { return scope.$watch(function () { return DS.lastModified(resourceName); }, function () { var items = DS.filter(resourceName, params); DS.utils.set(scope, expr, items); if (cb) { cb(null, items); } }); } catch (err) { if (cb) { cb(err); } else { throw err; } } } module.exports = bindAll; },{}],51:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.bindOne(scope, expr, ' + resourceName + ', id[, cb]): '; } /** * @doc method * @id DS.sync methods:bindOne * @name bindOne * @description * Bind an item in the data store to `scope` under the property specified by `expr`. * * ## Signature: * ```js * DS.bindOne(scope, expr, resourceName, id[, cb]) * ``` * * ## Example: * * ```js * // bind the document with id 5 to the 'doc' property of the $scope * var deregisterFunc = DS.bindOne($scope, 'doc', 'document', 5); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {object} scope The scope to bind to. * @param {string} expr An expression used to bind to the scope. Can be used to set nested keys, i.e. `"user.profile"`. * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to bind. * @param {function=} cb Optional callback executed on change. Signature: `cb(err, item)`. * @returns {function} Scope $watch deregistration function. */ function bindOne(scope, expr, resourceName, id, cb) { var DS = this; var IA = DS.errors.IA; if (!DS.utils.isObject(scope)) { throw new IA(errorPrefix(resourceName) + 'scope: Must be an object!'); } else if (!DS.utils.isString(expr)) { throw new IA(errorPrefix(resourceName) + 'expr: Must be a string!'); } else if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } try { return scope.$watch(function () { return DS.lastModified(resourceName, id); }, function () { var item = DS.get(resourceName, id); DS.utils.set(scope, expr, item); if (cb) { cb(null, item); } }); } catch (err) { if (cb) { cb(err); } else { throw err; } } } module.exports = bindOne; },{}],52:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.changes(' + resourceName + ', id): '; } /** * @doc method * @id DS.sync methods:changes * @name changes * @description * Synchronously return the changes object of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the diff between the item in its current state and the state of the item * the last time it was saved via an adapter. * * ## Signature: * ```js * DS.changes(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * // You might have to do $scope.$apply() first * * DS.changes('document', 5); // {...} Object describing changes * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item of the changes to retrieve. * @returns {object} The changes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function changes(resourceName, id) { var DS = this; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'id: Must be a string or a number!'); } var item = DS.get(resourceName, id); if (item) { DS.store[resourceName].observers[id].deliver(); var diff = DS.utils.diffObjectFromOldObject(item, DS.store[resourceName].previousAttributes[id]); DS.utils.forOwn(diff, function (changeset, name) { var toKeep = []; DS.utils.forOwn(changeset, function (value, field) { if (!angular.isFunction(value)) { toKeep.push(field); } }); diff[name] = DS.utils.pick(diff[name], toKeep); }); return diff; } } module.exports = changes; },{}],53:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.createInstance(' + resourceName + '[, attrs][, options]): '; } /** * @doc method * @id DS.sync methods:createInstance * @name createInstance * @description * Return a new instance of the specified resource. * * ## Signature: * ```js * DS.createInstance(resourceName[, attrs][, options]) * ``` * * ## Example: * * ```js * var User = DS.defineResource({ * name: 'user', * methods: { * say: function () { * return 'hi'; * } * } * }); * * var user = User.createInstance(); * var user2 = DS.createInstance('user'); * * user instanceof User[User.class]; // true * user2 instanceof User[User.class]; // true * * user.say(); // hi * user2.say(); // hi * * var user3 = User.createInstance({ name: 'John' }, { useClass: false }); * var user4 = DS.createInstance('user', { name: 'John' }, { useClass: false }); * * user3; // { name: 'John' } * user3 instanceof User[User.class]; // false * * user4; // { name: 'John' } * user4 instanceof User[User.class]; // false * * user3.say(); // TypeError: undefined is not a function * user4.say(); // TypeError: undefined is not a function * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} attrs Optional attributes to mix in to the new instance. * @param {object=} options Optional configuration. Properties: * * - `{boolean=}` - `useClass` - Whether to use the resource's wrapper class. Default: `true`. * * @returns {object} The new instance. */ function createInstance(resourceName, attrs, options) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; attrs = attrs || {}; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (attrs && !DS.utils.isObject(attrs)) { throw new IA(errorPrefix(resourceName) + 'attrs: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } if (!('useClass' in options)) { options.useClass = true; } var item; if (options.useClass) { var Func = definition[definition.class]; item = new Func(); } else { item = {}; } return DS.utils.deepMixIn(item, attrs); } module.exports = createInstance; },{}],54:[function(require,module,exports){ /*jshint evil:true*/ var errorPrefix = 'DS.defineResource(definition): '; function Resource(utils, options) { utils.deepMixIn(this, options); if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } } var methodsToProxy = [ 'bindAll', 'bindOne', 'changes', 'create', 'createInstance', 'destroy', 'destroyAll', 'eject', 'ejectAll', 'filter', 'find', 'findAll', 'get', 'hasChanges', 'inject', 'lastModified', 'lastSaved', 'loadRelations', 'previous', 'refresh', 'save', 'update', 'updateAll' ]; /** * @doc method * @id DS.sync methods:defineResource * @name defineResource * @description * Define a resource and register it with the data store. * * ## Signature: * ```js * DS.defineResource(definition) * ``` * * ## Example: * * ```js * DS.defineResource({ * name: 'document', * idAttribute: '_id', * endpoint: '/documents * baseUrl: 'http://myapp.com/api', * beforeDestroy: function (resourceName attrs, cb) { * console.log('looks good to me'); * cb(null, attrs); * } * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * * @param {string|object} definition Name of resource or resource definition object: Properties: * * - `{string}` - `name` - The name by which this resource will be identified. * - `{string="id"}` - `idAttribute` - The attribute that specifies the primary key for this resource. * - `{string=}` - `endpoint` - The attribute that specifies the primary key for this resource. Default is the value of `name`. * - `{string=}` - `baseUrl` - The url relative to which all AJAX requests will be made. * - `{boolean=}` - `useClass` - Whether to use a wrapper class created from the ProperCase name of the resource. The wrapper will always be used for resources that have `methods` defined. * - `{function=}` - `defaultFilter` - Override the filtering used internally by `DS.filter` with you own function here. * - `{*=}` - `meta` - A property reserved for developer use. This will never be used by the API. * - `{object=}` - `methods` - If provided, items of this resource will be wrapped in a constructor function that is * empty save for the attributes in this option which will be mixed in to the constructor function prototype. Enabling * this feature for this resource will incur a slight performance penalty, but allows you to give custom behavior to what * are now "instances" of this resource. * - `{function=}` - `beforeValidate` - Lifecycle hook. Overrides global. Signature: `beforeValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `validate` - Lifecycle hook. Overrides global. Signature: `validate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterValidate` - Lifecycle hook. Overrides global. Signature: `afterValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeCreate` - Lifecycle hook. Overrides global. Signature: `beforeCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterCreate` - Lifecycle hook. Overrides global. Signature: `afterCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeUpdate` - Lifecycle hook. Overrides global. Signature: `beforeUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterUpdate` - Lifecycle hook. Overrides global. Signature: `afterUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeDestroy` - Lifecycle hook. Overrides global. Signature: `beforeDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterDestroy` - Lifecycle hook. Overrides global. Signature: `afterDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeInject` - Lifecycle hook. Overrides global. Signature: `beforeInject(resourceName, attrs)`. * - `{function=}` - `afterInject` - Lifecycle hook. Overrides global. Signature: `afterInject(resourceName, attrs)`. * - `{function=}` - `serialize` - Serialization hook. Overrides global. Signature: `serialize(resourceName, attrs)`. * - `{function=}` - `deserialize` - Deserialization hook. Overrides global. Signature: `deserialize(resourceName, attrs)`. * * See [DSProvider.defaults](/documentation/api/angular-data/DSProvider.properties:defaults). */ function defineResource(definition) { var DS = this; var definitions = DS.definitions; var IA = DS.errors.IA; if (DS.utils.isString(definition)) { definition = definition.replace(/\s/gi, ''); definition = { name: definition }; } if (!DS.utils.isObject(definition)) { throw new IA(errorPrefix + 'definition: Must be an object!'); } else if (!DS.utils.isString(definition.name)) { throw new IA(errorPrefix + 'definition.name: Must be a string!'); } else if (definition.idAttribute && !DS.utils.isString(definition.idAttribute)) { throw new IA(errorPrefix + 'definition.idAttribute: Must be a string!'); } else if (definition.endpoint && !DS.utils.isString(definition.endpoint)) { throw new IA(errorPrefix + 'definition.endpoint: Must be a string!'); } else if (DS.store[definition.name]) { throw new DS.errors.R(errorPrefix + definition.name + ' is already registered!'); } try { // Inherit from global defaults Resource.prototype = DS.defaults; definitions[definition.name] = new Resource(DS.utils, definition); var def = definitions[definition.name]; // Setup nested parent configuration if (def.relations && def.relations.belongsTo) { DS.utils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { if (!DS.utils.isArray(relatedModel)) { relatedModel = [relatedModel]; } DS.utils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; } }); }); } def.getEndpoint = function (attrs, options) { var parent = this.parent; var parentKey = this.parentKey; var item; var endpoint; options = options || {}; options.params = options.params || {}; if (parent && parentKey && definitions[parent] && options.params[parentKey] !== false) { if (DS.utils.isNumber(attrs) || DS.utils.isString(attrs)) { item = DS.get(this.name, attrs); } if (DS.utils.isObject(attrs) && parentKey in attrs) { delete options.params[parentKey]; endpoint = DS.utils.makePath(definitions[parent].getEndpoint(attrs, options), attrs[parentKey], this.endpoint); } else if (item && parentKey in item) { delete options.params[parentKey]; endpoint = DS.utils.makePath(definitions[parent].getEndpoint(attrs, options), item[parentKey], this.endpoint); } else if (options && options.params[parentKey]) { endpoint = DS.utils.makePath(definitions[parent].getEndpoint(attrs, options), options.params[parentKey], this.endpoint); delete options.params[parentKey]; } } if (options.params[parentKey] === false) { delete options.params[parentKey]; } return endpoint || this.endpoint; }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Setup the cache var cache = DS.cacheFactory('DS.' + def.name, { maxAge: def.maxAge || null, recycleFreq: def.recycleFreq || 1000, cacheFlushInterval: def.cacheFlushInterval || null, deleteOnExpire: def.deleteOnExpire || 'none', onExpire: function (id) { var item = DS.eject(def.name, id); if (DS.utils.isFunction(def.onExpire)) { def.onExpire(id, item); } }, capacity: Number.MAX_VALUE, storageMode: 'memory', storageImpl: null, disabled: false, storagePrefix: 'DS.' + def.name }); // Create the wrapper class for the new resource def.class = DS.utils.pascalCase(definition.name); eval('function ' + def.class + '() {}'); def[def.class] = eval(def.class); // Apply developer-defined methods if (def.methods) { DS.utils.deepMixIn(def[def.class].prototype, def.methods); } // Prepare for computed properties if (def.computed) { DS.utils.forOwn(def.computed, function (fn, field) { if (angular.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { DS.$log.warn(errorPrefix + '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) { DS.$log.warn(errorPrefix + 'Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); angular.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DS.utils.filter(deps, function (dep) { return !!dep; }); }); } // Initialize store data for the new resource DS.store[def.name] = { collection: [], completedQueries: {}, pendingQueries: {}, index: cache, modified: {}, saved: {}, previousAttributes: {}, observers: {}, collectionModified: 0 }; // Proxy DS methods with shorthand ones angular.forEach(methodsToProxy, function (name) { if (name === 'bindOne' || name === 'bindAll') { def[name] = function () { var args = Array.prototype.slice.call(arguments); args.splice(2, 0, def.name); return DS[name].apply(DS, args); }; } else { def[name] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(def.name); return DS[name].apply(DS, args); }; } }); return def; } catch (err) { DS.$log.error(err); delete definitions[definition.name]; delete DS.store[definition.name]; throw err; } } module.exports = defineResource; },{}],55:[function(require,module,exports){ var observe = require('../../../lib/observe-js/observe-js'); /** * @doc method * @id DS.sync methods:digest * @name digest * @description * Trigger a digest loop that checks for changes and updates the `lastModified` timestamp if an object has changed. * Anything $watching `DS.lastModified(...)` will detect the updated timestamp and execute the callback function. If * your browser supports `Object.observe` then this function has no effect. * * ## Signature: * ```js * DS.digest() * ``` * * ## Example: * * ```js * Works like $scope.$apply() * ``` * */ function digest() { if (!this.$rootScope.$$phase) { this.$rootScope.$apply(function () { observe.Platform.performMicrotaskCheckpoint(); }); } else { observe.Platform.performMicrotaskCheckpoint(); } } module.exports = digest; },{"../../../lib/observe-js/observe-js":1}],56:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.eject(' + resourceName + ', ' + id + '): '; } function _eject(definition, resource, id) { var item; var found = false; for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { item = resource.collection[i]; found = true; break; } } if (found) { resource.collection.splice(i, 1); resource.observers[id].close(); delete resource.observers[id]; resource.index.remove(id); delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = this.utils.updateTimestamp(resource.collectionModified); this.notify(definition, 'eject', item); return item; } } /** * @doc method * @id DS.sync methods:eject * @name eject * @description * Eject the item of the specified type that has the given primary key from the data store. Ejection only removes items * from the data store and does not attempt to destroy items via an adapter. * * ## Signature: * ```js * DS.eject(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * * DS.eject('document', 45); * * DS.get('document', 45); // undefined * ``` * * ```js * $rootScope.$on('DS.eject', function ($event, resourceName, ejected) {...}); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to eject. * @returns {object} A reference to the item that was ejected from the data store. */ function eject(resourceName, id) { var DS = this; var definition = DS.definitions[resourceName]; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } var resource = DS.store[resourceName]; var ejected; if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { ejected = _eject.call(DS, definition, resource, id); }); } else { ejected = _eject.call(DS, definition, resource, id); } return ejected; } module.exports = eject; },{}],57:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.ejectAll(' + resourceName + '[, params]): '; } function _ejectAll(definition, resource, params) { var DS = this; var queryHash = DS.utils.toJson(params); var items = DS.filter(definition.name, params); var ids = DS.utils.toLookup(items, definition.idAttribute); angular.forEach(ids, function (item, id) { DS.eject(definition.name, id); }); delete resource.completedQueries[queryHash]; resource.collectionModified = DS.utils.updateTimestamp(resource.collectionModified); DS.notify(definition, 'eject', items); return items; } /** * @doc method * @id DS.sync methods:ejectAll * @name ejectAll * @description * Eject all matching items of the specified type from the data store. Ejection only removes items from the data store * and does not attempt to destroy items via an adapter. * * ## Signature: * ```js * DS.ejectAll(resourceName[, params]) * ``` * * ## Example: * * ```js * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * * DS.eject('document', 45); * * DS.get('document', 45); // undefined * ``` * * Eject all items of the specified type that match the criteria from the data store. * * ```js * DS.filter('document'); // [ { title: 'How to Cook', id: 45, author: 'John Anderson' }, * // { title: 'How to Eat', id: 46, author: 'Sally Jane' } ] * * DS.ejectAll('document', { where: { author: 'Sally Jane' } }); * * DS.filter('document'); // [ { title: 'How to Cook', id: 45, author: 'John Anderson' } ] * ``` * * Eject all items of the specified type from the data store. * * ```js * DS.filter('document'); // [ { title: 'How to Cook', id: 45, author: 'John Anderson' }, * // { title: 'How to Eat', id: 46, author: 'Sally Jane' } ] * * DS.ejectAll('document'); * * DS.filter('document'); // [ ] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is used to filter items. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @returns {array} The items that were ejected from the data store. */ function ejectAll(resourceName, params) { var DS = this; var definition = DS.definitions[resourceName]; params = params || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(params)) { throw new DS.errors.IA(errorPrefix(resourceName) + 'params: Must be an object!'); } var resource = DS.store[resourceName]; var ejected; if (DS.utils.isEmpty(params)) { resource.completedQueries = {}; } if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { ejected = _ejectAll.apply(DS, [definition, resource, params]); }); } else { ejected = _ejectAll.apply(DS, [definition, resource, params]); } return ejected; } module.exports = ejectAll; },{}],58:[function(require,module,exports){ function errorPrefix(resourceName) { return 'DS.filter(' + resourceName + '[, params][, options]): '; } /** * @doc method * @id DS.sync methods:filter * @name filter * @description * Synchronously filter items in the data store of the type specified by `resourceName`. * * ## Signature: * ```js * DS.filter(resourceName[, params][, options]) * ``` * * ## Example: * * For many examples see the [tests for DS.filter](https://github.com/jmdobry/angular-data/blob/master/test/integration/datastore/sync methods/filter.test.js). * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object=} params Parameter object that is used to filter items. Properties: * * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{number=}` - `skip` - Skip clause. * - `{number=}` - `offset` - Same as skip. * - `{string|array=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Properties: * * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * - `{boolean=}` - `allowSimpleWhere` - Treat top-level fields on the `params` argument as simple "where" equality clauses. Default: `true`. * * @returns {array} The filtered collection of items of the type specified by `resourceName`. */ function filter(resourceName, params, options) { var DS = this; var IA = DS.errors.IA; var definition = DS.definitions[resourceName]; options = options || {}; if (!definition) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (params && !DS.utils.isObject(params)) { throw new IA(errorPrefix(resourceName) + 'params: Must be an object!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } var resource = DS.store[resourceName]; // Protect against null params = params || {}; if ('allowSimpleWhere' in options) { options.allowSimpleWhere = !!options.allowSimpleWhere; } else { options.allowSimpleWhere = true; } var queryHash = DS.utils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started DS.findAll(resourceName, params, options); } } return definition.defaultFilter.call(DS, resource.collection, resourceName, params, options); } module.exports = filter; },{}],59:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.get(' + resourceName + ', ' + id + '): '; } /** * @doc method * @id DS.sync methods:get * @name get * @description * Synchronously return the resource with the given id. The data store will forward the request to an adapter if * `loadFromServer` is `true` in the options hash. * * ## Signature: * ```js * DS.get(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5'); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Also passed along to `DS.find` if `loadFromServer` is `true`. Properties: * * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * * @returns {object} The item of the type specified by `resourceName` with the primary key specified by `id`. */ function get(resourceName, id, options) { var DS = this; var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName, id) + 'options: Must be an object!'); } // cache miss, request resource from server var item = DS.store[resourceName].index.get(id); if (!item && options.loadFromServer) { DS.find(resourceName, id, options).then(null, function (err) { return DS.$q.reject(err); }); } // return resource from cache return item; } module.exports = get; },{}],60:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.hasChanges(' + resourceName + ', ' + id + '): '; } function diffIsEmpty(utils, diff) { return !(utils.isEmpty(diff.added) && utils.isEmpty(diff.removed) && utils.isEmpty(diff.changed)); } /** * @doc method * @id DS.sync methods:hasChanges * @name hasChanges * @description * Synchronously return whether object of the item of the type specified by `resourceName` that has the primary key * specified by `id` has changes. * * ## Signature: * ```js * DS.hasChanges(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * // You may have to do $scope.$apply() first * * DS.hasChanges('document', 5); // true * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item. * @returns {boolean} Whether the item of the type specified by `resourceName` with the primary key specified by `id` has changes. */ function hasChanges(resourceName, id) { var DS = this; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } // return resource from cache if (DS.get(resourceName, id)) { return diffIsEmpty(DS.utils, DS.changes(resourceName, id)); } else { return false; } } module.exports = hasChanges; },{}],61:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.sync methods:bindOne * @name bindOne * @methodOf DS * @description * See [DS.bindOne](/documentation/api/api/DS.sync methods:bindOne). */ bindOne: require('./bindOne'), /** * @doc method * @id DS.sync methods:bindAll * @name bindAll * @methodOf DS * @description * See [DS.bindAll](/documentation/api/api/DS.sync methods:bindAll). */ bindAll: require('./bindAll'), /** * @doc method * @id DS.sync methods:createInstance * @name createInstance * @methodOf DS * @description * See [DS.createInstance](/documentation/api/api/DS.sync methods:createInstance). */ createInstance: require('./createInstance'), /** * @doc method * @id DS.sync methods:defineResource * @name defineResource * @methodOf DS * @description * See [DS.defineResource](/documentation/api/api/DS.sync methods:defineResource). */ defineResource: require('./defineResource'), /** * @doc method * @id DS.sync methods:eject * @name eject * @methodOf DS * @description * See [DS.eject](/documentation/api/api/DS.sync methods:eject). */ eject: require('./eject'), /** * @doc method * @id DS.sync methods:ejectAll * @name ejectAll * @methodOf DS * @description * See [DS.ejectAll](/documentation/api/api/DS.sync methods:ejectAll). */ ejectAll: require('./ejectAll'), /** * @doc method * @id DS.sync methods:filter * @name filter * @methodOf DS * @description * See [DS.filter](/documentation/api/api/DS.sync methods:filter). */ filter: require('./filter'), /** * @doc method * @id DS.sync methods:get * @name get * @methodOf DS * @description * See [DS.get](/documentation/api/api/DS.sync methods:get). */ get: require('./get'), /** * @doc method * @id DS.sync methods:inject * @name inject * @methodOf DS * @description * See [DS.inject](/documentation/api/api/DS.sync methods:inject). */ inject: require('./inject'), /** * @doc method * @id DS.sync methods:lastModified * @name lastModified * @methodOf DS * @description * See [DS.lastModified](/documentation/api/api/DS.sync methods:lastModified). */ lastModified: require('./lastModified'), /** * @doc method * @id DS.sync methods:lastSaved * @name lastSaved * @methodOf DS * @description * See [DS.lastSaved](/documentation/api/api/DS.sync methods:lastSaved). */ lastSaved: require('./lastSaved'), /** * @doc method * @id DS.sync methods:digest * @name digest * @methodOf DS * @description * See [DS.digest](/documentation/api/api/DS.sync methods:digest). */ digest: require('./digest'), /** * @doc method * @id DS.sync methods:changes * @name changes * @methodOf DS * @description * See [DS.changes](/documentation/api/api/DS.sync methods:changes). */ changes: require('./changes'), /** * @doc method * @id DS.sync methods:previous * @name previous * @methodOf DS * @description * See [DS.previous](/documentation/api/api/DS.sync methods:previous). */ previous: require('./previous'), /** * @doc method * @id DS.sync methods:hasChanges * @name hasChanges * @methodOf DS * @description * See [DS.hasChanges](/documentation/api/api/DS.sync methods:hasChanges). */ hasChanges: require('./hasChanges') }; },{"./bindAll":50,"./bindOne":51,"./changes":52,"./createInstance":53,"./defineResource":54,"./digest":55,"./eject":56,"./ejectAll":57,"./filter":58,"./get":59,"./hasChanges":60,"./inject":62,"./lastModified":63,"./lastSaved":64,"./previous":65}],62:[function(require,module,exports){ var observe = require('../../../lib/observe-js/observe-js'); function errorPrefix(resourceName) { return 'DS.inject(' + resourceName + ', attrs[, options]): '; } function _inject(definition, resource, attrs) { var DS = this; var $log = DS.$log; function _react(added, removed, changed, oldValueFn) { var target = this; var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; resource.modified[innerId] = DS.utils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DS.utils.updateTimestamp(resource.collectionModified); if (definition.computed) { var item = DS.get(definition.name, innerId); DS.utils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed angular.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) { var args = []; angular.forEach(fn.deps, function (dep) { args.push(item[dep]); }); // recompute property item[field] = fn[fn.length - 1].apply(item, args); } }); } if (definition.idAttribute in changed) { $log.error('Doh! You just changed the primary key of an object! ' + 'I don\'t know how to handle this yet, so your data for the "' + definition.name + '" resource is now in an undefined (probably broken) state.'); } } var injected; if (DS.utils.isArray(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(DS, definition, resource, attrs[i])); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { var args = []; angular.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 DS.errors.R(errorPrefix(definition.name) + 'attrs: Must contain the property specified by `idAttribute`!'); $log.error(error); throw error; } else { try { definition.beforeInject(definition.name, attrs); var id = attrs[idA]; var item = DS.get(definition.name, id); if (!item) { if (definition.methods || definition.useClass) { if (attrs instanceof definition[definition.class]) { item = attrs; } else { item = new definition[definition.class](); } } else { item = {}; } resource.previousAttributes[id] = {}; DS.utils.deepMixIn(item, attrs); DS.utils.deepMixIn(resource.previousAttributes[id], attrs); resource.collection.push(item); resource.observers[id] = new observe.ObjectObserver(item); resource.observers[id].open(_react, item); resource.index.put(id, item); _react.call(item, {}, {}, {}); } else { DS.utils.deepMixIn(item, attrs); if (typeof resource.index.touch === 'function') { resource.index.touch(id); } else { resource.index.put(id, resource.index.get(id)); } resource.observers[id].deliver(); } resource.saved[id] = DS.utils.updateTimestamp(resource.saved[id]); definition.afterInject(definition.name, item); injected = item; } catch (err) { $log.error(err); $log.error('inject failed!', definition.name, attrs); } } } return injected; } function _injectRelations(definition, injected, options) { var DS = this; DS.utils.forOwn(definition.relations, function (relatedModels, type) { DS.utils.forOwn(relatedModels, function (defs, relationName) { if (!DS.utils.isArray(defs)) { defs = [defs]; } function _process(def, injected) { if (DS.definitions[relationName] && injected[def.localField]) { try { injected[def.localField] = DS.inject(relationName, injected[def.localField], options); } catch (err) { DS.$log.error(errorPrefix(definition.name) + 'Failed to inject ' + type + ' relation: "' + relationName + '"!', err); } } else if (options.findBelongsTo) { if (type === 'belongsTo') { if (DS.utils.isArray(injected)) { DS.utils.forEach(injected, function (injectedItem) { var parent = injectedItem[def.localKey] ? DS.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else { var parent = injected[def.localKey] ? DS.get(relationName, injected[def.localKey]) : null; if (parent) { injected[def.localField] = parent; } } } } } defs.forEach(function (def) { if (DS.utils.isArray(injected)) { DS.utils.forEach(injected, function (injectedI) { _process(def, injectedI); }); } else { _process(def, injected); } }); }); }); } /** * @doc method * @id DS.sync methods:inject * @name inject * @description * Inject the given item into the data store as the specified type. If `attrs` is an array, inject each item into the * data store. Injecting an item into the data store does not save it to the server. Emits a `"DS.inject"` event. * * ## Signature: * ```js * DS.inject(resourceName, attrs[, options]) * ``` * * ## Examples: * * ```js * DS.get('document', 45); // undefined * * DS.inject('document', { title: 'How to Cook', id: 45 }); * * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * ``` * * Inject a collection into the data store: * * ```js * DS.filter('document'); // [ ] * * DS.inject('document', [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ]); * * DS.filter('document'); // [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ] * ``` * * ```js * $rootScope.$on('DS.inject', function ($event, resourceName, injected) {...}); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object|array} attrs The item or collection of items to inject into the data store. * @param {object=} options The item or collection of items to inject into the data store. Properties: * * - `{boolean=}` - `findBelongsTo` - Find and attach any existing "belongsTo" relationships to the newly injected item. Default: `true`. * * @returns {object|array} A reference to the item that was injected into the data store or an array of references to * the items that were injected into the data store. */ function inject(resourceName, attrs, options) { var DS = this; var IA = DS.errors.IA; options = options || {}; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName) + resourceName); } else if (!DS.utils.isObject(attrs) && !DS.utils.isArray(attrs)) { throw new IA(errorPrefix(resourceName) + 'attrs: Must be an object or an array!'); } else if (!DS.utils.isObject(options)) { throw new IA(errorPrefix(resourceName) + 'options: Must be an object!'); } var definition = DS.definitions[resourceName]; var resource = DS.store[resourceName]; var injected; if (!('findBelongsTo' in options)) { options.findBelongsTo = true; } if (!DS.$rootScope.$$phase) { DS.$rootScope.$apply(function () { injected = _inject.call(DS, definition, resource, attrs); }); } else { injected = _inject.call(DS, definition, resource, attrs); } if (definition.relations) { _injectRelations.call(DS, definition, injected, options); } DS.notify(definition, 'inject', injected); return injected; } module.exports = inject; },{"../../../lib/observe-js/observe-js":1}],63:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.lastModified(' + resourceName + '[, ' + id + ']): '; } /** * @doc method * @id DS.sync methods:lastModified * @name lastModified * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was modified. * * ## Signature: * ```js * DS.lastModified(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to remove. * @returns {number} The timestamp of the last time either the collection for `resourceName` or the item of type * `resourceName` with the given primary key was modified. */ function lastModified(resourceName, id) { var DS = this; var resource = DS.store[resourceName]; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (id && !DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; } module.exports = lastModified; },{}],64:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.lastSaved(' + resourceName + '[, ' + id + ']): '; } /** * @doc method * @id DS.sync methods:lastSaved * @name lastSaved * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was saved via an async adapter. * * ## Signature: * ```js * DS.lastSaved(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * DS.lastSaved('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * DS.lastSaved('document', 5); // 1234235825494 * * document.author = 'Sally'; * * // You may have to call $scope.$apply() first * * DS.lastModified('document', 5); // 1234304985344 - something different * DS.lastSaved('document', 5); // 1234235825494 - still the same * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item for which to retrieve the lastSaved timestamp. * @returns {number} The timestamp of the last time the item of type `resourceName` with the given primary key was saved. */ function lastSaved(resourceName, id) { var DS = this; var resource = DS.store[resourceName]; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; } module.exports = lastSaved; },{}],65:[function(require,module,exports){ function errorPrefix(resourceName, id) { return 'DS.previous(' + resourceName + '[, ' + id + ']): '; } /** * @doc method * @id DS.sync methods:previous * @name previous * @description * Synchronously return the previous attributes of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the state of the item the last time it was saved via an async adapter. * * ## Signature: * ```js * DS.previous(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * d; // { author: 'Sally', id: 5 } * * // You may have to do $scope.$apply() first * * DS.previous('document', 5); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{NonexistentResourceError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item whose previous attributes are to be retrieved. * @returns {object} The previous attributes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function previous(resourceName, id) { var DS = this; if (!DS.definitions[resourceName]) { throw new DS.errors.NER(errorPrefix(resourceName, id) + resourceName); } else if (!DS.utils.isString(id) && !DS.utils.isNumber(id)) { throw new DS.errors.IA(errorPrefix(resourceName, id) + 'id: Must be a string or a number!'); } // return resource from cache return angular.copy(DS.store[resourceName].previousAttributes[id]); } module.exports = previous; },{}],66:[function(require,module,exports){ /** * @doc function * @id errors.types:IllegalArgumentError * @name IllegalArgumentError * @description Error that is thrown/returned when a caller does not honor the pre-conditions of a method/function. * @param {string=} message Error message. Default: `"Illegal Argument!"`. * @returns {IllegalArgumentError} A new instance of `IllegalArgumentError`. */ function IllegalArgumentError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:IllegalArgumentError.type * @name type * @propertyOf errors.types:IllegalArgumentError * @description Name of error type. Default: `"IllegalArgumentError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:IllegalArgumentError.message * @name message * @propertyOf errors.types:IllegalArgumentError * @description Error message. Default: `"Illegal Argument!"`. */ this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = Object.create(Error.prototype); IllegalArgumentError.prototype.constructor = IllegalArgumentError; /** * @doc function * @id errors.types:RuntimeError * @name RuntimeError * @description Error that is thrown/returned for invalid state during runtime. * @param {string=} message Error message. Default: `"Runtime Error!"`. * @returns {RuntimeError} A new instance of `RuntimeError`. */ function RuntimeError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:RuntimeError.type * @name type * @propertyOf errors.types:RuntimeError * @description Name of error type. Default: `"RuntimeError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:RuntimeError.message * @name message * @propertyOf errors.types:RuntimeError * @description Error message. Default: `"Runtime Error!"`. */ this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = Object.create(Error.prototype); RuntimeError.prototype.constructor = RuntimeError; /** * @doc function * @id errors.types:NonexistentResourceError * @name NonexistentResourceError * @description Error that is thrown/returned when trying to access a resource that does not exist. * @param {string=} resourceName Name of non-existent resource. * @returns {NonexistentResourceError} A new instance of `NonexistentResourceError`. */ function NonexistentResourceError(resourceName) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:NonexistentResourceError.type * @name type * @propertyOf errors.types:NonexistentResourceError * @description Name of error type. Default: `"NonexistentResourceError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:NonexistentResourceError.message * @name message * @propertyOf errors.types:NonexistentResourceError * @description Error message. Default: `"Runtime Error!"`. */ this.message = (resourceName || '') + ' is not a registered resource!'; } NonexistentResourceError.prototype = Object.create(Error.prototype); NonexistentResourceError.prototype.constructor = NonexistentResourceError; /** * @doc interface * @id errors * @name angular-data error types * @description * Various error types that may be thrown by angular-data. * * - [IllegalArgumentError](/documentation/api/api/errors.types:IllegalArgumentError) * - [RuntimeError](/documentation/api/api/errors.types:RuntimeError) * - [NonexistentResourceError](/documentation/api/api/errors.types:NonexistentResourceError) * * References to the constructor functions of these errors can be found in `DS.errors`. */ module.exports = [function () { return { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; }]; },{}],67:[function(require,module,exports){ (function (window, angular, undefined) { 'use strict'; /** * @doc overview * @id angular-data * @name angular-data * @description * __Version:__ 1.0.0-beta.1 * * ## Install * * #### Bower * ```text * bower install angular-data * ``` * * Load `dist/angular-data.js` or `dist/angular-data.min.js` onto your web page after Angular.js. * * #### Npm * ```text * npm install angular-data * ``` * * Load `dist/angular-data.js` or `dist/angular-data.min.js` onto your web page after Angular.js. * * #### Manual download * Download angular-data from the [Releases](https://github.com/jmdobry/angular-data/releases) * section of the angular-data GitHub project. * * ## Load into Angular * Your Angular app must depend on the module `"angular-data.DS"` in order to use angular-data. Loading * angular-data into your app allows you to inject the following: * * - `DS` * - `DSHttpAdapter` * - `DSUtils` * - `DSErrors` * * [DS](/documentation/api/api/DS) is the Data Store itself, which you will inject often. * [DSHttpAdapter](/documentation/api/api/DSHttpAdapter) is useful as a wrapper for `$http` and is configurable. * [DSUtils](/documentation/api/api/DSUtils) has some useful utility methods. * [DSErrors](/documentation/api/api/DSErrors) provides references to the various errors thrown by the data store. */ angular.module('angular-data.DS', ['ng']) .factory('DSUtils', require('./utils')) .factory('DSErrors', require('./errors')) .provider('DSHttpAdapter', require('./adapters/http')) .provider('DSLocalStorageAdapter', require('./adapters/localStorage')) .provider('DS', require('./datastore')) .config(['$provide', function ($provide) { $provide.decorator('$q', ['$delegate', function ($delegate) { // do whatever you you want $delegate.promisify = function (fn, target) { var _this = this; return function () { var deferred = _this.defer(), args = Array.prototype.slice.apply(arguments); args.push(function (err, result) { if (err) { deferred.reject(err); } else { deferred.resolve(result); } }); try { fn.apply(target || this, args); } catch (err) { deferred.reject(err); } return deferred.promise; }; }; return $delegate; }]); }]); })(window, window.angular); },{"./adapters/http":36,"./adapters/localStorage":37,"./datastore":49,"./errors":66,"./utils":68}],68:[function(require,module,exports){ module.exports = [function () { return { isBoolean: require('mout/lang/isBoolean'), isString: angular.isString, isArray: angular.isArray, isObject: angular.isObject, isNumber: angular.isNumber, isFunction: angular.isFunction, isEmpty: require('mout/lang/isEmpty'), toJson: angular.toJson, makePath: require('mout/string/makePath'), upperCase: require('mout/string/upperCase'), pascalCase: require('mout/string/pascalCase'), deepMixIn: require('mout/object/deepMixIn'), forOwn: require('mout/object/forOwn'), forEach: angular.forEach, pick: require('mout/object/pick'), set: require('mout/object/set'), contains: require('mout/array/contains'), filter: require('mout/array/filter'), toLookup: require('mout/array/toLookup'), slice: require('mout/array/slice'), sort: require('mout/array/sort'), updateTimestamp: function (timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, deepFreeze: function deepFreeze(o) { if (typeof Object.freeze === 'function') { var prop, propKey; Object.freeze(o); // First freeze the object. for (propKey in o) { prop = o[propKey]; if (!o.hasOwnProperty(propKey) || typeof prop !== 'object' || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // Recursively call deepFreeze. } } }, diffObjectFromOldObject: function (object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop2 in object) { if (prop2 in oldObject) continue; added[prop2] = object[prop2]; } return { added: added, removed: removed, changed: changed }; } }; }]; },{"mout/array/contains":2,"mout/array/filter":3,"mout/array/slice":7,"mout/array/sort":8,"mout/array/toLookup":9,"mout/lang/isBoolean":14,"mout/lang/isEmpty":15,"mout/object/deepMixIn":22,"mout/object/forOwn":24,"mout/object/pick":27,"mout/object/set":28,"mout/string/makePath":31,"mout/string/pascalCase":32,"mout/string/upperCase":35}]},{},[67]);
docs/tutorial/DO_NOT_TOUCH/01/src/index.js
FWeinb/cerebral
import React from 'react' import {render} from 'react-dom' import {Controller} from 'cerebral' import {Container} from 'cerebral/react' import Devtools from 'cerebral/devtools' import App from './components/App' const controller = Controller({ devtools: Devtools() }) render(( <Container controller={controller}> <App /> </Container> ), document.querySelector('#root'))
ajax/libs/jquery/1.9.1/jquery.min.js
rm-hull/cdnjs
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
js/auth/Login.js
BarberHour/barber-hour
import React, { Component } from 'react'; import { View, Text, StyleSheet, Image, TouchableNativeFeedback, TextInput, TouchableOpacity, StatusBar, Linking, Platform } from 'react-native'; import { connect } from 'react-redux'; import {FBLoginManager} from 'react-native-facebook-login'; import t from 'tcomb-form-native'; const Form = t.form.Form; import { loginWithFacebook, login } from '../actions/auth'; import CustomerMain from '../customer/Main'; import BarberMain from '../barber/Main'; import Signup from './Signup'; import FacebookButton from './FacebookButton'; import Logo from '../common/Logo'; import Button from '../common/Button'; import TextSeparator from '../common/TextSeparator'; import LargeButton from '../common/LargeButton'; import ForgotPassword from './ForgotPassword'; import NewPasswordForm from './NewPasswordForm'; import Email from '../forms/Email'; import PushNotifications from '../PushNotifications'; import AccountTypeSelector from './AccountTypeSelector'; import FindCityFromGPS from '../customer/FindCityFromGPS'; class Login extends Component { _openForgotPassowrd() { if (!this.props.form.isLoading) { this.props.navigator.push({ component: ForgotPassword, title: 'Redefinir senha' }); } } _openSignup() { this.props.navigator.replace({ component: Signup, title: 'Barber Hour', passProps: { skipDeepLinking: this.props.skipDeepLinking } }); } _login() { let value = this.refs.form.getValue(); // if are any validation errors, value will be null if (value !== null) { this.props.dispatch(login(value)); } } _onFacebookLogin() { if (!this.props.form.isLoading) { FBLoginManager.loginWithPermissions(['email', 'public_profile'], (error, data) => { if (!error) { this.props.dispatch(loginWithFacebook(data)); } }); } } componentDidMount() { Linking.addEventListener('url', this._handleURL.bind(this)); Linking.getInitialURL().then(url => this._handleURL({url})); } componentWillUnmount() { Linking.removeEventListener('url', this._handleURL.bind(this)); } _handleURL({url}) { if (!url || this.props.skipDeepLinking) { return; } var [action, params] = url.split('/')[2].split('?'); if (action === 'reset-password') { var [param, value] = params.split('='); if (param === 'token' && value) { this.props.navigator.resetTo({ component: NewPasswordForm, passProps: { token: value }, title: 'Nova senha' }); } } } componentDidUpdate() { if (this.props.isLoggedIn) { let component = AccountTypeSelector; if (this.props.type === 'Barber') { component = BarberMain; } else if (this.props.type === 'Customer') { component = this.props.city ? CustomerMain : FindCityFromGPS; } this.props.navigator.replace({component: component, title: 'Barber Hour'}); } } getFormValue() { return { email: this.props.form.email, password: this.props.form.password }; } render() { const Login = t.struct({ email: Email, password: t.String }); const buttonLabel = this.props.form.isLoading ? 'Entrando...' : 'Entrar'; return( <View style={styles.container}> <StatusBar backgroundColor='#C5C5C5' networkActivityIndicatorVisible={this.props.form.isLoading} /> <Logo style={styles.logo} /> <View style={styles.formContainer}> <View> <Form ref='form' type={Login} options={this.props.form} value={this.getFormValue()} /> <Button containerStyle={styles.button} text={buttonLabel} disabled={this.props.form.isLoading} onPress={this._login.bind(this)} /> </View> <View style={styles.forgotPasswordContainer}> <Text>Esqueceu sua senha? </Text> <TouchableOpacity onPress={this._openForgotPassowrd.bind(this)}> <Text style={styles.link}>Redefinir senha.</Text> </TouchableOpacity> </View> <TextSeparator style={styles.separatorContainer} /> <Button outline containerStyle={styles.facebookButton} text='Entrar com o Facebook' disabled={this.props.form.isLoading} onPress={this._onFacebookLogin.bind(this)} /> </View> <View style={styles.signupContainer}> <LargeButton text='Não tem uma conta? ' linkText='Cadastre-se.' disabled={this.props.form.isLoading} onPress={this._openSignup.bind(this)} /> </View> <PushNotifications /> </View> ); } } function select(store) { return { form: store.login, isLoggedIn: store.user.isLoggedIn, type: store.user.type, city: store.user.city }; } export default connect(select)(Login); var styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: 'white', justifyContent: 'space-between', marginTop: Platform.OS === 'ios' ? 60 : 0 }, logo: { width: 140, height: 140 }, formContainer: { paddingLeft: 20, paddingRight: 20, }, button: { marginTop: 10 }, forgotPasswordContainer: { flexDirection: 'row', justifyContent: 'center', marginTop: 10 }, link: { fontWeight: 'bold' }, facebookButton: { marginTop: 10, }, separatorContainer: { marginTop: 5, }, signupContainer: { height: 55 } });
ajax/libs/react-redux/4.0.1/react-redux.js
sympmarc/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("redux")); else if(typeof define === 'function' && define.amd) define(["react", "redux"], factory); else if(typeof exports === 'object') exports["ReactRedux"] = factory(require("react"), require("redux")); else root["ReactRedux"] = factory(root["React"], root["Redux"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_10__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _Provider = __webpack_require__(3); Object.defineProperty(exports, 'Provider', { enumerable: true, get: function get() { return _Provider.default; } }); var _connect = __webpack_require__(4); Object.defineProperty(exports, 'connect', { enumerable: true, get: function get() { return _connect.default; } }); /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); exports.default = _react.PropTypes.shape({ subscribe: _react.PropTypes.func.isRequired, dispatch: _react.PropTypes.func.isRequired, getState: _react.PropTypes.func.isRequired }); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = undefined; var _react = __webpack_require__(1); var _storeShape = __webpack_require__(2); var _storeShape2 = _interopRequireDefault(_storeShape); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var didWarnAboutReceivingStore = false; function warnAboutReceivingStore() { if (didWarnAboutReceivingStore) { return; } didWarnAboutReceivingStore = true; console.error( // eslint-disable-line no-console '<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/rackt/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.'); } var Provider = (function (_Component) { _inherits(Provider, _Component); Provider.prototype.getChildContext = function getChildContext() { return { store: this.store }; }; function Provider(props, context) { _classCallCheck(this, Provider); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.store = props.store; return _this; } Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var store = this.store; var nextStore = nextProps.store; if (store !== nextStore) { warnAboutReceivingStore(); } }; Provider.prototype.render = function render() { var children = this.props.children; return _react.Children.only(children); }; return Provider; })(_react.Component); exports.default = Provider; Provider.propTypes = { store: _storeShape2.default.isRequired, children: _react.PropTypes.element.isRequired }; Provider.childContextTypes = { store: _storeShape2.default.isRequired }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.__esModule = true; exports.default = connect; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _storeShape = __webpack_require__(2); var _storeShape2 = _interopRequireDefault(_storeShape); var _shallowEqual = __webpack_require__(6); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _isPlainObject = __webpack_require__(5); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _wrapActionCreators = __webpack_require__(7); var _wrapActionCreators2 = _interopRequireDefault(_wrapActionCreators); var _hoistNonReactStatics = __webpack_require__(8); var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); var _invariant = __webpack_require__(9); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var defaultMapStateToProps = function defaultMapStateToProps() { return {}; }; var defaultMapDispatchToProps = function defaultMapDispatchToProps(dispatch) { return { dispatch: dispatch }; }; var defaultMergeProps = function defaultMergeProps(stateProps, dispatchProps, parentProps) { return _extends({}, parentProps, stateProps, dispatchProps); }; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } // Helps track hot reloading. var nextVersion = 0; function connect(mapStateToProps, mapDispatchToProps, mergeProps) { var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; var shouldSubscribe = Boolean(mapStateToProps); var finalMapStateToProps = mapStateToProps || defaultMapStateToProps; var finalMapDispatchToProps = (0, _isPlainObject2.default)(mapDispatchToProps) ? (0, _wrapActionCreators2.default)(mapDispatchToProps) : mapDispatchToProps || defaultMapDispatchToProps; var finalMergeProps = mergeProps || defaultMergeProps; var shouldUpdateStateProps = finalMapStateToProps.length > 1; var shouldUpdateDispatchProps = finalMapDispatchToProps.length > 1; var _options$pure = options.pure; var pure = _options$pure === undefined ? true : _options$pure; var _options$withRef = options.withRef; var withRef = _options$withRef === undefined ? false : _options$withRef; // Helps track hot reloading. var version = nextVersion++; function computeStateProps(store, props) { var state = store.getState(); var stateProps = shouldUpdateStateProps ? finalMapStateToProps(state, props) : finalMapStateToProps(state); (0, _invariant2.default)((0, _isPlainObject2.default)(stateProps), '`mapStateToProps` must return an object. Instead received %s.', stateProps); return stateProps; } function computeDispatchProps(store, props) { var dispatch = store.dispatch; var dispatchProps = shouldUpdateDispatchProps ? finalMapDispatchToProps(dispatch, props) : finalMapDispatchToProps(dispatch); (0, _invariant2.default)((0, _isPlainObject2.default)(dispatchProps), '`mapDispatchToProps` must return an object. Instead received %s.', dispatchProps); return dispatchProps; } function _computeNextState(stateProps, dispatchProps, parentProps) { var mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps); (0, _invariant2.default)((0, _isPlainObject2.default)(mergedProps), '`mergeProps` must return an object. Instead received %s.', mergedProps); return mergedProps; } return function wrapWithConnect(WrappedComponent) { var Connect = (function (_Component) { _inherits(Connect, _Component); Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { if (!pure) { this.updateStateProps(nextProps); this.updateDispatchProps(nextProps); this.updateState(nextProps); return true; } var storeChanged = nextState.storeState !== this.state.storeState; var propsChanged = !(0, _shallowEqual2.default)(nextProps, this.props); var mapStateProducedChange = false; var dispatchPropsChanged = false; if (storeChanged || propsChanged && shouldUpdateStateProps) { mapStateProducedChange = this.updateStateProps(nextProps); } if (propsChanged && shouldUpdateDispatchProps) { dispatchPropsChanged = this.updateDispatchProps(nextProps); } if (propsChanged || mapStateProducedChange || dispatchPropsChanged) { this.updateState(nextProps); return true; } return false; }; function Connect(props, context) { _classCallCheck(this, Connect); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.version = version; _this.store = props.store || context.store; (0, _invariant2.default)(_this.store, 'Could not find "store" in either the context or ' + ('props of "' + _this.constructor.displayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "store" as a prop to "' + _this.constructor.displayName + '".')); _this.stateProps = computeStateProps(_this.store, props); _this.dispatchProps = computeDispatchProps(_this.store, props); _this.state = { storeState: null }; _this.updateState(); return _this; } Connect.prototype.computeNextState = function computeNextState() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; return _computeNextState(this.stateProps, this.dispatchProps, props); }; Connect.prototype.updateStateProps = function updateStateProps() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var nextStateProps = computeStateProps(this.store, props); if ((0, _shallowEqual2.default)(nextStateProps, this.stateProps)) { return false; } this.stateProps = nextStateProps; return true; }; Connect.prototype.updateDispatchProps = function updateDispatchProps() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var nextDispatchProps = computeDispatchProps(this.store, props); if ((0, _shallowEqual2.default)(nextDispatchProps, this.dispatchProps)) { return false; } this.dispatchProps = nextDispatchProps; return true; }; Connect.prototype.updateState = function updateState() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; this.nextState = this.computeNextState(props); }; Connect.prototype.isSubscribed = function isSubscribed() { return typeof this.unsubscribe === 'function'; }; Connect.prototype.trySubscribe = function trySubscribe() { if (shouldSubscribe && !this.unsubscribe) { this.unsubscribe = this.store.subscribe(this.handleChange.bind(this)); this.handleChange(); } }; Connect.prototype.tryUnsubscribe = function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; } }; Connect.prototype.componentDidMount = function componentDidMount() { this.trySubscribe(); }; Connect.prototype.componentWillUnmount = function componentWillUnmount() { this.tryUnsubscribe(); }; Connect.prototype.handleChange = function handleChange() { if (!this.unsubscribe) { return; } this.setState({ storeState: this.store.getState() }); }; Connect.prototype.getWrappedInstance = function getWrappedInstance() { (0, _invariant2.default)(withRef, 'To access the wrapped instance, you need to specify ' + '{ withRef: true } as the fourth argument of the connect() call.'); return this.refs.wrappedInstance; }; Connect.prototype.render = function render() { var ref = withRef ? 'wrappedInstance' : null; return _react2.default.createElement(WrappedComponent, _extends({}, this.nextState, { ref: ref })); }; return Connect; })(_react.Component); Connect.displayName = 'Connect(' + getDisplayName(WrappedComponent) + ')'; Connect.WrappedComponent = WrappedComponent; Connect.contextTypes = { store: _storeShape2.default }; Connect.propTypes = { store: _storeShape2.default }; if (true) { Connect.prototype.componentWillUpdate = function componentWillUpdate() { if (this.version === version) { return; } // We are hot reloading! this.version = version; // Update the state and bindings. this.trySubscribe(); this.updateStateProps(); this.updateDispatchProps(); this.updateState(); }; } return (0, _hoistNonReactStatics2.default)(Connect, WrappedComponent); }; } /***/ }, /* 5 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.default = isPlainObject; function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } var fnToString = function fnToString(fn) { return Function.prototype.toString.call(fn); }; /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject(obj) { if (!obj || (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object') { return false; } var proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype; if (proto === null) { return true; } var constructor = proto.constructor; return typeof constructor === 'function' && constructor instanceof constructor && fnToString(constructor) === fnToString(Object); } /***/ }, /* 6 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports.default = shallowEqual; function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = wrapActionCreators; var _redux = __webpack_require__(10); function wrapActionCreators(actionCreators) { return function (dispatch) { return (0, _redux.bindActionCreators)(actionCreators, dispatch); }; } /***/ }, /* 8 */ /***/ function(module, exports) { /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) { var keys = Object.getOwnPropertyNames(sourceComponent); for (var i=0; i<keys.length; ++i) { if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) { targetComponent[keys[i]] = sourceComponent[keys[i]]; } } return targetComponent; }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }, /* 10 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_10__; /***/ } /******/ ]) }); ;
ajax/libs/forerunnerdb/1.3.812/fdb-core+views.js
dada0423/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":34,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":9,"../lib/Shim.IE8":33}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":29,"./Shared":32}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":29,"./Shared":32}],5:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {*} callback Optional callback function. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * If the document contains a primary key field (based on the * collections's primary key) then the database will search for * an existing document with a matching id. If a matching * document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with * new data. Any keys that do not currently exist on the document * will be added to the document. * * If the document does not contain an id or the id passed does * not match an existing document, an insert is performed instead. * If no id is present a new primary key id is provided for the * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains * either "insert" or "update" depending on the type of operation * that was performed and "result" contains the return data from * the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this, updated || []); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } else { if (callback) { callback.call(this, updated || []); } } } else { if (callback) { callback.call(this, updated || []); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base object to alter. * @param {Object} newObj The new object to overwrite the existing one * with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark * (a dollar at the end of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search * query key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and * returns an object containing details about the query which * can be used to optimise the search. * * @param {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options, op); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options, op); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = this.objectId(); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other * variants and handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or * regular expression to use to match collection names against. * @returns {Array} An array of objects containing details of each * collection the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Condition":8,"./Index2d":12,"./IndexBinaryTree":13,"./IndexHashMap":14,"./KeyValueStore":15,"./Metrics":16,"./Overload":28,"./Path":29,"./ReactorIO":30,"./Shared":32}],7:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":6,"./Shared":32}],8:[function(_dereq_,module,exports){ "use strict"; /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. */ var //Overload = require('./Overload'), Shared, Condition; Shared = _dereq_('./Shared'); /** * Create a constructor method that calls the instance's init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. */ Condition = function () { this.init.apply(this, arguments); }; Condition.prototype.init = function (dataSource, id, clause) { this._dataSource = dataSource; this._id = id; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'id'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); Shared.synthesize(Condition.prototype, 'debug'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @param {*} initialState Initial state of condition. * @returns {Condition} */ Condition.prototype.start = function (initialState) { if (!this._started) { var self = this; if (arguments.length !== 0) { this._satisfied = initialState; } // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (this._debug) { console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]); } if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; /** * Drops the condition and removes it from memory. * @returns {Condition} */ Condition.prototype.drop = function () { this.stop(); delete this._dataSource.when[this._id]; return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":32}],9:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":10,"./Metrics.js":16,"./Overload":28,"./Shared":32}],10:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":5,"./Collection.js":6,"./Metrics.js":16,"./Overload":28,"./Shared":32}],11:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { lat: lat, lng: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":11,"./Path":29,"./Shared":32}],13:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":29,"./Shared":32}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":29,"./Shared":32}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk] !== undefined && val[pk] !== null) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":32}],16:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":27,"./Shared":32}],17:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],18:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Gets / sets the flag that will enable / disable chain reactor sending * from this instance. Chain reactor sending is enabled by default on all * instances. * @param {Boolean} val True or false to enable or disable chain sending. * @returns {*} */ chainEnabled: function (val) { if (val !== undefined) { this._chainDisabled = !val; return this; } return !this._chainDisabled; }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain && !this._chainDisabled); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain && !this._chainDisabled) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],19:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":28,"./Serialiser":31}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, id, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event); }); } else { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } } return this; }, 'string, function': function (event, listener) { var self = this, arr, index; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, listener); }); } else { if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } } return this; }, 'string, *, function': function (event, id, listener) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id, listener); }); } else { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } }, 'string, *': function (event, id) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id); }); } else { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } } }), emit: function (event, data) { this._listeners = this._listeners || {}; this._emitting = true; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } this._emitting = false; this._processRemovalQueue(); return this; }, /** * If events are cleared with the off() method while the event emitter is * actively processing any events then the off() calls get added to a * queue to be executed after the event emitter is finished. This stops * errors that might occur by potentially modifying the event queue while * the emitter is running through them. This method is called after the * event emitter is finished processing. * @private */ _processRemovalQueue: function () { var i; if (this._eventRemovalQueue && this._eventRemovalQueue.length) { // Execute each removal call for (i = 0; i < this._eventRemovalQueue.length; i++) { this._eventRemovalQueue[i](); } // Clear the removal queue this._eventRemovalQueue = []; } }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":28}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":28}],26:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],27:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":29,"./Shared":32}],28:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":32}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":32}],31:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],32:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.812', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":17,"./Mixin.ChainReactor":18,"./Mixin.Common":19,"./Mixin.Constants":20,"./Mixin.Events":21,"./Mixin.Matching":22,"./Mixin.Sorting":23,"./Mixin.Tags":24,"./Mixin.Triggers":25,"./Mixin.Updating":26,"./Overload":28}],33:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],34:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); //Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function (query, update, options, callback) { var finalQuery = { $and: [this.query(), query] }; this._from.update.call(this._from, finalQuery, update, options, callback); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well this.rebuildActiveBucket(this._querySettings.options); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * @see Mixin.Triggers::addTrigger() */ View.prototype.addTrigger = function () { return this._data.addTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeTrigger() */ View.prototype.removeTrigger = function () { return this._data.removeTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::ignoreTriggers() */ View.prototype.ignoreTriggers = function () { return this._data.ignoreTriggers.apply(this._data, arguments); }; /** * @see Mixin.Triggers::addLinkIO() */ View.prototype.addLinkIO = function () { return this._data.addLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeLinkIO() */ View.prototype.removeLinkIO = function () { return this._data.removeLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::willTrigger() */ View.prototype.willTrigger = function () { return this._data.willTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::processTrigger() */ View.prototype.processTrigger = function () { return this._data.processTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::_triggerIndexOf() */ View.prototype._triggerIndexOf = function () { return this._data._triggerIndexOf.apply(this._data, arguments); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this.decouple(this._querySettings.query); }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this.decouple(this._querySettings); } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":28,"./ReactorIO":30,"./Shared":32}]},{},[1]);
docs/src/app/components/pages/components/RefreshIndicator/ExampleReady.js
kasra-co/material-ui
import React from 'react'; import RefreshIndicator from 'material-ui/RefreshIndicator'; const style = { container: { position: 'relative', }, refresh: { display: 'inline-block', position: 'relative', }, }; const RefreshIndicatorExampleSimple = () => ( <div style={style.container}> <RefreshIndicator percentage={30} size={40} left={10} top={0} status="ready" style={style.refresh} /> <RefreshIndicator percentage={60} size={50} left={65} top={0} status="ready" style={style.refresh} /> <RefreshIndicator percentage={80} size={60} left={120} top={0} color={"red"} status="ready" style={style.refresh} /> <RefreshIndicator percentage={100} size={70} left={175} top={0} color={"red"} // Overridden by percentage={100} status="ready" style={style.refresh} /> </div> ); export default RefreshIndicatorExampleSimple;
test/components/Banners/UpdateMessage.spec.js
CPatchane/cozy-collect
'use strict' /* eslint-env jest */ import React from 'react' import { shallow } from 'enzyme' import { tMock } from '../../jestLib/I18n' import { UpdateMessage } from 'components/Banners/UpdateMessage' describe('UpdateMessage component', () => { it(`Should be render correctly if not blocking update`, () => { const component = shallow(<UpdateMessage t={tMock} />) .dive() .getElement() expect(component).toMatchSnapshot() }) it(`Should be render correctly if blocking update`, () => { const component = shallow(<UpdateMessage t={tMock} isBlocking />) .dive() .getElement() expect(component).toMatchSnapshot() }) })
client/components/auth/signup.js
raymestalez/vertex
import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import * as actions from '../../actions'; class Signup extends Component { handleFormSubmit({email, password}) { /* console.log(email, password);*/ // signupUser comes from actions. // it is an action creator that sends an email/pass to the server // and if they're correct, saves the token this.props.signupUser({email,password}); } renderAlert(){ if (this.props.errorMessage) { return ( <div className="alert alert-danger"> {this.props.errorMessage} </div> ); } } render () { /* props from reduxForm */ const { handleSubmit, fields: { email, password, passwordConfirm }} = this.props; /* console.log(...email);*/ console.log(this.props.fields); return ( <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <label>Email:</label> <input {...email} className="form-control" /> {email.touched && email.error && <div classNamer="error">{email.error}</div>} </fieldset> <fieldset className="form-group"> <label>Password:</label> <input {...password} type="password" className="form-control" /> {password.touched && password.error && <div classNamer="error">{password.error}</div>} </fieldset> <fieldset className="form-group"> <label>Repeat Password:</label> <input {...passwordConfirm} type="password" className="form-control" /> {passwordConfirm.touched && passwordConfirm.error && <div classNamer="error">{passwordConfirm.error}</div>} </fieldset> {this.renderAlert()} <button action="submit" className="btn btn-primary">Sign in</button> </form> ); } } function mapStateToProps(state) { return { errorMessage:state.auth.error }; } function validate(formProps) { const errors = {}; if (!formProps.email) { errors.email = "Enter an email"; } if (!formProps.password) { errors.password = "Enter a password"; } if (!formProps.passwordConfirm) { errors.passwordConfirm = "Enter a password confirmation"; } if (formProps.password != formProps.passwordConfirm) { errors.password = "Passwords don't match"; } /* console.log(errors);*/ return errors; } export default reduxForm({ form: 'signup', fields: ['email','password', 'passwordConfirm'], validate: validate }, mapStateToProps, actions)(Signup);
src/scripts/mixins/StoreWatchMixin.js
jshack3r/ws-react-starter
import React from 'react'; import AppStore from '../stores/store.js'; // ES2015 doesn't support mixins so we actually use a higher order component (StoreWatchMixin) // This receives a component to wrap and a state callback function as params and returns back a stateless component export default (Component, getStateCallback) => class extends React.Component { constructor(props) { super(props); this.state = getStateCallback(props); this._onChange = this._onChange.bind(this); } componentWillMount() { AppStore.addChangeListener(this._onChange); } componentWillUnmount() { AppStore.removeChangeListener(this._onChange); } _onChange() { this.setState(getStateCallback(this.props)); } render() { // Pass back the originally received props and also this state as props to the returned stateless component return <Component {...this.state} {...this.props} /> } }
app/routes.js
robteix/millie
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import HomePage from './containers/HomePage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> </Route> );
client/app/containers/FavoritesPage/index.js
yanhao-li/menu-plus
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import Subheader from 'material-ui/Subheader'; import RestaurantCard from 'components/Card/RestaurantCard'; import Paper from 'material-ui/Paper'; import PropTypes from 'prop-types'; const propTypes = { favorites: PropTypes.object.isRequired, }; const styles = { paper: { backgroundColor: '#ffffff', height: '100%', marginTop: 30, }, }; class FavoritesPage extends React.PureComponent { constructor(props) { super(props); this.state = { restaurants: this.props.favorites.restaurants, }; } componentWillReceiveProps(nextProps) { const { favorites } = nextProps; const { restaurants } = favorites; this.setState({ restaurants, }); } render() { const { isFetching } = this.props.favorites; const { restaurants } = this.state; if (isFetching) { return ( <div> Loading </div> ); } return ( <Paper className="container" style={styles.paper}> <Subheader>My favorites</Subheader> <ul className="row"> {restaurants.map((restaurant) => (<li key={restaurant.info.id}> <Link to={`/restaurant/${restaurant.info.id}`}><RestaurantCard restaurant={restaurant.info} /></Link></li> ) )} </ul> </Paper> ); } } FavoritesPage.propTypes = propTypes; const mapStateToProps = (state) => ({ auth: state.get('auth'), favorites: state.get('favorites'), }); export default connect(mapStateToProps)(FavoritesPage);
ajax/libs/yui/3.14.0/scrollview-base/scrollview-base-debug.js
hpneo/cdnjs
YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ // Local vars var getClassName = Y.ClassNameManager.getClassName, DOCUMENT = Y.config.doc, IE = Y.UA.ie, NATIVE_TRANSITIONS = Y.Transition.useNative, vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated SCROLLVIEW = 'scrollview', CLASS_NAMES = { vertical: getClassName(SCROLLVIEW, 'vert'), horizontal: getClassName(SCROLLVIEW, 'horiz') }, EV_SCROLL_END = 'scrollEnd', FLICK = 'flick', DRAG = 'drag', MOUSEWHEEL = 'mousewheel', UI = 'ui', TOP = 'top', LEFT = 'left', PX = 'px', AXIS = 'axis', SCROLL_Y = 'scrollY', SCROLL_X = 'scrollX', BOUNCE = 'bounce', DISABLED = 'disabled', DECELERATION = 'deceleration', DIM_X = 'x', DIM_Y = 'y', BOUNDING_BOX = 'boundingBox', CONTENT_BOX = 'contentBox', GESTURE_MOVE = 'gesturemove', START = 'start', END = 'end', EMPTY = '', ZERO = '0s', SNAP_DURATION = 'snapDuration', SNAP_EASING = 'snapEasing', EASING = 'easing', FRAME_DURATION = 'frameDuration', BOUNCE_RANGE = 'bounceRange', _constrain = function (val, min, max) { return Math.min(Math.max(val, min), max); }; /** * ScrollView provides a scrollable widget, supporting flick gestures, * across both touch and mouse based devices. * * @class ScrollView * @param config {Object} Object literal with initial attribute values * @extends Widget * @constructor */ function ScrollView() { ScrollView.superclass.constructor.apply(this, arguments); } Y.ScrollView = Y.extend(ScrollView, Y.Widget, { // *** Y.ScrollView prototype /** * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit. * Used by the _transform method. * * @property _forceHWTransforms * @type boolean * @protected */ _forceHWTransforms: Y.UA.webkit ? true : false, /** * <p>Used to control whether or not ScrollView's internal * gesturemovestart, gesturemove and gesturemoveend * event listeners should preventDefault. The value is an * object, with "start", "move" and "end" properties used to * specify which events should preventDefault and which shouldn't:</p> * * <pre> * { * start: false, * move: true, * end: false * } * </pre> * * <p>The default values are set up in order to prevent panning, * on touch devices, while allowing click listeners on elements inside * the ScrollView to be notified as expected.</p> * * @property _prevent * @type Object * @protected */ _prevent: { start: false, move: true, end: false }, /** * Contains the distance (postive or negative) in pixels by which * the scrollview was last scrolled. This is useful when setting up * click listeners on the scrollview content, which on mouse based * devices are always fired, even after a drag/flick. * * <p>Touch based devices don't currently fire a click event, * if the finger has been moved (beyond a threshold) so this * check isn't required, if working in a purely touch based environment</p> * * @property lastScrolledAmt * @type Number * @public * @default 0 */ lastScrolledAmt: 0, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ _minScrollX: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ _maxScrollX: null, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ _minScrollY: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ _maxScrollY: null, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { var sv = this; // Cache these values, since they aren't going to change. sv._bb = sv.get(BOUNDING_BOX); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes sv._cAxis = sv.get(AXIS); sv._cBounce = sv.get(BOUNCE); sv._cBounceRange = sv.get(BOUNCE_RANGE); sv._cDeceleration = sv.get(DECELERATION); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { var sv = this; // Bind interaction listers sv._bindFlick(sv.get(FLICK)); sv._bindDrag(sv.get(DRAG)); sv._bindMousewheel(true); // Bind change events sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. if (IE) { sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties if (ScrollView.SNAP_DURATION) { sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } if (ScrollView.SNAP_EASING) { sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } if (ScrollView.EASING) { sv.set(EASING, ScrollView.EASING); } if (ScrollView.FRAME_STEP) { sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } if (ScrollView.BOUNCE_RANGE) { sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE); } // Recalculate dimension properties // TODO: This should be throttled. // Y.one(WINDOW).after('resize', sv._afterDimChange, sv); }, /** * Bind event listeners * * @method _bindAttrs * @private */ _bindAttrs: function () { var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners sv.after({ 'scrollEnd': sv._afterScrollEnd, 'disabledChange': sv._afterDisabledChange, 'flickChange': sv._afterFlickChange, 'dragChange': sv._afterDragChange, 'axisChange': sv._afterAxisChange, 'scrollYChange': scrollChangeHandler, 'scrollXChange': scrollChangeHandler, 'heightChange': dimChangeHandler, 'widthChange': dimChangeHandler }); }, /** * Bind (or unbind) gesture move listeners required for drag support * * @method _bindDrag * @param drag {boolean} If true, the method binds listener to enable * drag (gesturemovestart). If false, the method unbinds gesturemove * listeners for drag support. * @private */ _bindDrag: function (drag) { var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners bb.detach(DRAG + '|*'); if (drag) { bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv)); } }, /** * Bind (or unbind) flick listeners. * * @method _bindFlick * @param flick {Object|boolean} If truthy, the method binds listeners for * flick support. If false, the method unbinds flick listeners. * @private */ _bindFlick: function (flick) { var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners bb.detach(FLICK + '|*'); if (flick) { bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick sv._bindDrag(sv.get(DRAG)); } }, /** * Bind (or unbind) mousewheel listeners. * * @method _bindMousewheel * @param mousewheel {Object|boolean} If truthy, the method binds listeners for * mousewheel support. If false, the method unbinds mousewheel listeners. * @private */ _bindMousewheel: function (mousewheel) { var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv)); } }, /** * syncUI implementation. * * Update the scroll position, based on the current value of scrollX/scrollY. * * @method syncUI */ syncUI: function () { var sv = this, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight; // If the axis is undefined, auto-calculate it if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value sv._cDisabled = sv.get(DISABLED); // Run this to set initial values sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. if (sv._isOutOfBounds()) { sv._snapBack(); } }, /** * Utility method to obtain widget dimensions * * @method _getScrollDims * @return {Object} The offsetWidth, offsetHeight, scrollWidth and * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth, * scrollHeight] * @private */ _getScrollDims: function () { var sv = this, cb = sv._cb, bb = sv._bb, TRANS = ScrollView._TRANSITION, // Ideally using CSSMatrix - don't think we have it normalized yet though. // origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e, // origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f, origX = sv.get(SCROLL_X), origY = sv.get(SCROLL_Y), origHWTransform, dims; // TODO: Is this OK? Just in case it's called 'during' a transition. if (NATIVE_TRANSITIONS) { cb.setStyle(TRANS.DURATION, ZERO); cb.setStyle(TRANS.PROPERTY, EMPTY); } origHWTransform = sv._forceHWTransforms; sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. sv._moveTo(cb, 0, 0); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; sv._moveTo(cb, -(origX), -(origY)); sv._forceHWTransforms = origHWTransform; return dims; }, /** * This method gets invoked whenever the height or width attributes change, * allowing us to determine which scrolling axes need to be enabled. * * @method _uiDimensionsChange * @protected */ _uiDimensionsChange: function () { var sv = this, bb = sv._bb, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight, rtl = sv.rtl, svAxis = sv._cAxis, minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0), maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)), minScrollY = 0, maxScrollY = Math.max(0, scrollHeight - height); if (svAxis && svAxis.x) { bb.addClass(CLASS_NAMES.horizontal); } if (svAxis && svAxis.y) { bb.addClass(CLASS_NAMES.vertical); } sv._setBounds({ minScrollX: minScrollX, maxScrollX: maxScrollX, minScrollY: minScrollY, maxScrollY: maxScrollY }); }, /** * Set the bounding dimensions of the ScrollView * * @method _setBounds * @protected * @param bounds {Object} [duration] ms of the scroll animation. (default is 0) * @param {Number} [bounds.minScrollX] The minimum scroll X value * @param {Number} [bounds.maxScrollX] The maximum scroll X value * @param {Number} [bounds.minScrollY] The minimum scroll Y value * @param {Number} [bounds.maxScrollY] The maximum scroll Y value */ _setBounds: function (bounds) { var sv = this; // TODO: Do a check to log if the bounds are invalid sv._minScrollX = bounds.minScrollX; sv._maxScrollX = bounds.maxScrollX; sv._minScrollY = bounds.minScrollY; sv._maxScrollY = bounds.maxScrollY; }, /** * Get the bounding dimensions of the ScrollView * * @method _getBounds * @protected */ _getBounds: function () { var sv = this; return { minScrollX: sv._minScrollX, maxScrollX: sv._maxScrollX, minScrollY: sv._minScrollY, maxScrollY: sv._maxScrollY }; }, /** * Scroll the element to a given xy coordinate * * @method scrollTo * @param x {Number} The x-position to scroll to. (null for no movement) * @param y {Number} The y-position to scroll to. (null for no movement) * @param {Number} [duration] ms of the scroll animation. (default is 0) * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute) * @param {String} [node] The node to transform. Setting this can be useful in * dual-axis paginated instances. (default is the instance's contentBox) */ scrollTo: function (x, y, duration, easing, node) { // Check to see if widget is disabled if (this._cDisabled) { return; } var sv = this, cb = sv._cb, TRANS = ScrollView._TRANSITION, callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this newX = 0, newY = 0, transition = {}, transform; // default the optional arguments duration = duration || 0; easing = easing || sv.get(EASING); // @TODO: Cache this node = node || cb; if (x !== null) { sv.set(SCROLL_X, x, {src:UI}); newX = -(x); } if (y !== null) { sv.set(SCROLL_Y, y, {src:UI}); newY = -(y); } transform = sv._transform(newX, newY); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move if (duration === 0) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', transform); } else { // TODO: If both set, batch them in the same update // Update: Nope, setStyles() just loops through each property and applies it. if (x !== null) { node.setStyle(LEFT, newX + PX); } if (y !== null) { node.setStyle(TOP, newY + PX); } } } // Animate else { transition.easing = easing; transition.duration = duration / 1000; if (NATIVE_TRANSITIONS) { transition.transform = transform; } else { transition.left = newX + PX; transition.top = newY + PX; } node.transition(transition, callback); } }, /** * Utility method, to create the translate transform string with the * x, y translation amounts provided. * * @method _transform * @param {Number} x Number of pixels to translate along the x axis * @param {Number} y Number of pixels to translate along the y axis * @private */ _transform: function (x, y) { // TODO: Would we be better off using a Matrix for this? var prop = 'translate(' + x + 'px, ' + y + 'px)'; if (this._forceHWTransforms) { prop += ' translateZ(0)'; } return prop; }, /** * Utility method, to move the given element to the given xy position * * @method _moveTo * @param node {Node} The node to move * @param x {Number} The x-position to move to * @param y {Number} The y-position to move to * @private */ _moveTo : function(node, x, y) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', this._transform(x, y)); } else { node.setStyle(LEFT, x + PX); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { var sv = this; // If for some reason we're OOB, snapback if (sv._isOutOfBounds()) { sv._snapBack(); } else { /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ sv.fire(EV_SCROLL_END); } }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { if (this._cDisabled) { return false; } var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; if (sv._prevent.start) { e.preventDefault(); } // if a flick animation is in progress, cancel it if (sv._flickAnim) { sv._cancelFlick(); sv._onTransEnd(); } // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later sv._gesture = { // Will hold the axis value axis: null, // The current attribute values startX: currentX, startY: currentY, // The X/Y coordinates where the event began startClientX: clientX, startClientY: clientY, // The X/Y coordinates where the event will end endClientX: null, endClientY: null, // The current delta of the event deltaX: null, deltaY: null, // Will be populated for flicks flick: null, // Create some listeners for the rest of the gesture cycle onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)), // @TODO: Don't bind gestureMoveEnd if it's a Flick? onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv)) }; }, /** * gesturemove event handler * * @method _onGestureMove * @param e {Event.Facade} The gesturemove event facade * @private */ _onGestureMove: function (e) { var sv = this, gesture = sv._gesture, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, startX = gesture.startX, startY = gesture.startY, startClientX = gesture.startClientX, startClientY = gesture.startClientY, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.move) { e.preventDefault(); } gesture.deltaX = startClientX - clientX; gesture.deltaY = startClientY - clientY; // Determine if this is a vertical or horizontal movement // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent if (gesture.axis === null) { gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. if (gesture.axis === DIM_X && svAxisX) { sv.set(SCROLL_X, startX + gesture.deltaX); } else if (gesture.axis === DIM_Y && svAxisY) { sv.set(SCROLL_Y, startY + gesture.deltaY); } }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY, isOOB; if (sv._prevent.end) { e.preventDefault(); } // Store the end X/Y coordinates gesture.endClientX = clientX; gesture.endClientY = clientY; // Cleanup the event handlers gesture.onGestureMove.detach(); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle if (!flick) { // @TODO: Be more intelligent about this. Look at the Flick attribute to see // if it is safe to assume _flick did or didn't fire. // Then, the order _flick and _onGestureMoveEnd fire doesn't matter? // If there was movement (_onGestureMove fired) if (gesture.deltaX !== null && gesture.deltaY !== null) { isOOB = sv._isOutOfBounds(); // If we're out-out-bounds, then snapback if (isOOB) { sv._snapBack(); } // Inbounds else { // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) { sv._onTransEnd(); } } } } }, /** * Execute a flick at the end of a scroll action * * @method _flick * @param e {Event.Facade} The Flick event facade * @private */ _flick: function (e) { if (this._cDisabled) { return false; } var sv = this, svAxis = sv._cAxis, flick = e.flick, flickAxis = flick.axis, flickVelocity = flick.velocity, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, startPosition = sv.get(axisAttr); // Sometimes flick is enabled, but drag is disabled if (sv._gesture) { sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis if (svAxis[flickAxis]) { sv._flickFrame(flickVelocity, flickAxis, startPosition); } }, /** * Execute a single frame in the flick animation * * @method _flickFrame * @param velocity {Number} The velocity of this animated frame * @param flickAxis {String} The axis on which to animate * @param startPosition {Number} The starting X/Y point to flick from * @protected */ _flickFrame: function (velocity, flickAxis, startPosition) { var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, bounds = sv._getBounds(), // Localize cached values bounce = sv._cBounce, bounceRange = sv._cBounceRange, deceleration = sv._cDeceleration, frameDuration = sv._cFrameDuration, // Calculate newVelocity = velocity * deceleration, newPosition = startPosition - (frameDuration * newVelocity), // Some convinience conditions min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY, max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY, belowMin = (newPosition < min), belowMax = (newPosition < max), aboveMin = (newPosition > min), aboveMax = (newPosition > max), belowMinRange = (newPosition < (min - bounceRange)), withinMinRange = (belowMin && (newPosition > (min - bounceRange))), withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))), aboveMaxRange = (newPosition > (max + bounceRange)), tooSlow; // If we're within the range but outside min/max, dampen the velocity if (withinMinRange || withinMaxRange) { newVelocity *= bounce; } // Is the velocity too slow to bother? tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim if (sv._flickAnim) { sv._cancelFlick(); } // If we're inside the scroll area, just end if (aboveMin && belowMax) { sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); sv.set(axisAttr, newPosition); } }, _cancelFlick: function () { var sv = this; if (sv._flickAnim) { // Cancel the flick (if it exists) sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking delete sv._flickAnim; } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { var sv = this, scrollY = sv.get(SCROLL_Y), bounds = sv._getBounds(), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY); // Because Mousewheel events fire off 'document', every ScrollView widget will react // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis, // becuase otherwise the 'prevent' will block page scrolling. if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Jump to the new offset sv.set(SCROLL_Y, scrollToY); // if we have scrollbars plugin, update & set the flash timer on the scrollbar // @TODO: This probably shouldn't be in this module if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves sv.scrollbars._update(); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event sv._onTransEnd(); // prevent browser default behavior on mouse scroll e.preventDefault(); } }, /** * Checks to see the current scrollX/scrollY position beyond the min/max boundary * * @method _isOutOfBounds * @param x {Number} [optional] The X position to check * @param y {Number} [optional] The Y position to check * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false) * @private */ _isOutOfBounds: function (x, y) { var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY; return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY)); }, /** * Bounces back * @TODO: Should be more generalized and support both X and Y detection * * @method _snapBack * @private */ _snapBack: function () { var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); if (newX !== currentX) { sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else if (newY !== currentY) { sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { sv._onTransEnd(); } }, /** * After listener for changes to the scrollX or scrollY attribute * * @method _afterScrollChange * @param e {Event.Facade} The event facade * @protected */ _afterScrollChange: function (e) { if (e.src === ScrollView.UI_SRC) { return false; } var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() if (e.attrName === SCROLL_X) { scrollToArgs.push(val); scrollToArgs.push(sv.get(SCROLL_Y)); } else { scrollToArgs.push(sv.get(SCROLL_X)); scrollToArgs.push(val); } scrollToArgs.push(duration); scrollToArgs.push(easing); sv.scrollTo.apply(sv, scrollToArgs); }, /** * After listener for changes to the flick attribute * * @method _afterFlickChange * @param e {Event.Facade} The event facade * @protected */ _afterFlickChange: function (e) { this._bindFlick(e.newVal); }, /** * After listener for changes to the disabled attribute * * @method _afterDisabledChange * @param e {Event.Facade} The event facade * @protected */ _afterDisabledChange: function (e) { // Cache for performance - we check during move this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { this._cAxis = e.newVal; }, /** * After listener for changes to the drag attribute * * @method _afterDragChange * @param e {Event.Facade} The event facade * @protected */ _afterDragChange: function (e) { this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { var sv = this; if (sv._flickAnim) { sv._cancelFlick(); } // Ideally this should be removed, but doing so causing some JS errors with fast swiping // because _gesture is being deleted after the previous one has been overwritten // delete sv._gesture; // TODO: Move to sv.prevGesture? }, /** * Setter for 'axis' attribute * * @method _axisSetter * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on * @param name {String} The attribute name * @return {Object} An object to specify scrollability on the x & y axes * * @protected */ _axisSetter: function (val) { // Turn a string into an axis object if (Y.Lang.isString(val)) { return { x: val.match(/x/i) ? true : false, y: val.match(/y/i) ? true : false }; } }, /** * The scrollX, scrollY setter implementation * * @method _setScroll * @private * @param {Number} val * @param {String} dim * * @return {Number} The value */ _setScroll : function(val) { // Just ensure the widget is not disabled if (this._cDisabled) { val = Y.Attribute.INVALID_VALUE; } return val; }, /** * Setter for the scrollX attribute * * @method _setScrollX * @param val {Number} The new scrollX value * @return {Number} The normalized value * @protected */ _setScrollX: function(val) { return this._setScroll(val, DIM_X); }, /** * Setter for the scrollY ATTR * * @method _setScrollY * @param val {Number} The new scrollY value * @return {Number} The normalized value * @protected */ _setScrollY: function(val) { return this._setScroll(val, DIM_Y); } // End prototype properties }, { // Static properties /** * The identity of the widget. * * @property NAME * @type String * @default 'scrollview' * @readOnly * @protected * @static */ NAME: 'scrollview', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Specifies ability to scroll on x, y, or x and y axis/axes. * * @attribute axis * @type String */ axis: { setter: '_axisSetter', writeOnce: 'initOnly' }, /** * The current scroll position in the x-axis * * @attribute scrollX * @type Number * @default 0 */ scrollX: { value: 0, setter: '_setScrollX' }, /** * The current scroll position in the y-axis * * @attribute scrollY * @type Number * @default 0 */ scrollY: { value: 0, setter: '_setScrollY' }, /** * Drag coefficent for inertial scrolling. The closer to 1 this * value is, the less friction during scrolling. * * @attribute deceleration * @default 0.93 */ deceleration: { value: 0.93 }, /** * Drag coefficient for intertial scrolling at the upper * and lower boundaries of the scrollview. Set to 0 to * disable "rubber-banding". * * @attribute bounce * @type Number * @default 0.1 */ bounce: { value: 0.1 }, /** * The minimum distance and/or velocity which define a flick. Can be set to false, * to disable flick support (note: drag support is enabled/disabled separately) * * @attribute flick * @type Object * @default Object with properties minDistance = 10, minVelocity = 0.3. */ flick: { value: { minDistance: 10, minVelocity: 0.3 } }, /** * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately) * @attribute drag * @type boolean * @default true */ drag: { value: true }, /** * The default duration to use when animating the bounce snap back. * * @attribute snapDuration * @type Number * @default 400 */ snapDuration: { value: 400 }, /** * The default easing to use when animating the bounce snap back. * * @attribute snapEasing * @type String * @default 'ease-out' */ snapEasing: { value: 'ease-out' }, /** * The default easing used when animating the flick * * @attribute easing * @type String * @default 'cubic-bezier(0, 0.1, 0, 1.0)' */ easing: { value: 'cubic-bezier(0, 0.1, 0, 1.0)' }, /** * The interval (ms) used when animating the flick for JS-timer animations * * @attribute frameDuration * @type Number * @default 15 */ frameDuration: { value: 15 }, /** * The default bounce distance in pixels * * @attribute bounceRange * @type Number * @default 150 */ bounceRange: { value: 150 } }, /** * List of class names used in the scrollview's DOM * * @property CLASS_NAMES * @type Object * @static */ CLASS_NAMES: CLASS_NAMES, /** * Flag used to source property changes initiated from the DOM * * @property UI_SRC * @type String * @static * @default 'ui' */ UI_SRC: UI, /** * Object map of style property names used to set transition properties. * Defaults to the vendor prefix established by the Transition module. * The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and * `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty"). * * @property _TRANSITION * @private */ _TRANSITION: { DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'), PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty') }, /** * The default bounce distance in pixels * * @property BOUNCE_RANGE * @type Number * @static * @default false * @deprecated (in 3.7.0) */ BOUNCE_RANGE: false, /** * The interval (ms) used when animating the flick * * @property FRAME_STEP * @type Number * @static * @default false * @deprecated (in 3.7.0) */ FRAME_STEP: false, /** * The default easing used when animating the flick * * @property EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ EASING: false, /** * The default easing to use when animating the bounce snap back. * * @property SNAP_EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ SNAP_EASING: false, /** * The default duration to use when animating the bounce snap back. * * @property SNAP_DURATION * @type Number * @static * @default false * @deprecated (in 3.7.0) */ SNAP_DURATION: false // End static properties }); }, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
src/components/Vehicles.js
mick842/rental-cars-client
import React from 'react'; import Vehicle from "./Vehicle"; function Vehicles(props) { return ( <div className="vehicles"> { props.vehicles.map((vehicle) => { return <Vehicle key={vehicle.id} mark={vehicle.mark} model={vehicle.model} year={vehicle.year} gearbox={vehicle.gearboxType} image={vehicle.image} pricePerDay={vehicle.pricePerDay} status={vehicle.status} id={vehicle.id} /> })} </div> ); } export default Vehicles;
src/components/App.js
TonyHYK/tonyhyk.github.io
import React, { Component } from 'react'; import AboutMe from './AboutMe'; import AboutSite from './AboutSite'; import Work from './Work'; import Contact from './Contact'; import isMobile from 'is-mobile'; //carousel stuff import {Carousel} from 'react-responsive-carousel'; import 'style-loader!react-responsive-carousel/lib/styles/carousel.css'; let TABS = ["Home", "Work", "Contact", "About Me", "About This Site"]; class App extends Component { constructor(props) { super(props); this.changeTab = this.changeTab.bind(this); this.state = {tab: TABS[0]}; } render() { return ( <div> <NavBar changeTab={this.changeTab} /> <Header tab={this.state.tab} /> <Content tab={this.state.tab} /> <BackgroundCarousel /> </div> ); } changeTab(newTab) { this.setState({tab: TABS[newTab]}); } } function Content({tab}) { let div; switch (tab) { case TABS[1]: div = <Work />; break; case TABS[2]: div = <Contact />; break; case TABS[3]: div = <AboutMe />; break; case TABS[4]: div = <AboutSite />; break; default: div = <div />; } return <div className="content">{div}</div>; } function Header({tab}) { return ( <div className="header"> { tab === TABS[0] ? <div> <h1>Tony Hung</h1> <div className="profile" /> <h2 className="keywords">Programmer | Gamer | Traveler</h2> </div> : <div className="profile hideOnMobile" /> } </div> ) } function NavBar({changeTab}) { return ( <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-collapse collapse"> <ul className="nav navbar-nav navbar-right"> { TABS.map((t, i) => { return ( <li key={i} onClick={() => changeTab(i)}><a>{t}</a></li> ) }) } </ul> </div> </div> </nav> ) } function BackgroundCarousel() { if (isMobile()) { return ( <div className="carousel"> <div className="background backMobile" /> </div> ); } else { return ( <Carousel className="carousel" axis="horizontal" showThumbs={false} showStatus={false} showArrows={false} autoPlay infiniteLoop interval={5000}> <div> <div className="background back1"/> <p className="legend">Kayangan Lake, Philippines</p> </div> <div> <div className="background back2"/> <p className="legend">Nara, Japan</p> </div> <div> <div className="background back3"/> <p className="legend">Berlin, Germany</p> </div> </Carousel> ); } } export default App;
docs/src/app/components/pages/components/Divider/ExampleMenu.js
mmrtnz/material-ui
import React from 'react'; import Divider from 'material-ui/Divider'; import {Menu, MenuItem} from 'material-ui/Menu'; const style = { // Without this, the menu overflows the CodeExample container. float: 'left', }; const DividerExampleMenu = () => ( <Menu desktop={true} style={style}> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Help & feedback" /> <Divider /> <MenuItem primaryText="Sign out" /> </Menu> ); export default DividerExampleMenu;
src/entypo/XingWithCircle.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--XingWithCircle'; let EntypoXingWithCircle = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M10,0.4c-5.302,0-9.6,4.298-9.6,9.6s4.298,9.6,9.6,9.6s9.6-4.298,9.6-9.6S15.302,0.4,10,0.4z M8.063,11.5c0,0-0.086,0.172-0.153,0.309C7.839,11.947,7.674,12,7.563,12H6.149c-0.25,0-0.239-0.191-0.178-0.316C6.034,11.559,6.063,11.5,6.063,11.5l1.125-2.25L6.563,8c0,0-0.029-0.06-0.092-0.185C6.41,7.69,6.399,7.5,6.649,7.5h1.414c0.111,0,0.276,0.053,0.347,0.19C8.477,7.828,8.563,8,8.563,8l0.625,1.25L8.063,11.5z M14.03,5.815C13.967,5.94,13.938,6,13.938,6l-2.5,5l1.5,3c0,0,0.029,0.059,0.092,0.184c0.062,0.125,0.072,0.316-0.178,0.316h-1.414c-0.112,0-0.275-0.053-0.345-0.191C11.024,14.171,10.938,14,10.938,14l-1.5-3l2.5-5c0,0,0.086-0.172,0.155-0.31c0.069-0.138,0.232-0.19,0.345-0.19h1.414C14.102,5.5,14.091,5.69,14.03,5.815z"/> </EntypoIcon> ); export default EntypoXingWithCircle;
client/src/auth/SignOut.js
flyrightsister/boxcharter
/* * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved. * * This file is part of BoxCharter. * * BoxCharter is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * BoxCharter is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>. * */ /** * Written with help from Stephen Grider's Advanced React and Redux Udemy Course * @module * SignOut */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { ClarityAlert } from '../clarity'; import SignIn from './SignIn'; import * as actions from './authActions'; /** * @class SignOut */ export class SignOutComponent extends Component { /** * Set alert state to true by default. * @method constructor * @param {object} props - React props. * @returns {undefined} */ constructor(props) { super(props); this.state = { alertOpen: true, }; this.closeAlert = this.closeAlert.bind(this); } /** * @method componentWillMont * @returns {undefined} */ componentWillMount() { this.props.signOutUser(); } /** * Set alertOpen state to false. * @method closeAlert * @returns {undefined} */ closeAlert() { this.setState({ alertOpen: false }); } /** * @method render * @returns {JSX.Element} - Rendered component. */ render() { return ( <div data-test="sign-out-component"> { this.state.alertOpen ? <ClarityAlert communicateCloseToParent={this.closeAlert} alertType="success" alertText="You have been logged out." /> : null } <SignIn /> </div>); } } SignOutComponent.propTypes = { signOutUser: PropTypes.func.isRequired, }; export default connect(null, actions)(SignOutComponent);
src/constants/PayloadSources.js
sdjustin/arena-deck-review
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var keyMirror = require('react/lib/keyMirror'); var PayloadSources = keyMirror({ VIEW_ACTION: null, SERVER_ACTION: null }); module.exports = PayloadSources;
ajax/libs/yui/3.7.3/event-focus/event-focus.js
ram-nadella/cdnjs
YUI.add('event-focus', function (Y, NAME) { /** * Adds bubbling and delegation support to DOM events focus and blur. * * @module event * @submodule event-focus */ var Event = Y.Event, YLang = Y.Lang, isString = YLang.isString, arrayIndex = Y.Array.indexOf, useActivate = (function() { // Changing the structure of this test, so that it doesn't use inline JS in HTML, // which throws an exception in Win8 packaged apps, due to additional security restrictions: // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences var p = Y.config.doc.createElement("p"), listener; p.setAttribute("onbeforeactivate", ";"); listener = p.onbeforeactivate; // listener is a function in IE8+. // listener is a string in IE6,7 (unfortunate, but that's not going to change. Otherwise we could have just checked for function). // listener is a function in IE10, in a Win8 App environment (no exception running the test). // listener is undefined in Webkit/Gecko. // listener is a function in Webkit/Gecko if it's a supported event (e.g. onclick). return (listener !== undefined); }()); function define(type, proxy, directEvent) { var nodeDataKey = '_' + type + 'Notifiers'; Y.Event.define(type, { _useActivate : useActivate, _attach: function (el, notifier, delegate) { if (Y.DOM.isWindow(el)) { return Event._attach([type, function (e) { notifier.fire(e); }, el]); } else { return Event._attach( [proxy, this._proxy, el, this, notifier, delegate], { capture: true }); } }, _proxy: function (e, notifier, delegate) { var target = e.target, currentTarget = e.currentTarget, notifiers = target.getData(nodeDataKey), yuid = Y.stamp(currentTarget._node), defer = (useActivate || target !== currentTarget), directSub; notifier.currentTarget = (delegate) ? target : currentTarget; notifier.container = (delegate) ? currentTarget : null; // Maintain a list to handle subscriptions from nested // containers div#a>div#b>input #a.on(focus..) #b.on(focus..), // use one focus or blur subscription that fires notifiers from // #b then #a to emulate bubble sequence. if (!notifiers) { notifiers = {}; target.setData(nodeDataKey, notifiers); // only subscribe to the element's focus if the target is // not the current target ( if (defer) { directSub = Event._attach( [directEvent, this._notify, target._node]).sub; directSub.once = true; } } else { // In old IE, defer is always true. In capture-phase browsers, // The delegate subscriptions will be encountered first, which // will establish the notifiers data and direct subscription // on the node. If there is also a direct subscription to the // node's focus/blur, it should not call _notify because the // direct subscription from the delegate sub(s) exists, which // will call _notify. So this avoids _notify being called // twice, unnecessarily. defer = true; } if (!notifiers[yuid]) { notifiers[yuid] = []; } notifiers[yuid].push(notifier); if (!defer) { this._notify(e); } }, _notify: function (e, container) { var currentTarget = e.currentTarget, notifierData = currentTarget.getData(nodeDataKey), axisNodes = currentTarget.ancestors(), doc = currentTarget.get('ownerDocument'), delegates = [], // Used to escape loops when there are no more // notifiers to consider count = notifierData ? Y.Object.keys(notifierData).length : 0, target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret; // clear the notifications list (mainly for delegation) currentTarget.clearData(nodeDataKey); // Order the delegate subs by their placement in the parent axis axisNodes.push(currentTarget); // document.get('ownerDocument') returns null // which we'll use to prevent having duplicate Nodes in the list if (doc) { axisNodes.unshift(doc); } // ancestors() returns the Nodes from top to bottom axisNodes._nodes.reverse(); if (count) { // Store the count for step 2 tmp = count; axisNodes.some(function (node) { var yuid = Y.stamp(node), notifiers = notifierData[yuid], i, len; if (notifiers) { count--; for (i = 0, len = notifiers.length; i < len; ++i) { if (notifiers[i].handle.sub.filter) { delegates.push(notifiers[i]); } } } return !count; }); count = tmp; } // Walk up the parent axis, notifying direct subscriptions and // testing delegate filters. while (count && (target = axisNodes.shift())) { yuid = Y.stamp(target); notifiers = notifierData[yuid]; if (notifiers) { for (i = 0, len = notifiers.length; i < len; ++i) { notifier = notifiers[i]; sub = notifier.handle.sub; match = true; e.currentTarget = target; if (sub.filter) { match = sub.filter.apply(target, [target, e].concat(sub.args || [])); // No longer necessary to test against this // delegate subscription for the nodes along // the parent axis. delegates.splice( arrayIndex(delegates, notifier), 1); } if (match) { // undefined for direct subs e.container = notifier.container; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } delete notifiers[yuid]; count--; } if (e.stopped !== 2) { // delegates come after subs targeting this specific node // because they would not normally report until they'd // bubbled to the container node. for (i = 0, len = delegates.length; i < len; ++i) { notifier = delegates[i]; sub = notifier.handle.sub; if (sub.filter.apply(target, [target, e].concat(sub.args || []))) { e.container = notifier.container; e.currentTarget = target; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } } if (e.stopped) { break; } } }, on: function (node, sub, notifier) { sub.handle = this._attach(node._node, notifier); }, detach: function (node, sub) { sub.handle.detach(); }, delegate: function (node, sub, notifier, filter) { if (isString(filter)) { sub.filter = function (target) { return Y.Selector.test(target._node, filter, node === target ? null : node._node); }; } sub.handle = this._attach(node._node, notifier, true); }, detachDelegate: function (node, sub) { sub.handle.detach(); } }, true); } // For IE, we need to defer to focusin rather than focus because // `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate, // el.onfocusin, doSomething, then el.onfocus. All others support capture // phase focus, which executes before doSomething. To guarantee consistent // behavior for this use case, IE's direct subscriptions are made against // focusin so subscribers will be notified before js following el.focus() is // executed. if (useActivate) { // name capture phase direct subscription define("focus", "beforeactivate", "focusin"); define("blur", "beforedeactivate", "focusout"); } else { define("focus", "focus", "focus"); define("blur", "blur", "blur"); } }, '@VERSION@', {"requires": ["event-synthetic"]});
src/public_src/index.js
fedevela/projectccs
'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var io = require('socket.io-client'); var feathers = require('feathers/client'); var hooks = require('feathers-hooks'); var socketio = require('feathers-socketio/client'); var localstorage = require('feathers-localstorage'); var authentication = require('feathers-authentication/client'); var moment = require('moment'); var FlipMove = require('react-flip-move'); var PageHeader = require('react-bootstrap/lib/PageHeader'); var Tab = require('react-bootstrap/lib/Tab'); var Tabs = require('react-bootstrap/lib/Tabs'); var ListGroup = require('react-bootstrap/lib/ListGroup'); var FormGroup = require('react-bootstrap/lib/FormGroup'); var FormControl = require('react-bootstrap/lib/FormControl'); var ListGroupItem = require('react-bootstrap/lib/ListGroupItem'); var Button = require('react-bootstrap/lib/Button'); var ButtonGroup = require('react-bootstrap/lib/ButtonGroup'); //var Glyphicon = require('react-bootstrap/lib/Glyphicon'); var ControlLabel = require('react-bootstrap/lib/ControlLabel'); var Grid = require('react-bootstrap/lib/Grid'); var Row = require('react-bootstrap/lib/Row'); var Col = require('react-bootstrap/lib/Col'); //var BarCharts = require('BarChart'); var Chart = require('react-google-charts').Chart; const socket = io('https://cardif-workspace-fedevela.c9users.io/'); const app = feathers().configure(socketio(socket)).configure(hooks()).configure(authentication({storage: window.localStorage})); // A placeholder image if the user does not have one const PLACEHOLDER = 'https://placeimg.com/60/60/people'; // An anonymous user if the servicioRegistroVentas does not have that information const dummyUser = { avatar: PLACEHOLDER, email: 'Anonymous' }; //data= {[ { value: 30, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 10, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 25, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 40, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 2, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 5, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 33, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 13, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 49, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 32, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2},{ value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2}, { value: 0, high: 50, low:0, unitHeight: 3, barItemTop: 0, barInterval: 2} ]}; const FormMessages = React.createClass({ getInitialState() { return {value: ''}; }, // getValidationState() { // const length = this.state.value.length; // if (length > 10) // return 'success'; // else if (length > 5) // return 'warning'; // else if (length > 0) // return 'error'; // } // , handleChange(e) { this.setState({value: e.target.value}); }, sendMessage(ev) { // Get the messages service const messageService = app.service('messages'); // Create a new message with the text from the input field messageService.create({text: this.state.value}).then(() => this.setState({value: ''})); ev.preventDefault(); }, render() { return ( <form onSubmit={this.sendMessage}> {/* <FormGroup controlId="formMessages" validationState={this.getValidationState()}> */} <FormGroup controlId="formMessages"> <ControlLabel>Mensaje</ControlLabel> <Grid> <Row> <Col xs={8} md={4}> <FormControl type="text" value={this.state.value} placeholder="Escribe tu mensaje..." onChange={this.handleChange}/> </Col> <Col xs={2} md={1}> <Button bsStyle="primary" type="submit">Enviar</Button> </Col> </Row> </Grid> {/* <HelpBlock>Validation is based on string length.</HelpBlock> */} </FormGroup> </form> ); } }); const LogoutButton = React.createClass({ logout() { app.logout().then(() => window.location.href = '/login.html'); }, render() { return <Button onClick={this.logout} bsSize="small" bsStyle="danger" id="LogoutButtonID"> {/* @TODO hacer funcionar los Glyphicon <Glyphicon glyph="close-circle" /> */} Cerrar </Button>; } }); const ChatApp = React.createClass({ getInitialState() { return { users: [], messages: [], usuario: this.props.usuario, BarChartData: { chartType: 'BarChart', div_id: 'BarChart', options: { title: 'Registro de ventas', bar: { groupWidth: '100%' }, legend: { position: 'none' }, hAxis: { viewWindow: { min: 0 }, format: '0' } } }, GaugeChartData: { chartType: 'Gauge', div_id: 'GaugeChart' } } }, componentDidUpdate: function() { // const node = this.getDOMNode().querySelector('.chat'); // node.scrollTop = node.scrollHeight - node.clientHeight; }, componentDidMount() { const userService = app.service('users'); const messageService = app.service('messages'); const servicioRegistroVentas = app.service('servicioRegistroVentas'); // Find all users initially userService.find({ query: { $sort: { numVentasRegistradas: -1 }, $limit: -1 } }).then(page => { // debugger; this.setState({users: page.data}); }); // Listen to new users so we can show them in real-time userService.on('created', () => userService.find({ query: { $sort: { numVentasRegistradas: -1 }, $limit: -1 } }).then(page => { this.setState({users: page.data}); for (var aUser of page.data) { if (aUser._id === this.state.usuario._id) { this.setState({usuario: aUser}); // debugger; break; } } })); // Find the last 10 messages messageService.find({ query: { $sort: { createdAt: -1 }, $limit: this.props.limit || 25 } }).then(page => this.setState({messages: page.data.reverse()})); // Listen to newly created messages // messageService.on('created', message => this.setState({messages: this.state.messages.concat(message)})); messageService.on('created', () => messageService.find({ query: { $sort: { createdAt: -1 }, $limit: this.props.limit || 25 } }).then(page => this.setState({messages: page.data.reverse()}))); // Listen to newly created registroVentas servicioRegistroVentas.on('created', () => userService.find({ query: { $sort: { numVentasRegistradas: -1 }, $limit: -1 } }).then(page => { // debugger; this.setState({users: page.data}); for (var aUser of page.data) { if (aUser._id === this.state.usuario._id) { this.setState({usuario: aUser}); break; } } })); }, registrarVenta(ev) { // debugger; app.service('servicioRegistroVentas').create({registroVentaTipo: "crear"}); ev.preventDefault(); }, cancelarVenta(ev) { app.service('servicioRegistroVentas').create({registroVentaTipo: "cancelar"}); ev.preventDefault(); }, render() { // debugger; var indicePosicion = 0; return <div id="app"> <LogoutButton/> <PageHeader> Cardif CIMA </PageHeader> {this.state.usuario.email} : {this.state.usuario.numVentasRegistradas} Ventas <Tabs defaultActiveKey={2} id='mainTabs'> <Tab eventKey={1} title="Registro"> <div> <header> <ButtonGroup> <Button bsStyle="danger" onClick={this.cancelarVenta}> - (Cancelar Venta) </Button> <Button bsStyle="success" onClick={this.registrarVenta}> + (Registrar Venta) </Button> </ButtonGroup> </header> <img src="img/gauge.png"/> {/* <Chart chartType={this.state.GaugeChartData.chartType} data={[ [ 'Label', 'Value' ], [ 'Memory', 80 ], [ 'CPU', 55 ], ['Network', 68] ]} options={this.state.GaugeChartData.options} graph_id={this.state.GaugeChartData.div_id}/> */} <Chart chartType={this.state.BarChartData.chartType} data={[ [ 'Ventas', 'Cantidad', { role: 'style' } ], [ 'Registradas', this.state.usuario.numVentasRegistradas, 'green' ], ['Canceladas', this.state.usuario.numVentasCanceladas, '#ff1f00'] ]} options={this.state.BarChartData.options} graph_id={this.state.BarChartData.div_id}/> </div> </Tab> <Tab eventKey={2} title="Ranking"> <div> <header> <ButtonGroup> <Button bsStyle="danger" onClick={this.cancelarVenta}> - (Cancelar Venta) </Button> <Button bsStyle="success" onClick={this.registrarVenta}> + (Registrar Venta) </Button> </ButtonGroup> </header> <main className="chat flex flex-column flex-1 clear"> <FlipMove duration={1000}> {this.state.users.map(user => { var theTruncatedEmail = user.email.replace(/@.+/i, ""); var theProfileImg = user.profileImg || PLACEHOLDER; indicePosicion++; return <div className="message flex flex-row rankingTable" key={user._id}> <div className="indicePosicionClass">{indicePosicion}.</div> <img src={theProfileImg} alt={theTruncatedEmail} className="avatar"/> <div className="message-wrapper"> <p className="message-header"> <span className="username font-600">{theTruncatedEmail}</span> </p> <p className="message-content font-300"> {user.numVentasRegistradas} Ventas </p> </div> </div>; })} </FlipMove> </main> </div> </Tab> <Tab eventKey={3} title="Chat"> <ButtonGroup> <Button> General </Button> <Button> Tips de Ventas </Button> <Button> Campañas </Button> <Button> Sucursal </Button> </ButtonGroup> <main className="chat flex flex-column flex-1 clear"> <FlipMove> {this.state.messages.map(message => { var theUser = message.sentBy || dummyUser; var theProfileImg = theUser.profileImg || PLACEHOLDER; var theTruncatedEmail = theUser.email.replace(/@.+/i, ""); // debugger; return <div className="message flex flex-row" key={message._id}> <img src={theProfileImg} alt={theTruncatedEmail} className="avatar"/> <div className="message-wrapper"> <p className="message-header"> <span className="username font-600">{theTruncatedEmail}</span> <span className="sent-date font-300 messageDateClass"> {moment(message.createdAt).format('MMM Do, hh:mm:ss')} </span> </p> <p className="message-content font-300"> {message.text} </p> </div> </div>; })} </FlipMove> </main> <footer> <FormMessages/> </footer> </Tab> <Tab eventKey={4} title="Contenidos"> Contenidos: <ListGroup componentClass="ul"> <ListGroupItem> <a href="https://www.bnpparibascardif.com/documents/583427/809429/Pr%C3%A9sentation+investisseurs/7aacd782-5876-48c6-96c3-8ea95f2cd27c"> <img src="img/Mimetypes-application-pdf-icon.png"/> Documento PDF AAA </a> </ListGroupItem> <ListGroupItem> <a href="https://www.youtube.com/watch?v=Egj6hvtU_VE"> <img src="img/Web-Youtube-alt-2-Metro-icon.png"/> Video YouTube AAA </a> </ListGroupItem> <ListGroupItem> <a href="https://www.bnpparibascardif.com/documents/583427/809429/Pr%C3%A9sentation+investisseurs/7aacd782-5876-48c6-96c3-8ea95f2cd27c"> <img src="img/Mimetypes-application-pdf-icon.png"/> Documento PDF BBB </a> </ListGroupItem> <ListGroupItem> <a href="https://www.bnpparibascardif.com/documents/583427/809429/Pr%C3%A9sentation+investisseurs/7aacd782-5876-48c6-96c3-8ea95f2cd27c"> <img src="img/Mimetypes-application-pdf-icon.png"/> Documento PDF CCC </a> </ListGroupItem> <ListGroupItem> <a href="https://www.youtube.com/watch?v=Egj6hvtU_VE"> <img src="img/Web-Youtube-alt-2-Metro-icon.png"/> Video YouTube BBB </a> </ListGroupItem> </ListGroup> </Tab> </Tabs> </div>; } }); app.authenticate().then((authResponse) => { // debugger; ReactDOM.render( <ChatApp usuario={authResponse.data}/>, document.querySelector('#mainAppContainer')); //}).catch(error => { // if (error.code === 401) { // window.location.href = '/login.html' // } // console.log(error.stack); // console.error(error); });
src/__tests__/DropdownToggle.spec.js
reactstrap/reactstrap
import React from 'react'; import { mount } from 'enzyme'; import { DropdownToggle } from '../'; import { DropdownContext } from '../DropdownContext'; describe('DropdownToggle', () => { const setReferenceNode = jest.fn(); let isOpen; let inNavbar; let toggle; beforeEach(() => { isOpen = false; inNavbar = false; setReferenceNode.mockClear(); toggle = () => { isOpen = !isOpen; }; }); it('should wrap text', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle>Ello world</DropdownToggle> </DropdownContext.Provider> ); expect(wrapper.text()).toBe('Ello world'); }); it('should add default visually-hidden content', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle /> </DropdownContext.Provider> ); expect(wrapper.text()).toBe('Toggle Dropdown'); expect(wrapper.find('.visually-hidden').hostNodes().length).toBe(1); }); it('should add default visually-hidden content', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle aria-label="Dropup Toggle" /> </DropdownContext.Provider> ); expect(wrapper.text()).toBe('Dropup Toggle'); expect(wrapper.find('.visually-hidden').hostNodes().length).toBe(1); }); it('should render elements', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle>Click Me</DropdownToggle> </DropdownContext.Provider> ); expect(wrapper.text()).toBe('Click Me'); expect(wrapper.find('button').hostNodes().length).toBe(1); }); it('should render a caret', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle caret>Ello world</DropdownToggle> </DropdownContext.Provider> ); expect(wrapper.childAt(0).childAt(0).hasClass('dropdown-toggle')).toBe(true); }); describe('color', () => { it('should render the dropdown as a BUTTON element with default color secondary', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle /> </DropdownContext.Provider> ); expect(wrapper.find('button').hostNodes().length).toBe(1); expect(wrapper.find('button').hostNodes().hasClass('btn-secondary')).toBe(true); }); it('should render the dropdown as a BUTTON element with explicit color success', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle color="success" /> </DropdownContext.Provider> ); expect(wrapper.find('button').hostNodes().length).toBe(1); expect(wrapper.find('button').hostNodes().hasClass('btn-success')).toBe(true); }); it('should render the dropdown as an A element with no color attribute', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle tag="a" /> </DropdownContext.Provider> ); expect(wrapper.find('a').hostNodes().length).toBe(1); expect(wrapper.find('a[color]').hostNodes().length).toBe(0); }); it('should render the dropdown as a DIV element with no color attribute', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle tag="div" color="success" /> </DropdownContext.Provider> ); expect(wrapper.find('div').hostNodes().length).toBe(1); expect(wrapper.find('div[color]').hostNodes().length).toBe(0); }); }); it('should render a split', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle split>Ello world</DropdownToggle> </DropdownContext.Provider> ); expect(wrapper.childAt(0).childAt(0).hasClass('dropdown-toggle-split')).toBe(true); }); describe('onClick', () => { it('should call props.onClick if it exists', () => { const onClick = jest.fn(); const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle onClick={() => onClick()}>Ello world</DropdownToggle> </DropdownContext.Provider> ); const instance = wrapper.instance(); instance.onClick({}); expect(onClick).toHaveBeenCalled(); }); it('should call context.toggle when present ', () => { toggle = jest.fn(); const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle>Ello world</DropdownToggle> </DropdownContext.Provider> ); const instance = wrapper.instance(); instance.onClick({ preventDefault: () => { } }); expect(toggle).toHaveBeenCalled(); }); }); describe('disabled', () => { it('should preventDefault when disabled', () => { const e = { preventDefault: jest.fn() }; const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle disabled>Ello world</DropdownToggle> </DropdownContext.Provider> ); const instance = wrapper.instance(); instance.onClick(e); expect(e.preventDefault).toHaveBeenCalled(); }); }); describe('nav', () => { it('should add .nav-link class', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle nav>Ello world</DropdownToggle> </DropdownContext.Provider> ); expect(wrapper.find('a').hostNodes().length).toBe(1); expect(wrapper.find('.nav-link').hostNodes().length).toBe(1); }); it('should not set the tag prop when the tag is defined', () => { const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle nav>Ello world</DropdownToggle> </DropdownContext.Provider> ); expect(wrapper.prop('tag')).toBe(undefined); }); it('should preventDefault', () => { const e = { preventDefault: jest.fn() }; const wrapper = mount( <DropdownContext.Provider value={{ isOpen, inNavbar, toggle }}> <DropdownToggle nav>Ello world</DropdownToggle> </DropdownContext.Provider> ); const instance = wrapper.instance(); instance.onClick(e); expect(e.preventDefault).toHaveBeenCalled(); }); }); });
src/components/StyledCheckbox.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { themeGet, fontSize } from 'styled-system'; import { Flex } from '@rebass/grid'; const IconCheckmark = () => { return ( <svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg"> <path id="checkmark-tiny" d="M3.30913 8C3.0158 8 2.73358 7.88442 2.52358 7.67438L0.32583 5.47599C-0.10861 5.04257 -0.10861 4.34021 0.32583 3.90569C0.760269 3.47116 1.46248 3.47116 1.89692 3.90569L3.16913 5.17835L5.98574 0.462633C6.34352 -0.0341285 7.03573 -0.149706 7.53683 0.20814C8.03572 0.565985 8.14905 1.26056 7.79128 1.75843L4.21134 7.53769C4.01245 7.81663 3.68357 8 3.30913 8Z" /> </svg> ); }; const CheckboxContainer = styled(Flex)` ${fontSize} height: ${props => props.size}; align-items: center; /* Hide the default checkbox */ input { position: absolute; opacity: 0; height: 0; width: 0; } label { cursor: pointer; margin: 0; margin-left: 1.5em; color: black; z-index: 9; font-weight: normal; } /* Show our custom checkbox */ .custom-checkbox { display: flex; justify-content: center; align-items: center; position: absolute; cursor: pointer; height: ${props => props.size}; width: ${props => props.size}; border: 1px solid #dcdee0; border-radius: 4px; background-color: white; transition: background-color 0.2s; svg { opacity: 0; height: 0.572em; width: 0.572em; fill: white; } } /* Hover label / checkbox - only for pointer devices (ignored on touch devices) */ @media (hover:hover) { &:hover input:not(:disabled):not(:checked) ~ .custom-checkbox { background: ${themeGet('colors.primary.400')}; border-color: ${themeGet('colors.primary.400')}; svg { opacity: 1; } } } /* Checked */ input:checked ~ .custom-checkbox { background: ${themeGet('colors.primary.500')}; border-color: ${themeGet('colors.primary.500')}; svg { opacity: 1; } } /* Focused */ input:focus ~ .custom-checkbox { background: ${themeGet('colors.primary.400')}; border-color: ${themeGet('colors.primary.400')}; } /* Disabled */ input:disabled { & ~ .custom-checkbox { background: #f7f8fa; border: 1px solid #e8e9eb; cursor: not-allowed; svg { fill: ${themeGet('colors.primary.200')}; } } & ~ label { cursor: not-allowed; } } `; class StyledCheckbox extends React.Component { constructor(props) { super(props); this.state = { checked: props.defaultChecked }; } onChange(newValue) { const { name, checked, onChange, disabled } = this.props; if (disabled) { return false; } if (checked === undefined) { this.setState({ checked: newValue }); } if (onChange) { onChange({ name, checked: newValue, type: 'checkbox' }); } } render() { const { name, checked, label, disabled, size, inputId } = this.props; const realChecked = checked === undefined ? this.state.checked : checked; return ( <CheckboxContainer onClick={() => this.onChange(!realChecked)} fontSize={size} size={size}> <input id={inputId} name={name} type="checkbox" checked={realChecked} disabled={disabled} readOnly /> <span className="custom-checkbox"> <IconCheckmark /> </span> {label && <label>{label}</label>} </CheckboxContainer> ); } } StyledCheckbox.defaultProps = { size: '14px', defaultChecked: false, }; StyledCheckbox.propTypes = { /** The name of the input */ name: PropTypes.string.isRequired, /** Called when state change with a bool representing new state */ onChange: PropTypes.func, /** Wether the checkbox is checked. Use it to control the component. If not provided, component will maintain its own state. */ checked: PropTypes.bool, /** Wether the checkbox should be checked by default. Ignored if `checked` is provided. */ defaultChecked: PropTypes.bool, /** And optional ID for the `<input/>` */ inputId: PropTypes.string, /** Wether checkbox should be disabled */ disabled: PropTypes.bool, /** An optional label to display next to checkbox */ label: PropTypes.string, /** An optional size */ size: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.array]), }; export default StyledCheckbox;
components/ImageGrid/index.js
samuelngs/px
import React, { Component } from 'react'; import { View, Image, ScrollView, TouchableOpacity, TouchableHighlight, StyleSheet, Dimensions, InteractionManager } from 'react-native'; import { LazyloadScrollView, LazyloadView } from 'react-native-lazyload'; import Touchable from 'px/components/Touchable'; import { SharedView } from 'px/components/Navigation'; import ProgressiveTransitionImage from 'px/components/ProgressiveTransitionImage'; import offset from './offset'; const suggestColumnWidth = 200; export default class ImageGrid extends Component { static defaultProps = { id : 'image-grid', route: '', images: [ ], maxColumnWidth: 250, minColumnCount: 2, maxColumnCount: 3, columnGap: 4, showsScrollIndicator: true, radius: 0, offset: { top: 0, bottom: 0, left: 0, right: 0, }, onPress: () => { }, } static propTypes = { id: React.PropTypes.string, route: React.PropTypes.string, images: React.PropTypes.array.isRequired, maxColumnWidth: React.PropTypes.number, minColumnCount: React.PropTypes.number, maxColumnCount: React.PropTypes.number, columnGap: React.PropTypes.number, showsScrollIndicator: React.PropTypes.bool, radius: React.PropTypes.number, offset: React.PropTypes.shape({ top: React.PropTypes.number, bottom: React.PropTypes.number, left: React.PropTypes.number, right: React.PropTypes.number, }), onPress: React.PropTypes.func, } state = { dimensions: { height: Dimensions.get('window').height, width: Dimensions.get('window').width, }, dataSources: [ ], } componentWillReceiveProps({ images }) { this.initialDataSource(images); } componentLayoutUpdate(e) { InteractionManager.runAfterInteractions(() => { const { images } = this.props; const { height, width } = Dimensions.get('window'); const dimensions = { height, width, }; return this.setState({ dimensions, }, () => this.initialDataSource(images)); }); } initialDataSource(images) { const { minColumnCount, maxColumnCount, columnGap } = this.props; const { dimensions: { width }, dataSources: predataSource } = this.state; const count = Math.floor(width / suggestColumnWidth); const columns = count >= minColumnCount ? (count > maxColumnCount ? maxColumnCount : count ) : minColumnCount; const sources = [ ...Array(columns) ].map(_ => []); const heights = [ ...Array(columns) ].map(_ => 0); const avgWidth = width / columns; const dataSources = [ ...predataSource ]; for ( const [ index, value ] of images.entries() ) { const { width: imageWidth, height: imageHeight } = value; const actualHeight = avgWidth / imageWidth * imageHeight; let lheight = heights[0]; let lindex = 0; for ( const [ index, height ] of heights.entries() ) { if ( height < lheight ) { lheight = height; lindex = index; } } heights[lindex] += actualHeight; sources[lindex].push(value); } for ( let i = columns; i < dataSources.length; i++ ) { dataSources.splice(i, 1); } for ( const [ index, source ] of sources.entries() ) { dataSources[index] = source; } return this.setState({ dataSources }); } renderImage(src, i, imageWidth) { const { id, route, columnGap, radius, onPress } = this.props; const height = imageWidth / src.width * src.height; return <TouchableOpacity key={ i } style={{ width: imageWidth, height, margin: columnGap }} activeOpacity={1} focusedOpacity={1} onPress={() => onPress(src)}> <ProgressiveTransitionImage name={src.id} route={route} source={{ uri: src.urls.small }} wrapper={LazyloadView} options={{ host: id, style: { width: imageWidth, height }}} style={{ width: imageWidth, height, borderRadius: radius }} containerStyle={{ width: imageWidth, height, backgroundColor: src.color, borderRadius: radius }} /> </TouchableOpacity> } renderColumn(ds, i, columnWidth, imageWidth) { return <View key={i} style={[styles.column, { width: columnWidth }]}> { ds.map((src, i) => this.renderImage(src, i, imageWidth)) } </View> } render() { const { id, maxColumnWidth, columnGap, showsScrollIndicator, offset: preLayoutOffset } = this.props; const layoutOffset = { top: 0, bottom: 0, left: 0, right: 0, ...preLayoutOffset }; const { dimensions: { width }, dataSources } = this.state; const avgColumnWidth = width / dataSources.length; const actlColumnWidth = (avgColumnWidth > maxColumnWidth ? maxColumnWidth : avgColumnWidth) - columnGap; const actlImageWidth = actlColumnWidth - columnGap * 2; return <LazyloadScrollView name={id} style={[styles.container, { paddingTop: offset + columnGap + layoutOffset.top }]} removeClippedSubviews={true} showsHorizontalScrollIndicator={showsScrollIndicator} showsVerticalScrollIndicator={showsScrollIndicator} scrollIndicatorInsets={{ top: offset + columnGap + layoutOffset.top, bottom: columnGap + layoutOffset.bottom }} onLayout={(e) => this.componentLayoutUpdate(e)} > <View style={[ styles.wrapper, { marginRight: columnGap, marginLeft: columnGap, paddingBottom: columnGap * 2 + layoutOffset.bottom }]}> { dataSources.map((ds, i) => this.renderColumn(ds, i, actlColumnWidth, actlImageWidth)) } </View> </LazyloadScrollView> } } const styles = StyleSheet.create({ container: { flex: 1, }, wrapper: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', }, column: { flexDirection: 'column', flexWrap: 'wrap', }, });
src/documentation/LoginPage/LoginPage.stories.js
wfp/ui
import React from 'react'; import markdown from './README.mdx'; import TextInput from '../../components/TextInput'; import Button from '../../components/Button'; import Modal from '../../components/Modal'; import Link from '../../components/Link'; export default { title: 'Templates/Login', parameters: { componentSubtitle: 'Example', status: 'legacy', mdx: markdown, introText: 'Login page for legacy applications not using WFPs single sign-on', previewWidth: 'full', }, }; export const Regular = (args) => ( <Modal open hideClose modalHeading="Login" inPortal={false} modalLabel="Sample Application" primaryButtonText="Login" secondaryButtonText="Forgot password?" modalSecondaryAction={ <Button kind="secondary">Sign in with WFP SSO</Button> } modalFooter={({ primaryButtonText, secondaryButtonText }) => ( <div className="wfp--modal__buttons-container"> <Link>{secondaryButtonText}</Link> <Button>{primaryButtonText}</Button> </div> )} backgroundImage="https://password.go.wfp.org/images/MAU_20150202_WFP-Agron_Dragaj_0018.jpg"> <p className="wfp--modal-content__text wfp--form-long"> <TextInput id="emailinput" labelText="Your email adress" placeholder="[email protected]" helperText={`Enter the email adress you've used when you've registred`} /> <TextInput id="passportinput" labelText="Your password" type="password" placeholder="" helperText="" /> </p> </Modal> ); Regular.decorators = [ (Story) => ( <div style={{ position: 'relative', height: '700px', }}> <Story /> </div> ), ]; Regular.args = {};
ajax/libs/redux-form/1.0.1/redux.min.js
cdnjs/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.ReduxForm=e(require("react")):t.ReduxForm=e(t.React)}(this,function(t){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";function r(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function o(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},i=n(5),a=o(i),s=n(6),c=o(s),f=n(14),l=o(f),d=n(1),p=o(d),h=n(4),v=o(h),y=n(3),m=r(y),g=u({},p.default(u({},m,{initializeWithKey:function(t,e){return v.default(m.initialize,{key:t})(e)}}),function(t){return function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;n>o;o++)r[o-1]=arguments[o];return v.default(t,{form:e}).apply(void 0,r)}})),b=g.blur,_=g.change,O=g.initialize,T=g.initializeWithKey,w=g.reset,S=g.startAsyncValidation,x=g.stopAsyncValidation,A=g.touch,P=g.untouch;e.blur=b,e.change=_,e.connectReduxForm=l.default,e.reducer=a.default,e.initialize=O,e.initializeWithKey=T,e.reset=w,e.startAsyncValidation=S,e.stopAsyncValidation=x,e.touch=A,e.untouch=P,e.default=c.default},function(t,e){"use strict";function n(t,e){return Object.keys(t).reduce(function(n,o){var u;return r({},n,(u={},u[o]=e(t[o],o),u))},{})}e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t};e.default=n,t.exports=e.default},function(t,e){"use strict";e.__esModule=!0;var n="redux-form/BLUR";e.BLUR=n;var r="redux-form/CHANGE";e.CHANGE=r;var o="redux-form/INITIALIZE";e.INITIALIZE=o;var u="redux-form/RESET";e.RESET=u;var i="redux-form/START_ASYNC_VALIDATION";e.START_ASYNC_VALIDATION=i;var a="redux-form/START_SUBMIT";e.START_SUBMIT=a;var s="redux-form/STOP_ASYNC_VALIDATION";e.STOP_ASYNC_VALIDATION=s;var c="redux-form/STOP_SUBMIT";e.STOP_SUBMIT=c;var f="redux-form/TOUCH";e.TOUCH=f;var l="redux-form/UNTOUCH";e.UNTOUCH=l},function(t,e,n){"use strict";function r(t,e){return{type:p.BLUR,field:t,value:e}}function o(t,e){return{type:p.CHANGE,field:t,value:e}}function u(t){return{type:p.INITIALIZE,data:t}}function i(){return{type:p.RESET}}function a(){return{type:p.START_ASYNC_VALIDATION}}function s(){return{type:p.START_SUBMIT}}function c(t){return{type:p.STOP_ASYNC_VALIDATION,errors:t}}function f(){return{type:p.STOP_SUBMIT}}function l(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return{type:p.TOUCH,fields:e}}function d(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return{type:p.UNTOUCH,fields:e}}e.__esModule=!0,e.blur=r,e.change=o,e.initialize=u,e.reset=i,e.startAsyncValidation=a,e.startSubmit=s,e.stopAsyncValidation=c,e.stopSubmit=f,e.touch=l,e.untouch=d;var p=n(2)},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){return"function"==typeof t?function(){return u({},t.apply(void 0,arguments),e)}:a.default(t,function(t){return o(t,e)})}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t};e.default=o;var i=n(1),a=r(i);t.exports=e.default},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){var n={};for(var r in t)e.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function u(){var t,e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=n.form,u=n.key,i=o(n,["form","key"]);if(!r)return e;if(u){var s,c;return a({},e,(c={},c[r]=a({},e[r],(s={},s[u]=p((e[r]||{})[u],i),s)),c))}return a({},e,(t={},t[r]=p(e[r],i),t))}function i(t){return t.plugin=function(t){var e=this;return i(function(){var n=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],o=e(n,r);return a({},o,f.default(t,function(t,e){return t(o[e]||l,r)}))})},t.normalize=function(t){var e=this;return i(function(){var n=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],o=e(n,r);return a({},o,f.default(t,function(t,e){return a({},o[e],f.default(t,function(t,r){return a({},o[e][r],{value:t(o[e][r]?o[e][r].value:void 0,n[e]&&n[e][r]?n[e][r].value:void 0,d(o[e]))})}))}))})},t}e.__esModule=!0;var a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},s=n(2),c=n(1),f=r(c),l={_asyncValidating:!1,_submitting:!1};e.initialState=l;var d=function(t){return Object.keys(t).reduce(function(e,n){var r;return"_"===n[0]?e:a({},e,(r={},r[n]=t[n].value,r))},{})},p=function(){var t,e,n=arguments.length<=0||void 0===arguments[0]?l:arguments[0],r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];switch(r.type){case s.BLUR:return a({},n,(t={},t[r.field]=a({},n[r.field],{value:r.value,touched:!(!r.touch&&!(n[r.field]||{}).touched)}),t));case s.CHANGE:return a({},n,(e={},e[r.field]=a({},n[r.field],{value:r.value,touched:!(!r.touch&&!(n[r.field]||{}).touched),asyncError:null}),e));case s.INITIALIZE:return a({},f.default(r.data,function(t){return{initial:t,value:t}}),{_asyncValidating:!1,_submitting:!1});case s.RESET:return a({},f.default(n,function(t,e){return"_"===e[0]?t:{initial:t.initial,value:t.initial}}),{_asyncValidating:!1,_submitting:!1});case s.START_ASYNC_VALIDATION:return a({},n,{_asyncValidating:!0});case s.START_SUBMIT:return a({},n,{_submitting:!0});case s.STOP_ASYNC_VALIDATION:return a({},n,f.default(r.errors,function(t,e){return a({},n[e],{asyncError:t})}),{_asyncValidating:!1});case s.STOP_SUBMIT:return a({},n,{_submitting:!1});case s.TOUCH:return a({},n,r.fields.reduce(function(t,e){var r;return a({},t,(r={},r[e]=a({},n[e],{touched:!0}),r))},{}));case s.UNTOUCH:return a({},n,r.fields.reduce(function(t,e){var r;return a({},t,(r={},r[e]=a({},n[e],{touched:!1}),r))},{}));default:return n}};e.default=i(u)},function(t,e,n){"use strict";function r(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function o(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){var n={};for(var r in t)e.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e,n){if(t&&t[e]){if(!n)return t[e];if(t[e][n])return t[e][n]}return S.initialState}function c(t,e){if(void 0!==t||!e)return t;var n=e.target,r=n.type,o=n.value,u=n.checked;return"checkbox"===r?u:o}function f(t){return function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;n>o;o++)r[o-1]=arguments[o];return e&&e.preventDefault?(e.preventDefault(),e.stopPropagation(),t.apply(void 0,r)):t.apply(void 0,[e].concat(r))}}function l(t){var e=p({validate:function(){return{valid:!0}},touchOnBlur:!0,touchOnChange:!1,asyncValidate:null,asyncBlurFields:[]},t),n=e.form,r=e.fields,o=e.validate,l=e.touchOnBlur,y=e.touchOnChange,g=e.asyncValidate,_=e.asyncBlurFields;if(!n)throw new Error("No form name passed to redux-form");if(!r||!r.length)throw new Error("No fields passed to redux-form");return function(t){return function(e){function T(){i(this,T),e.apply(this,arguments)}return a(T,e),T.prototype.render=function(){function e(){b(N(h));var t=g(P);if(!t||"function"!=typeof t.then)throw new Error("asyncValidate function passed to reduxForm must return a promise!");return t.then(function(t){return b(k(t)),!!t.valid},function(t){throw b(k({})),new Error("redux-form: Asynchronous validation failed: "+t)})}var n=this,i=this.props,a=i.formName,d=i.form,h=i.formKey,b=i.dispatch,T=u(i,["formName","form","formKey","dispatch"]),S=s(d,a,h),x=!0,A=!0,P=r.reduce(function(t,e){var n;return p({},t,(n={},n[e]=S[e]?S[e].value:void 0,n))},{}),j=h?w.default(m,{form:a,key:h}):w.default(m,{form:a}),I=j.blur,M=j.change,E=j.initialize,C=j.reset,N=j.startAsyncValidation,R=j.startSubmit,k=j.stopAsyncValidation,V=j.stopSubmit,U=j.touch,D=j.untouch,B=function(t,n){return function(r){var u=c(n,r),i=w.default(I,{touch:l});if(b(i(t,u)),g&&~_.indexOf(t)){var a,s=o(p({},P,(a={},a[t]=u,a)))[t];s||e()}}},L=function(t,e){return function(n){var r=w.default(M,{touch:y});b(r(t,c(e,n)))}},z=function(t){var o=function(t){return function(n){n&&n.preventDefault&&(n.preventDefault(),n.stopPropagation());var o=function(){var e=t(P);if(e&&"function"==typeof e.then){var n=function(t){return b(V()),t};b(R()),e.then(n,n)}};return b(U.apply(void 0,r)),x?g?e().then(function(t){return x&&t?o(P):void 0}):o(P):void 0}};if("function"==typeof t)return o(t);var u=n.props.onSubmit;if(!u)throw new Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");o(u)(t)},H=o(P),F=r.reduce(function(t,e){var n,r=S[e]||{},o=O.default(r.value,r.initial),u=H[e]||r.asyncError;return u&&(x=!1),o||(A=!1),p({},t,(n={},n[e]={checked:"boolean"==typeof r.value?r.value:void 0,dirty:!o,error:u,handleBlur:B(e),handleChange:L(e),invalid:!!u,name:e,onBlur:B(e),onChange:L(e),pristine:o,touched:r.touched,valid:!u,value:r.value},n))},{});return v.default.createElement(t,p({asyncValidating:S._asyncValidating,dirty:!A,fields:F,formKey:h,invalid:!x,pristine:A,submitting:S._submitting,valid:x,values:P,asyncValidate:f(e),handleBlur:f(B),handleChange:f(L),handleSubmit:f(z),initializeForm:f(function(t){return b(E(t))}),resetForm:f(function(){return b(C())}),touch:f(function(){return b(U.apply(void 0,arguments))}),touchAll:f(function(){return b(U.apply(void 0,r))}),untouch:f(function(){return b(D.apply(void 0,arguments))}),untouchAll:f(function(){return b(untouchAll.apply(void 0,r))}),dispatch:b},T))},d(T,null,[{key:"displayName",value:"ReduxForm("+b.default(t)+")",enumerable:!0},{key:"DecoratedComponent",value:t,enumerable:!0},{key:"propTypes",value:{formName:h.PropTypes.string,formKey:h.PropTypes.string,form:h.PropTypes.object,onSubmit:h.PropTypes.func,dispatch:h.PropTypes.func.isRequired},enumerable:!0},{key:"defaultProps",value:{formName:n},enumerable:!0}]),T}(h.Component)}}e.__esModule=!0;var d=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),p=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t};e.default=l;var h=n(13),v=o(h),y=n(3),m=r(y),g=n(15),b=o(g),_=n(16),O=o(_),T=n(4),w=o(T),S=n(5);t.exports=e.default},function(t,e){"use strict";function n(t){return t.shape({subscribe:t.func.isRequired,dispatch:t.func.isRequired,getState:t.func.isRequired})}e.__esModule=!0,e.default=n,t.exports=e.default},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){function n(){return f}function r(t){return l.push(t),function(){var e=l.indexOf(t);l.splice(e,1)}}function o(t){if(!i.default(t))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if(d)throw new Error("Reducers may not dispatch actions.");try{d=!0,f=c(f,t)}finally{d=!1}return l.slice().forEach(function(t){return t()}),t}function u(){return c}function s(t){c=t,o({type:a.INIT})}if("function"!=typeof t)throw new Error("Expected the reducer to be a function.");var c=t,f=e,l=[],d=!1;return o({type:a.INIT}),{dispatch:o,subscribe:r,getState:n,getReducer:u,replaceReducer:s}}e.__esModule=!0,e.default=o;var u=n(10),i=r(u),a={INIT:"@@redux/INIT"};e.ActionTypes=a},function(t,e){"use strict";function n(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return e.reduceRight(function(t,e){return e(t)})}e.__esModule=!0,e.default=n,t.exports=e.default},function(t,e){"use strict";function n(t){if(!t||"object"!=typeof t)return!1;var e="function"==typeof t.constructor?Object.getPrototypeOf(t):Object.prototype;if(null===e)return!0;var n=e.constructor;return"function"==typeof n&&n instanceof n&&r(n)===r(Object)}e.__esModule=!0,e.default=n;var r=function(t){return Function.prototype.toString.call(t)};t.exports=e.default},function(t,e){"use strict";function n(t,e){return Object.keys(t).reduce(function(n,r){return n[r]=e(t[r],r),n},{})}e.__esModule=!0,e.default=n,t.exports=e.default},function(t,e){function n(){c=!1,i.length?s=i.concat(s):f=-1,s.length&&r()}function r(){if(!c){var t=setTimeout(n);c=!0;for(var e=s.length;e;){for(i=s,s=[];++f<e;)i[f].run();f=-1,e=s.length}i=null,c=!1,clearTimeout(t)}}function o(t,e){this.fun=t,this.array=e}function u(){}var i,a=t.exports={},s=[],c=!1,f=-1;a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];s.push(new o(t,e)),1!==s.length||c||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=u,a.addListener=u,a.once=u,a.off=u,a.removeListener=u,a.removeAllListeners=u,a.emit=u,a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(e,n){e.exports=t},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return function(t){return e.reduce(function(t,e){return e(t)},t)}}function u(){return o(s.default.apply(void 0,arguments),c)}e.__esModule=!0,e.default=u;var i=n(20),a=n(6),s=r(a),c=i.connect(function(t){return{form:t.form}});t.exports=e.default},function(t,e){"use strict";function n(t){return t.displayName||t.name||"Component"}e.__esModule=!0,e.default=n,t.exports=e.default},function(t,e){"use strict";function n(t,e){if(t===e)return!0;if(t&&"object"==typeof t){if(!e||"object"!=typeof e)return!1;for(var r=Object.keys(e),o=0;o<r.length;o++){var u=r[o];if(!n(t[u],e[u]))return!1}}else if(t||e)return t===e;return!0}e.__esModule=!0,e.default=n,t.exports=e.default},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t){var e=i.default(t),n=s.default(t);return{Provider:e,connect:n}}e.__esModule=!0,e.default=o;var u=n(19),i=r(u),a=n(18),s=r(a);t.exports=e.default},function(t,e,n){(function(r){"use strict";function o(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){return t.displayName||t.name||"Component"}function s(t){var e=t.Component,n=t.PropTypes,o=d.default(n);return function(n,s,l){function d(t,e){var n=t.getState(),r=P?b(n,e):b(n);return _.default(y.default(r),"`mapStateToProps` must return an object. Instead received %s.",r),r}function p(t,e){var n=t.dispatch,r=j?x(n,e):x(n);return _.default(y.default(r),"`mapDispatchToProps` must return an object. Instead received %s.",r),r}function v(t,e,n){var r=A(t,e,n);return _.default(y.default(r),"`mergeProps` must return an object. Instead received %s.",r),r}var m=Boolean(n),b=n||O,x=y.default(s)?g.default(s):s||T,A=l||w,P=b.length>1,j=x.length>1,I=S++;return function(n){var s=function(e){function r(t,n){u(this,r),e.call(this,t,n),this.version=I,this.store=t.store||n.store,_.default(this.store,'Could not find "store" in either the context or '+('props of "'+this.constructor.displayName+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+this.constructor.displayName+'".')),this.stateProps=d(this.store,t),this.dispatchProps=p(this.store,t),this.state={props:this.computeNextState()}}return i(r,e),r.prototype.shouldComponentUpdate=function(t,e){return!h.default(this.state.props,e.props)},c(r,null,[{key:"displayName",value:"Connect("+a(n)+")",enumerable:!0},{key:"WrappedComponent",value:n,enumerable:!0},{key:"contextTypes",value:{store:o},enumerable:!0},{key:"propTypes",value:{store:o},enumerable:!0}]),r.prototype.computeNextState=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0];return v(this.stateProps,this.dispatchProps,t)},r.prototype.updateStateProps=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=d(this.store,t);return h.default(e,this.stateProps)?!1:(this.stateProps=e,!0)},r.prototype.updateDispatchProps=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=p(this.store,t);return h.default(e,this.dispatchProps)?!1:(this.dispatchProps=e,!0)},r.prototype.updateState=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=this.computeNextState(t);h.default(e,this.state.props)||this.setState({props:e})},r.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},r.prototype.trySubscribe=function(){m&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},r.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},r.prototype.componentDidMount=function(){this.trySubscribe()},r.prototype.componentWillReceiveProps=function(t){h.default(t,this.props)||(P&&this.updateStateProps(t),j&&this.updateDispatchProps(t),this.updateState(t))},r.prototype.componentWillUnmount=function(){this.tryUnsubscribe()},r.prototype.handleChange=function(){this.updateStateProps()&&this.updateState()},r.prototype.getWrappedInstance=function(){return this.refs.wrappedInstance},r.prototype.render=function(){return t.createElement(n,f({ref:"wrappedInstance"},this.state.props))},r}(e);return"undefined"!=typeof r&&"undefined"!=typeof r.env,"undefined"!=typeof __DEV__&&__DEV__&&(s.prototype.componentWillUpdate=function(){this.version!==I&&(this.version=I,this.trySubscribe(),this.updateStateProps(),this.updateDispatchProps(),this.updateState())}),s}}}e.__esModule=!0;var c=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),f=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t};e.default=s;var l=n(7),d=o(l),p=n(22),h=o(p),v=n(21),y=o(v),m=n(23),g=o(m),b=n(24),_=o(b),O=function(){return{}},T=function(t){return{dispatch:t}},w=function(t,e,n){return f({},n,t,e)},S=0;t.exports=e.default}).call(e,n(12))},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function i(t){var e=t.version;if("string"!=typeof e)return!1;var n=e.split("."),r=parseInt(n[0],10),o=parseInt(n[1],10);return 0===r&&13===o}function a(t){function e(){p||d||(p=!0,console.error("With React 0.14 and later versions, you no longer need to wrap <Provider> child into a function."))}function n(){!p&&d&&(p=!0,console.error("With React 0.13, you need to wrap <Provider> child into a function. This restriction will be removed with React 0.14."))}var r=t.Component,a=t.PropTypes,c=t.Children,l=f.default(a),d=i(t),p=!1;return function(t){function r(e,n){o(this,r),t.call(this,e,n),this.state={store:e.store}}return u(r,t),r.prototype.getChildContext=function(){return{store:this.state.store}},s(r,null,[{key:"childContextTypes",value:{store:l.isRequired},enumerable:!0},{key:"propTypes",value:{store:l.isRequired,children:(d?a.func:a.element).isRequired},enumerable:!0}]),r.prototype.componentWillReceiveProps=function(t){var e=this.state.store,n=t.store;if(e!==n){var r=n.getReducer();e.replaceReducer(r)}},r.prototype.render=function(){var t=this.props.children;return"function"==typeof t?(e(),t=t()):n(),c.only(t)},r}(r)}e.__esModule=!0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}();e.default=a;var c=n(7),f=r(c);t.exports=e.default},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var o=n(13),u=r(o),i=n(17),a=r(i),s=a.default(u.default),c=s.Provider,f=s.connect;e.Provider=c,e.connect=f},function(t,e){"use strict";function n(t){if(!t||"object"!=typeof t)return!1;var e="function"==typeof t.constructor?Object.getPrototypeOf(t):Object.prototype;if(null===e)return!0;var n=e.constructor;return"function"==typeof n&&n instanceof n&&r(n)===r(Object)}e.__esModule=!0,e.default=n;var r=function(t){return Function.prototype.toString.call(t)};t.exports=e.default},function(t,e){"use strict";function n(t,e){if(t===e)return!0;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty,u=0;u<n.length;u++)if(!o.call(e,n[u])||t[n[u]]!==e[n[u]])return!1;return!0}e.__esModule=!0,e.default=n,t.exports=e.default},function(t,e,n){"use strict";function r(t){return function(e){return o.bindActionCreators(t,e)}}e.__esModule=!0,e.default=r;var o=n(25);t.exports=e.default},function(t,e,n){"use strict";var r=function(t,e,n,r,o,u,i,a){if(!t){var s;if(void 0===e)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,u,i,a],f=0;s=new Error("Invariant Violation: "+e.replace(/%s/g,function(){return c[f++]}))}throw s.framesToPop=1,s}};t.exports=r},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var o=n(8),u=r(o),i=n(28),a=r(i),s=n(27),c=r(s),f=n(26),l=r(f),d=n(9),p=r(d);e.createStore=u.default,e.combineReducers=a.default,e.bindActionCreators=c.default,e.applyMiddleware=l.default,e.compose=p.default},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(){for(var t=arguments.length,e=Array(t),n=0;t>n;n++)e[n]=arguments[n];return function(t){return function(n,r){var o=t(n,r),i=o.dispatch,s=[],c={getState:o.getState,dispatch:function(t){return i(t)}};return s=e.map(function(t){return t(c)}),i=a.default.apply(void 0,s.concat([o.dispatch])),u({},o,{dispatch:i})}}}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t};e.default=o;var i=n(9),a=r(i);t.exports=e.default},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){return function(){return e(t.apply(void 0,arguments))}}function u(t,e){if("function"==typeof t)return o(t,e);if("object"!=typeof t||null==t)throw new Error("bindActionCreators expected an object or a function, instead received "+typeof t+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');return a.default(t,function(t){return o(t,e)})}e.__esModule=!0,e.default=u;var i=n(11),a=r(i);t.exports=e.default},function(t,e,n){(function(r){"use strict";function o(t){return t&&t.__esModule?t:{"default":t}}function u(t,e){var n=e&&e.type,r=n&&'"'+n.toString()+'"'||"an action";return'Reducer "'+t+'" returned undefined handling '+r+". To ignore an action, you must explicitly return the previous state."}function i(t,e){var n=Object.keys(e);if(0===n.length)return void console.error("Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.");if(!f.default(t))return void console.error('initialState has unexpected type of "'+{}.toString.call(t).match(/\s([a-z|A-Z]+)/)[1]+'". Expected initialState to be an object with the following '+('keys: "'+n.join('", "')+'"'));var r=Object.keys(t).filter(function(t){return n.indexOf(t)<0});r.length>0&&console.error("Unexpected "+(r.length>1?"keys":"key")+" "+('"'+r.join('", "')+'" in initialState will be ignored. ')+('Expected to find one of the known reducer keys instead: "'+n.join('", "')+'"'))}function a(t){var e=h.default(t,function(t){return"function"==typeof t});Object.keys(e).forEach(function(t){var n=e[t];if("undefined"==typeof n(void 0,{type:s.ActionTypes.INIT}))throw new Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var r=Math.random().toString(36).substring(7).split("").join(".");if("undefined"==typeof n(void 0,{type:r}))throw new Error('Reducer "'+t+'" returned undefined when probed with a random type. '+("Don't try to handle "+s.ActionTypes.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")});var n,o=d.default(e,function(){return void 0});return function(t,a){void 0===t&&(t=o);var s=d.default(e,function(e,n){var r=e(t[n],a);if("undefined"==typeof r)throw new Error(u(n,a));return r});return"undefined"!=typeof r&&"undefined"!=typeof r.env,"undefined"!=typeof __DEV__&&__DEV__&&(n||(i(t,s),n=!0)),s}}e.__esModule=!0,e.default=a;var s=n(8),c=n(10),f=o(c),l=n(11),d=o(l),p=n(29),h=o(p);t.exports=e.default}).call(e,n(12))},function(t,e){"use strict";function n(t,e){return Object.keys(t).reduce(function(n,r){return e(t[r])&&(n[r]=t[r]),n},{})}e.__esModule=!0,e.default=n,t.exports=e.default}])});
src/Tooltip.js
yuche/react-bootstrap
/* eslint-disable react/no-multi-comp */ import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const Tooltip = React.createClass({ mixins: [BootstrapMixin], propTypes: { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: CustomPropTypes.isRequiredForA11y(React.PropTypes.string), /** * Sets the direction the Tooltip is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Tooltip. */ positionLeft: React.PropTypes.number, /** * The "top" position value for the Tooltip. */ positionTop: React.PropTypes.number, /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * Title text */ title: React.PropTypes.node }, getDefaultProps() { return { placement: 'right' }; }, render() { const classes = { 'tooltip': true, [this.props.placement]: true }; const style = { 'left': this.props.positionLeft, 'top': this.props.positionTop }; const arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return ( <div role='tooltip' {...this.props} className={classNames(this.props.className, classes)} style={style}> <div className="tooltip-arrow" style={arrowStyle} /> <div className="tooltip-inner"> {this.props.children} </div> </div> ); } }); export default Tooltip;
node_modules/react-icons/md/contact-phone.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdContactPhone = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m29.8 23.4c-0.4-1.1-0.7-2.2-0.7-3.4s0.3-2.3 0.7-3.4h2.7l2.5-3.2-3.3-3.4c-2.2 1.6-3.8 3.9-4.6 6.6-0.3 1.1-0.5 2.2-0.5 3.4s0.2 2.3 0.5 3.4c0.8 2.6 2.4 5 4.6 6.6l3.3-3.4-2.5-3.2h-2.7z m-6.4 6.6v-1.6c0-3.4-6.7-5.2-10-5.2s-10 1.8-10 5.2v1.6h20z m-10-20c-2.8 0-5 2.3-5 5s2.2 5 5 5 5-2.3 5-5-2.3-5-5-5z m23.2-5c1.8 0 3.4 1.6 3.4 3.4v23.2c0 1.8-1.6 3.4-3.4 3.4h-33.2c-1.8 0-3.4-1.6-3.4-3.4v-23.2c0-1.8 1.6-3.4 3.4-3.4h33.2z"/></g> </Icon> ) export default MdContactPhone
src/client/app.js
laundree/laundree
// @flow import Debug from 'debug' import ReactDOM from 'react-dom' import React from 'react' import { BrowserRouter } from 'react-router-dom' import io from 'socket.io-client' import { createStore } from 'redux' import sdk from './sdk' import App from '../react/App' import ReactGA from 'react-ga' import { redux } from 'laundree-sdk' import type { State } from 'laundree-sdk/lib/redux' import { toLocale } from '../locales' ReactGA.initialize(window.__GOOGLE_ANALYTICS__TRACKING_ID__) const debug = Debug('laundree.initializers.app') function setupStore () { const state = window.__REDUX_STATE__ const socketUrl = typeof state.config.socketIoBase === 'string' ? `${state.config.socketIoBase}/redux` : '/redux' const socket = io(socketUrl, {query: {jwt: state.config.token}}) debug('Setting up store with state', state) const store = createStore(redux.reducer, state) const dispatchAction = action => { debug(`Dispatching: ${action.type}`, action) store.dispatch(action) } socket.on('actions', actions => actions.forEach(dispatchAction)) sdk.setupRedux(store, socket) return store } function setup () { const rootElement = document.querySelector('#AppRoot') if (!rootElement) return const store = setupStore() const state: State = store.getState() const locale = toLocale(state.config.locale || '', 'en') const token = state.config.token || null if (typeof token === 'string') { sdk.authenticator = () => Promise.resolve({type: 'bearer', token}) } sdk.baseUrl = typeof state.config.apiBase === 'string' ? state.config.apiBase : '/api' // $FlowFixMe it is though ReactDOM.hydrate( <BrowserRouter basename={`/${locale}`}> <App store={store} locale={locale} /> </BrowserRouter>, rootElement) } export default setup
src/docs/apiExamples/Label.js
recharts/recharts.org
import React from 'react'; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Label, LabelList } from 'recharts'; import { localeGet } from '../../utils/LocaleUtils'; const data = [ { name: 'Page A', uv: 4000, pv: 2400, amt: 2400, }, { name: 'Page B', uv: 3000, pv: 1398, amt: 2210, }, { name: 'Page C', uv: 2000, pv: 9800, amt: 2290, }, { name: 'Page D', uv: 2780, pv: 3908, amt: 2000, }, { name: 'Page E', uv: 1890, pv: 4800, amt: 2181, }, { name: 'Page F', uv: 2390, pv: 3800, amt: 2500, }, { name: 'Page G', uv: 3490, pv: 4300, amt: 2100, }, ]; const example = (local) => ( <div> <p style={{ fontSize: 18 }}>{localeGet(local, 'label', 'cartesian-title')}</p> <div className="cartesian-label-position"> <svg width={600} height={400}> <rect x={100} y={100} width={400} height={200} stroke="#000" fill="none" /> <g> <text x={300} y={90} textAnchor="middle"> top </text> </g> <g> <text x={90} y={200} textAnchor="end"> left </text> </g> <g> <text x={510} y={200} textAnchor="start"> right </text> </g> <g> <text x={300} y={200} textAnchor="middle"> center </text> </g> <g> <text x={300} y={310} textAnchor="middle" dominantBaseline="hanging"> bottom </text> </g> <g> <text x={110} y={200}> insideLeft </text> </g> <g> <text x={490} y={200} textAnchor="end"> insideRight </text> </g> <g> <text x={300} y={110} textAnchor="middle" dominantBaseline="hanging"> insideTop </text> </g> <g> <text x={300} y={290} textAnchor="middle"> insideBottom </text> </g> <g> <text x={110} y={110} dominantBaseline="hanging"> insideTopLeft </text> </g> <g> <text x={490} y={110} textAnchor="end" dominantBaseline="hanging"> insideTopRight </text> </g> <g> <text x={110} y={290}> insideBottomLeft </text> </g> <g> <text x={490} y={290} textAnchor="end"> insideBottomRight </text> </g> </svg> </div> <p style={{ fontSize: 18 }}>{localeGet(local, 'label', 'polar-title')}</p> <div className="poral-label-position"> <svg width={700} height={400}> <path d="M225,256.7L300,126.8A200,200,0,0,0,100,126.8L175,256.7A50,50,0,0,1,225,256.7" fill="none" stroke="#666" /> <g> <text x={200} y={300} textAnchor="middle" dominantBaseline="middle"> center </text> </g> <g> <text x={200} y={90} textAnchor="start" dominantBaseline="middle"> outside </text> </g> <g> <text x={200} y={175} textAnchor="middle" dominantBaseline="middle"> inside </text> </g> <path d="M400,300A200,200,0,0,1,600,100L600,60A240,240,0,0,0,360,300Z" fill="none" stroke="#666" /> <defs> <path id="textPathLabelDemoInsideStart" d="M383.34,261.8A220,220,0,0,1,600,80" /> </defs> <defs> <path id="textPathLabelDemoInsideEnd" d="M561.8,83.34A220,220,0,0,0,380,300" /> </defs> <defs> <path id="textPathLabelDemoEnd" d="M638.2,83.34A220,220,0,0,1,820,300" /> </defs> <text dominantBaseline="central"> <textPath xlinkHref="#textPathLabelDemoInsideStart">insideStart</textPath> </text> <text dominantBaseline="central" textAnchor="start"> <textPath xlinkHref="#textPathLabelDemoInsideEnd">insideEnd</textPath> </text> <text dominantBaseline="central" textAnchor="start"> <textPath xlinkHref="#textPathLabelDemoEnd">End</textPath> </text> </svg> </div> </div> ); const chartExample = () => ( <BarChart width={730} height={250} data={data} margin={{ top: 15, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="name"> <Label value="Pages of my website" offset={0} position="insideBottom" /> </XAxis> <YAxis label={{ value: 'pv of page', angle: -90, position: 'insideLeft', textAnchor: 'middle', }} /> <Bar dataKey="pv" fill="#8884d8"> <LabelList dataKey="name" position="top" /> </Bar> </BarChart> ); export default [ { demo: example, code: '', }, { demo: chartExample, code: ` <BarChart width={730} height={250} data={data} margin={{ top: 15, right: 30, left: 20, bottom: 5 }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="name"> <Label value="Pages of my website" offset={0} position="insideBottom" /> </XAxis> <YAxis label={{ value: 'pv of page', angle: -90, position: 'insideLeft' }} /> <Bar dataKey="pv" fill="#8884d8"> <LabelList dataKey="name" position="top" /> </Bar> </BarChart> `, dataCode: `const data = ${JSON.stringify(data, null, 2)}`, }, ];
app/classifier/world-wide-telescope.spec.js
zooniverse/Panoptes-Front-End
import React from 'react'; import assert from 'assert'; import WorldWideTelescope from './world-wide-telescope'; import { shallow } from 'enzyme'; const testSubject = { locations: [{ 'image/jpeg': 'http://www.image.com' }], metadata: {} }; const testProject = { slug: "zooniverse/test-project" }; const incompleteAnnotations = [ { task: 'T0', type: 'drawing', value: [{ height: 1000, width: 800, x: 315, y: 130 }] }, { task: 'T1', type: 'drawing', value: [{ details: [{ value: '44 00' }], x: 880, y: 1260 }] }, { task: 'T2', type: 'drawing', value: [{ details: [{ value: 0 }], x: 660, y: 1310 }] } ]; // These annotations are for two completely annotated charts const testAnnotations = [ { task: 'T0', type: 'drawing', value: [{ height: 275, width: 375, x: 485, y: 185 }, { height: 260, width: 540, x: 530, y: 730 }] }, { task: 'T1', type: 'drawing', value: [{ details: [{ value: '44 00' }], x: 1025, y: 1010 }, { details: [{ value: '44 00' }], x: 820, y: 490 }, { details: [{ value: '14 46 00' }], x: 555, y: 1010 }, { details: [{ value: '14 46 00' }], x: 520, y: 490 }, { details: [{ value: '-62 35' }], x: 495, y: 935 }, { details: [{ value: '-62 35' }], x: 445, y: 430 }, { details: [{ value: '-62 10' }], x: 460, y: 195 }, { details: [{ value: '-62 10' }], x: 490, y: 755 }] }, { task: 'T2', type: 'drawing', value: [{ details: [{ value: 0 }], x: 790, y: 1050 }, { details: [{ value: 0 }], x: 670, y: 515 }, { details: [{ value: 2 }], x: 445, y: 305 }, { details: [{ value: 2 }], x: 470, y: 835 }] } ]; const testWorkflow = { tasks: { T0: { type: 'drawing' }, T1: { type: 'drawing' }, T2: { type: 'drawing' } } }; describe('WorldWideTelescope render without incomplete annotations', function () { it('will render an empty div with no annotations', function() { const page = shallow(<WorldWideTelescope subject={testSubject} />); assert.equal(page.find('div').children().length, 0) }); it('will render an empty div with incomplete annotations', function() { const page = shallow(<WorldWideTelescope subject={testSubject} workflow={testWorkflow} project={testProject} annotations={incompleteAnnotations} />); assert.equal(page.find('div').children().length, 0) }); }); xdescribe('WorldWideTelescope with classification', function() { let wrapper; before(function () { wrapper = shallow(<WorldWideTelescope subject={testSubject} annotations={testAnnotations} workflow={testWorkflow} project={testProject} />); }); it('will render a WWT link for each full classification', function() { const linkInstances = wrapper.find('.standard-button'); assert.equal(linkInstances.length, 2); }); it('will render a cropped image for each fully classified chart', function() { const image = wrapper.find('img'); assert.equal(image.length, 2); }); it('will render text about misaligned images', function() { const content = wrapper.find('.worldwide-telescope__content'); content.forEach((node) => { assert.equal(node.childAt(1).type(), 'p'); }) }); });
ajax/libs/angular-google-maps/2.0.7/angular-google-maps.js
mitsuruog/cdnjs
/*! angular-google-maps 2.0.7 2014-11-04 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/angular-google-maps.git */ (function() { String.prototype.contains = function(value, fromIndex) { return this.indexOf(value, fromIndex) !== -1; }; String.prototype.flare = function(flare) { if (flare == null) { flare = 'uiGmap'; } return flare + this; }; String.prototype.ns = String.prototype.flare; }).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; if (comparison == null) { comparison = void 0; } res = _.map(array1, (function(_this) { return function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }; })(this)); return _.filter(res, function(o) { return o != null; }); }; _.containsObject = _.includeObject = function(obj, target, comparison) { if (comparison == null) { comparison = void 0; } if (obj === null) { return false; } return _.any(obj, (function(_this) { return function(value) { if (comparison != null) { return comparison(value, target); } else { return _.isEqual(value, target); } }; })(this)); }; _.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); /* ! 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('uiGmapgoogle-maps.providers', []); angular.module("uiGmapgoogle-maps.wrapped", []); angular.module("uiGmapgoogle-maps.extensions", ["uiGmapgoogle-maps.wrapped", 'uiGmapgoogle-maps.providers']); angular.module("uiGmapgoogle-maps.directives.api.utils", ['uiGmapgoogle-maps.extensions']); angular.module("uiGmapgoogle-maps.directives.api.managers", []); angular.module("uiGmapgoogle-maps.directives.api.options", ["uiGmapgoogle-maps.directives.api.utils"]); angular.module("uiGmapgoogle-maps.directives.api.options.builders", []); angular.module("uiGmapgoogle-maps.directives.api.models.child", ["uiGmapgoogle-maps.directives.api.utils", "uiGmapgoogle-maps.directives.api.options", "uiGmapgoogle-maps.directives.api.options.builders"]); angular.module("uiGmapgoogle-maps.directives.api.models.parent", ["uiGmapgoogle-maps.directives.api.managers", "uiGmapgoogle-maps.directives.api.models.child", 'uiGmapgoogle-maps.providers']); angular.module("uiGmapgoogle-maps.directives.api", ["uiGmapgoogle-maps.directives.api.models.parent"]); angular.module("uiGmapgoogle-maps", ["uiGmapgoogle-maps.directives.api", 'uiGmapgoogle-maps.providers']).factory("uiGmapdebounce", [ "$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.providers'.ns()).factory('MapScriptLoader'.ns(), [ '$q', 'uuid'.ns(), function($q, uuid) { var getScriptUrl, scriptId; scriptId = void 0; getScriptUrl = function(options) { if (options.china) { return 'http://maps.google.cn/maps/api/js?'; } else { return 'https://maps.googleapis.com/maps/api/js?'; } }; return { load: function(options) { var deferred, query, randomizedFunctionName, script; deferred = $q.defer(); if (angular.isDefined(window.google) && angular.isDefined(window.google.maps)) { deferred.resolve(window.google.maps); return deferred.promise; } randomizedFunctionName = options.callback = 'onGoogleMapsReady' + Math.round(Math.random() * 1000); window[randomizedFunctionName] = function() { window[randomizedFunctionName] = null; deferred.resolve(window.google.maps); }; query = _.map(options, function(v, k) { return k + '=' + v; }); if (scriptId) { document.getElementById(scriptId).remove(); } query = query.join('&'); script = document.createElement('script'); scriptId = "ui_gmap_map_load_" + uuid.generate(); script.id = scriptId; script.type = 'text/javascript'; script.src = getScriptUrl(options) + query; document.body.appendChild(script); return deferred.promise; } }; } ]).provider('GoogleMapApi'.ns(), function() { this.options = { china: false, v: '3.17', libraries: '', language: 'en', sensor: 'false' }; this.configure = function(options) { angular.extend(this.options, options); }; this.$get = [ 'MapScriptLoader'.ns(), (function(_this) { return function(loader) { return loader.load(_this.options); }; })(this) ]; return this; }); }).call(this); (function() { angular.module("google-maps.extensions".ns()).service('ExtendGWin'.ns(), function() { return { init: _.once(function() { if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor, recurse) { if (recurse != null) { return; } this._isOpen = true; this._open(map, anchor, true); }; google.maps.InfoWindow.prototype.close = function(recurse) { if (recurse != null) { return; } this._isOpen = false; this._close(true); }; google.maps.InfoWindow.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; /* Do the same for InfoBox TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier */ if (window.InfoBox) { window.InfoBox.prototype._open = window.InfoBox.prototype.open; window.InfoBox.prototype._close = window.InfoBox.prototype.close; window.InfoBox.prototype._isOpen = false; window.InfoBox.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; window.InfoBox.prototype.close = function() { this._isOpen = false; this._close(); }; window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; } if (window.MarkerLabel_) { window.MarkerLabel_.prototype.setContent = function() { var content; content = this.marker_.get("labelContent"); if (!content || _.isEqual(this.oldContent, content)) { return; } if (typeof (content != null ? content.nodeType : void 0) === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; this.oldContent = content; } else { this.labelDiv_.innerHTML = ""; this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.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 window.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); (function() { angular.module("uiGmapgoogle-maps.directives.api.utils").service("_sync".ns(), [ function() { return { fakePromise: function() { var _cb; _cb = void 0; return { then: function(cb) { return _cb = cb; }, resolve: function() { return _cb.apply(void 0, arguments); } }; } }; } ]).service("uiGmap_async", [ "$timeout", "uiGmapPromise", function($timeout, uiGmapPromise) { var defaultChunkSize, doChunk, each, map, waitOrGo; defaultChunkSize = 20; /* utility to reduce code bloat. The whole point is to check if there is existing synchronous work going on. If so we wait on it. Note: This is fully intended to be mutable (ie existingPiecesObj is getting existingPieces prop slapped on) */ waitOrGo = function(existingPiecesObj, fnPromise) { if (!existingPiecesObj.existingPieces) { return existingPiecesObj.existingPieces = fnPromise(); } else { return existingPiecesObj.existingPieces = existingPiecesObj.existingPieces.then(function() { return fnPromise(); }); } }; /* Author: Nicholas McCready & jfriend00 _async handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui The design of any functionality of _async is to be like lodash/underscore and replicate it but call things asynchronously underneath. Each should be sufficient for most things to be derived from. Optional Asynchronous Chunking via promises. */ doChunk = function(array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index) { var cnt, e, i; try { if (chunkSizeOrDontChunk && chunkSizeOrDontChunk < array.length) { cnt = chunkSizeOrDontChunk; } else { cnt = array.length; } i = index; while (cnt-- && i < (array ? array.length : i + 1)) { chunkCb(array[i], i); ++i; } if (array) { if (i < array.length) { index = i; if (chunkSizeOrDontChunk) { if (typeof pauseCb === "function") { pauseCb(); } return $timeout(function() { return doChunk(array, chunkSizeOrDontChunk, pauseMilli, chunkCb, pauseCb, overallD, index); }, pauseMilli, false); } } else { return overallD.resolve(); } } } catch (_error) { e = _error; return overallD.reject("error within chunking iterator: " + e); } }; each = function(array, chunk, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) { var overallD, ret; if (chunkSizeOrDontChunk == null) { chunkSizeOrDontChunk = defaultChunkSize; } if (index == null) { index = 0; } if (pauseMilli == null) { pauseMilli = 1; } ret = void 0; overallD = uiGmapPromise.defer(); ret = overallD.promise; if (!pauseMilli) { overallD.reject("pause (delay) must be set from _async!"); return ret; } if (array === void 0 || (array != null ? array.length : void 0) <= 0) { overallD.resolve(); return ret; } doChunk(array, chunkSizeOrDontChunk, pauseMilli, chunk, pauseCb, overallD, index); return ret; }; map = function(objs, iterator, pauseCb, chunkSizeOrDontChunk, index, pauseMilli) { var results; results = []; if (!((objs != null) && (objs != null ? objs.length : void 0) > 0)) { return uiGmapPromise.resolve(results); } return each(objs, function(o) { return results.push(iterator(o)); }, pauseCb, chunkSizeOrDontChunk, index, pauseMilli).then(function() { return results; }); }; return { each: each, map: map, waitOrGo: waitOrGo, defaultChunkSize: defaultChunkSize }; } ]); }).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".ns()).factory("BaseObject".ns(), 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".ns()).factory("ChildEvents".ns(), function() { return { onChildCreation: function(child) {} }; }); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("CtrlHandle".ns(), [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.$on('$destroy', function() { return CtrlHandle.handle($scope); }); $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("EventsHelper".ns(), [ "Logger".ns(), 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 scope.$evalAsync(eventHandler.apply(scope, [gObject, eventName, model, arguments])); }); } })); } }, 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".ns()).factory("FitHelper".ns(), [ "BaseObject".ns(), "Logger".ns(), "_async".ns(), function(BaseObject, $log, _async) { var FitHelper; return FitHelper = (function(_super) { __extends(FitHelper, _super); function FitHelper() { return FitHelper.__super__.constructor.apply(this, arguments); } FitHelper.prototype.fit = function(gMarkers, gMap) { var bounds, everSet; if (gMap && gMarkers && gMarkers.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; return _async.each(gMarkers, (function(_this) { return function(gMarker) { if (gMarker) { if (!everSet) { everSet = true; } return bounds.extend(gMarker.getPosition()); } }; })(this)).then(function() { if (everSet) { return gMap.fitBounds(bounds); } }); } }; return FitHelper; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).service("GmapUtil".ns(), [ "Logger".ns(), "$compile", function(Logger, $compile) { var getCoords, getLatitude, getLongitude, 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); } }; validateCoords = function(coords) { if (angular.isUndefined(coords)) { return false; } if (_.isArray(coords)) { if (coords.length === 2) { return true; } } else if ((coords != null) && (coords != null ? coords.type : void 0)) { if (coords.type === "Point" && _.isArray(coords.coordinates) && coords.coordinates.length === 2) { return true; } } if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) { return true; } return false; }; return { setCoordsFromEvent: function(prevValue, newLatLon) { if (!prevValue) { return; } if (Array.isArray(prevValue) && prevValue.length === 2) { prevValue[1] = newLatLon.lat(); prevValue[0] = newLatLon.lng(); } else if (angular.isDefined(prevValue.type) && prevValue.type === "Point") { prevValue.coordinates[1] = newLatLon.lat(); prevValue.coordinates[0] = newLatLon.lng(); } else { prevValue.latitude = newLatLon.lat(); prevValue.longitude = newLatLon.lng(); } return prevValue; }, getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor); xPos = parseFloat(anchor[1]); yPos = parseFloat(anchor[2]); if ((xPos != null) && (yPos != null)) { return new google.maps.Point(xPos, yPos); } }, createWindowOptions: function(gMarker, scope, content, defaults) { var options; if ((content != null) && (defaults != null) && ($compile != null)) { options = angular.extend({}, defaults, { content: this.buildContent(scope, defaults, content), position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords) }); if ((gMarker != null) && ((options != null ? options.pixelOffset : void 0) == null)) { if (options.boxClass == null) { } else { options.pixelOffset = { height: 0, width: -2 }; } } return options; } else { if (!defaults) { Logger.error("infoWindow defaults not defined"); if (!content) { return Logger.error("infoWindow content not defined"); } } else { return defaults; } } }, buildContent: function(scope, defaults, content) { var parsed, ret; if (defaults.content != null) { ret = defaults.content; } else { if ($compile != null) { content = content.replace(/^\s+|\s+$/g, ""); parsed = content === '' ? '' : $compile(content)(scope); if (parsed.length > 0) { ret = parsed[0]; } } else { ret = content; } } return ret; }, defaultDelay: 50, isTrue: function(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; }, validateBoundPoints: function(bounds) { if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) { return false; } return true; }, convertBoundPoints: function(bounds) { var result; result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude)); return result; }, fitMapBounds: function(map, bounds) { return map.fitBounds(bounds); } }; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).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; }, reset: function() { ctr = 0; return proms.length = 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("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapLinked", [ "uiGmapBaseObject", 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("uiGmapgoogle-maps.directives.api.utils").service("uiGmapLogger", [ "$log", function($log) { return { doLog: false, info: function(msg) { if (this.doLog) { if ($log != null) { return $log.info(msg); } else { return console.info(msg); } } }, log: function(msg) { if (this.doLog) { if ($log != null) { return $log.log(msg); } else { return console.log(msg); } } }, error: function(msg) { if (this.doLog) { if ($log != null) { return $log.error(msg); } else { return console.error(msg); } } }, debug: function(msg) { if (this.doLog) { if ($log != null) { return $log.debug(msg); } else { return console.debug(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".ns()).factory("ModelKey".ns(), [ "BaseObject".ns(), "GmapUtil".ns(), function(BaseObject, GmapUtil) { var ModelKey; return ModelKey = (function(_super) { __extends(ModelKey, _super); function ModelKey(scope) { this.scope = scope; this.getChanges = __bind(this.getChanges, this); this.getProp = __bind(this.getProp, this); this.setIdKey = __bind(this.setIdKey, this); this.modelKeyComparison = __bind(this.modelKeyComparison, this); ModelKey.__super__.constructor.call(this); this.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) { if (key == null) { return; } if (key !== 'self') { return model[key]; } return model; }; ModelKey.prototype.getProp = function(propName, model) { return this.modelOrKey(model, propName); }; /* For the cases were watching a large object we only want to know the list of props that actually changed. Also we want to limit the amount of props we analyze to whitelisted props that are actually tracked by scope. (should make things faster with whitelisted) */ ModelKey.prototype.getChanges = function(now, prev, whitelistedProps) { var c, changes, prop; if (whitelistedProps) { prev = _.pick(prev, whitelistedProps); now = _.pick(now, whitelistedProps); } changes = {}; prop = {}; c = {}; for (prop in now) { if (!prev || prev[prop] !== now[prop]) { if (_.isArray(now[prop])) { changes[prop] = now[prop]; } else if (_.isObject(now[prop])) { c = this.getChanges(now[prop], prev[prop]); if (!_.isEmpty(c)) { changes[prop] = c; } } else { changes[prop] = now[prop]; } } } return changes; }; return ModelKey; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).factory("ModelsWatcher".ns(), [ "Logger".ns(), "_async".ns(), function(Logger, _async) { return { figureOutState: function(idKey, scope, childObjects, comparison, callBack) { var adds, mappedScopeModelIds, removals, updates; 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()) + ",\ncan not use do comparison/insertion"); } }).then((function(_this) { return 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); } }); }; })(this)).then((function(_this) { return function() { return callBack({ adds: adds, removals: removals, updates: updates }); }; })(this)); } }; } ]); }).call(this); (function() { angular.module('uiGmapgoogle-maps.directives.api.utils').service('uiGmapPromise', [ '$q', function($q) { return { defer: function() { return $q.defer(); }, resolve: function() { var d; d = $q.defer(); d.resolve.apply(void 0, arguments); return d.promise; } }; } ]); }).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; if (!this.didValueStateChange) { return this.allVals; } all = []; this.keys().forEach((function(_this) { return function(key) { if (_.indexOf(propsToPop, key) === -1) { return all.push(_this[key]); } }; })(this)); all; this.didValueStateChange = false; this.keys(); return this.allVals = all; }; PropMap.prototype.keys = function() { var all, keys; if (!this.didKeyStateChange) { return this.allKeys; } keys = _.keys(this); all = []; _.each(keys, (function(_this) { return function(prop) { if (_.indexOf(propsToPop, prop) === -1) { return all.push(prop); } }; })(this)); 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() { return this.keys().map((function(_this) { return function(k) { return _this.remove(k); }; })(this)); }; PropMap.prototype.removeAll = function() { return this.slice(); }; return PropMap; })(); angular.module("uiGmapgoogle-maps.directives.api.utils").factory("uiGmapPropMap", function() { return window.PropMap; }); }).call(this); (function() { angular.module("google-maps.directives.api.utils".ns()).factory("PropertyAction".ns(), [ "Logger".ns(), function(Logger) { var PropertyAction; PropertyAction = function(setterFn, isFirstSet, key) { var self; self = this; this.setIfChange = function(newVal, oldVal) { var callingKey; callingKey = this.exp; if (!_.isEqual(oldVal, newVal || isFirstSet)) { return setterFn(callingKey, newVal); } }; this.sic = this.setIfChange; return this; }; return PropertyAction; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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".ns()).factory("ClustererMarkerManager".ns(), [ "Logger".ns(), "FitHelper".ns(), "PropMap".ns(), function($log, FitHelper, PropMap) { var ClustererMarkerManager; ClustererMarkerManager = (function(_super) { __extends(ClustererMarkerManager, _super); ClustererMarkerManager.type = 'ClustererMarkerManager'; 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); this.type = ClustererMarkerManager.type; 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) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.remove(gMarker); }; })(this)); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.removeMany(this.getGMarkers()); return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Attaching event: " + eventName + " to clusterer"); _results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName])); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.clearEvents = function(options) { 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".ns()).factory("MarkerManager".ns(), [ "Logger".ns(), "FitHelper".ns(), "PropMap".ns(), function(Logger, FitHelper, PropMap) { var MarkerManager; MarkerManager = (function(_super) { __extends(MarkerManager, _super); MarkerManager.include(FitHelper); MarkerManager.type = 'MarkerManager'; function MarkerManager(gMap, opt_markers, opt_options) { this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.handleOptDraw = __bind(this.handleOptDraw, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); MarkerManager.__super__.constructor.call(this); this.type = MarkerManager.type; this.gMap = gMap; this.gMarkers = new PropMap(); this.$log = Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { var exists, msg; if (optDraw == null) { optDraw = true; } if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; Logger.error(msg); throw msg; } exists = (this.gMarkers.get(gMarker.key)) != null; if (!exists) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.put(gMarker.key, gMarker); } }; MarkerManager.prototype.addMany = function(gMarkers) { return gMarkers.forEach((function(_this) { return function(gMarker) { return _this.add(gMarker); }; })(this)); }; MarkerManager.prototype.remove = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.handleOptDraw(gMarker, optDraw, false); if (this.gMarkers.get(gMarker.key)) { return this.gMarkers.remove(gMarker.key); } }; MarkerManager.prototype.removeMany = function(gMarkers) { return this.gMarkers.values().forEach((function(_this) { return function(marker) { return _this.remove(marker); }; })(this)); }; MarkerManager.prototype.draw = function() { var deletes; deletes = []; this.gMarkers.values().forEach((function(_this) { return function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { gMarker.setMap(_this.gMap); return gMarker.isDrawn = true; } else { return deletes.push(gMarker); } } }; })(this)); return deletes.forEach((function(_this) { return function(gMarker) { gMarker.isDrawn = false; return _this.remove(gMarker, true); }; })(this)); }; MarkerManager.prototype.clear = function() { this.gMarkers.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".ns()).factory("add-events".ns(), [ "$timeout", function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(listener) { return google.maps.event.removeListener(listener); }); return remove = null; }; }; return addEvents; } ]); }).call(this); (function() { angular.module("google-maps".ns()).factory("array-sync".ns(), [ "add-events".ns(), 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() { 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.options.builders".ns()).service("CommonOptionsBuilder".ns(), [ "BaseObject".ns(), "Logger".ns(), function(BaseObject, $log) { var CommonOptionsBuilder; return CommonOptionsBuilder = (function(_super) { __extends(CommonOptionsBuilder, _super); function CommonOptionsBuilder() { this.watchProps = __bind(this.watchProps, this); this.buildOpts = __bind(this.buildOpts, this); return CommonOptionsBuilder.__super__.constructor.apply(this, arguments); } CommonOptionsBuilder.prototype.props = [ 'clickable', 'draggable', 'editable', 'visible', { prop: 'stroke', isColl: true } ]; CommonOptionsBuilder.prototype.buildOpts = function(customOpts, forEachOpts) { var hasModel, model, opts, _ref, _ref1, _ref2; if (customOpts == null) { customOpts = {}; } if (forEachOpts == null) { forEachOpts = {}; } if (!this.scope) { $log.error("this.scope not defined in CommonOptionsBuilder can not buildOpts"); return; } if (!this.map) { $log.error("this.map not defined in CommonOptionsBuilder can not buildOpts"); return; } hasModel = _(this.scope).chain().keys().contains('model').value(); model = hasModel ? this.scope.model : this.scope; opts = angular.extend(customOpts, this.DEFAULTS, { map: this.map, strokeColor: (_ref = model.stroke) != null ? _ref.color : void 0, strokeOpacity: (_ref1 = model.stroke) != null ? _ref1.opacity : void 0, strokeWeight: (_ref2 = model.stroke) != null ? _ref2.weight : void 0 }); angular.forEach(angular.extend(forEachOpts, { clickable: true, draggable: false, editable: false, "static": false, fit: false, visible: true, zIndex: 0 }), (function(_this) { return function(defaultValue, key) { if (angular.isUndefined(model[key] || model[key] === null)) { return opts[key] = defaultValue; } else { return opts[key] = model[key]; } }; })(this)); if (opts["static"]) { opts.editable = false; } return opts; }; CommonOptionsBuilder.prototype.watchProps = function(props) { if (props == null) { props = this.props; } return props.forEach((function(_this) { return function(prop) { if ((_this.attrs[prop] != null) || (_this.attrs[prop != null ? prop.prop : void 0] != null)) { if (prop != null ? prop.isColl : void 0) { return _this.scope.$watchCollection(prop.prop, _this.setMyOptions); } else { return _this.scope.$watch(prop, _this.setMyOptions); } } }; })(this)); }; return CommonOptionsBuilder; })(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.options.builders".ns()).factory("PolylineOptionsBuilder".ns(), [ "CommonOptionsBuilder".ns(), function(CommonOptionsBuilder) { var PolylineOptionsBuilder; return PolylineOptionsBuilder = (function(_super) { __extends(PolylineOptionsBuilder, _super); function PolylineOptionsBuilder() { return PolylineOptionsBuilder.__super__.constructor.apply(this, arguments); } PolylineOptionsBuilder.prototype.buildOpts = function(pathPoints) { return PolylineOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, { geodesic: false }); }; return PolylineOptionsBuilder; })(CommonOptionsBuilder); } ]).factory("ShapeOptionsBuilder".ns(), [ "CommonOptionsBuilder".ns(), function(CommonOptionsBuilder) { var ShapeOptionsBuilder; return ShapeOptionsBuilder = (function(_super) { __extends(ShapeOptionsBuilder, _super); function ShapeOptionsBuilder() { return ShapeOptionsBuilder.__super__.constructor.apply(this, arguments); } ShapeOptionsBuilder.prototype.buildOpts = function(customOpts, forEachOpts) { var _ref, _ref1; customOpts = angular.extend(customOpts, { fillColor: (_ref = this.scope.fill) != null ? _ref.color : void 0, fillOpacity: (_ref1 = this.scope.fill) != null ? _ref1.opacity : void 0 }); return ShapeOptionsBuilder.__super__.buildOpts.call(this, customOpts, forEachOpts); }; return ShapeOptionsBuilder; })(CommonOptionsBuilder); } ]).factory("PolygonOptionsBuilder".ns(), [ "ShapeOptionsBuilder".ns(), function(ShapeOptionsBuilder) { var PolygonOptionsBuilder; return PolygonOptionsBuilder = (function(_super) { __extends(PolygonOptionsBuilder, _super); function PolygonOptionsBuilder() { return PolygonOptionsBuilder.__super__.constructor.apply(this, arguments); } PolygonOptionsBuilder.prototype.buildOpts = function(pathPoints) { return PolygonOptionsBuilder.__super__.buildOpts.call(this, { path: pathPoints }, { geodesic: false }); }; return PolygonOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory("RectangleOptionsBuilder".ns(), [ "ShapeOptionsBuilder".ns(), function(ShapeOptionsBuilder) { var RectangleOptionsBuilder; return RectangleOptionsBuilder = (function(_super) { __extends(RectangleOptionsBuilder, _super); function RectangleOptionsBuilder() { return RectangleOptionsBuilder.__super__.constructor.apply(this, arguments); } RectangleOptionsBuilder.prototype.buildOpts = function(bounds) { return RectangleOptionsBuilder.__super__.buildOpts.call(this, { bounds: bounds }); }; return RectangleOptionsBuilder; })(ShapeOptionsBuilder); } ]).factory("CircleOptionsBuilder".ns(), [ "ShapeOptionsBuilder".ns(), function(ShapeOptionsBuilder) { var CircleOptionsBuilder; return CircleOptionsBuilder = (function(_super) { __extends(CircleOptionsBuilder, _super); function CircleOptionsBuilder() { return CircleOptionsBuilder.__super__.constructor.apply(this, arguments); } CircleOptionsBuilder.prototype.buildOpts = function(center, radius) { return CircleOptionsBuilder.__super__.buildOpts.call(this, { center: center, radius: radius }); }; return CircleOptionsBuilder; })(ShapeOptionsBuilder); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.options".ns()).service("MarkerOptions".ns(), [ "Logger".ns(), "GmapUtil".ns(), function($log, GmapUtil) { return _.extend(GmapUtil, { createOptions: 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 : GmapUtil.getCoords(coords), visible: defaults.visible != null ? defaults.visible : GmapUtil.validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, isLabel: function(options) { if ((options.labelContent != null) || (options.labelAnchor != null) || (options.labelClass != null) || (options.labelStyle != null) || (options.labelVisible != null)) { return true; } else { return false; } } }); } ]); }).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".ns()).factory("DrawFreeHandChildModel".ns(), [ "Logger".ns(), '$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.map = map; enable = (function(_this) { return function() { var _ref; if ((_ref = _this.deferred) != null) { _ref.resolve(); } return _this.map.setOptions(_this.oldOptions); }; })(this); disableMap = (function(_this) { return function() { $log.info('disabling map move'); _this.oldOptions = map.getOptions(); return _this.map.setOptions({ draggable: false, zoomControl: false, scrollwheel: false, disableDoubleClickZoom: false }); }; })(this); this.engage = (function(_this) { return 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; }; })(this); 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".ns()).factory("MarkerChildModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(), "Logger".ns(), "EventsHelper".ns(), "PropertyAction".ns(), "MarkerOptions".ns(), "IMarker".ns(), "MarkerManager".ns(), "uiGmapPromise", function(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) { var MarkerChildModel, keys; keys = ['coords', 'icon', 'options', 'fit']; MarkerChildModel = (function(_super) { var destroy; __extends(MarkerChildModel, _super); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); MarkerChildModel.include(MarkerOptions); destroy = function(child) { if ((child != null ? child.gMarker : void 0) != null) { child.removeEvents(child.externalListeners); child.removeEvents(child.internalListeners); if (child != null ? child.gMarker : void 0) { if (child.removeFromManager) { child.gMarkerManager.remove(child.gMarker); } child.gMarker.setMap(null); return child.gMarker = null; } } }; function MarkerChildModel(scope, model, keys, gMap, defaults, doClick, gMarkerManager, doDrawSelf, trackModel, needRedraw) { var action, firstTime; this.model = model; this.keys = keys; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gMarkerManager = gMarkerManager; this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true; this.trackModel = trackModel != null ? trackModel : true; this.needRedraw = needRedraw != null ? needRedraw : false; this.internalEvents = __bind(this.internalEvents, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.isNotValid = __bind(this.isNotValid, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); this.destroy = __bind(this.destroy, this); this.deferred = uiGmapPromise.defer(); _.each(this.keys, (function(_this) { return function(v, k) { return _this[k + 'Key'] = _.isFunction(_this.keys[k]) ? _this.keys[k]() : _this.keys[k]; }; })(this)); this.idKey = this.idKeyKey || "id"; if (this.model[this.idKey] != null) { this.id = this.model[this.idKey]; } MarkerChildModel.__super__.constructor.call(this, scope); this.setMyScope('all', this.model, void 0, true); this.scope.getGMarker = (function(_this) { return function() { return _this.gMarker; }; })(this); this.createMarker(this.model); firstTime = true; if (this.trackModel) { this.scope.model = this.model; this.scope.$watch('model', (function(_this) { return function(newValue, oldValue) { var changes; if (newValue !== oldValue) { changes = _this.getChanges(newValue, oldValue, IMarker.keys); return _.each(changes, function(v, k) { _this.setMyScope(k, newValue, oldValue); return _this.needRedraw = true; }); } }; })(this), true); } else { action = new PropertyAction((function(_this) { return function(calledKey, newVal) { return _this.setMyScope(calledKey, scope); }; })(this), false); _.each(this.keys, function(v, k) { return scope.$watch(k, action.sic, true); }); } this.scope.$on("$destroy", (function(_this) { return function() { return destroy(_this); }; })(this)); $log.info(this); } MarkerChildModel.prototype.destroy = function(removeFromManager) { if (removeFromManager == null) { removeFromManager = true; } this.removeFromManager = removeFromManager; return this.scope.$destroy(); }; MarkerChildModel.prototype.setMyScope = function(thingThatChanged, model, oldModel, isInit) { var justCreated; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } if (model == null) { model = this.model; } if (!this.gMarker) { this.setOptions(this.scope); justCreated = true; } switch (thingThatChanged) { case 'all': return _.each(this.keys, (function(_this) { return function(v, k) { return _this.setMyScope(k, model, oldModel, isInit); }; })(this)); case 'icon': return this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon); case 'coords': return this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords); case 'options': if (!justCreated) { return this.createMarker(model, oldModel, isInit); } } }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } return this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions); }; 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 (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.isNotValid = function(scope, doCheckGmarker) { var hasIdenticalScopes, hasNoGmarker; if (doCheckGmarker == null) { doCheckGmarker = true; } hasNoGmarker = !doCheckGmarker ? false : this.gMarker === void 0; hasIdenticalScopes = !this.trackModel ? scope.$id !== this.scope.$id : false; return hasIdenticalScopes || hasNoGmarker; }; MarkerChildModel.prototype.setCoords = function(scope) { if (this.isNotValid(scope) || (this.gMarker == null)) { return; } if (this.getProp(this.coordsKey, this.model) != null) { if (!this.validateCoords(this.getProp(this.coordsKey, this.model))) { $log.debug("MarkerChild does not have coords yet. They may be defined later."); return; } this.gMarker.setPosition(this.getCoords(this.getProp(this.coordsKey, this.model))); this.gMarker.setVisible(this.validateCoords(this.getProp(this.coordsKey, this.model))); return this.gMarkerManager.add(this.gMarker); } else { return this.gMarkerManager.remove(this.gMarker); } }; MarkerChildModel.prototype.setIcon = function(scope) { if (this.isNotValid(scope) || (this.gMarker == null)) { return; } this.gMarker.setIcon(this.getProp(this.iconKey, this.model)); this.gMarkerManager.add(this.gMarker); this.gMarker.setPosition(this.getCoords(this.getProp(this.coordsKey, this.model))); return this.gMarker.setVisible(this.validateCoords(this.getProp(this.coordsKey, this.model))); }; MarkerChildModel.prototype.setOptions = function(scope) { var coords, icon, _options; if (this.isNotValid(scope, false)) { return; } if (scope.coords == null) { return; } coords = this.getProp(this.coordsKey, this.model); icon = this.getProp(this.iconKey, this.model); _options = this.getProp(this.optionsKey, this.model); this.opts = this.createOptions(coords, icon, _options); if ((this.gMarker != null) && (this.isLabel(this.gMarker === this.isLabel(this.opts)))) { this.gMarker.setOptions(this.opts); } else { if (this.gMarker != null) { this.gMarkerManager.remove(this.gMarker); this.gMarker = null; } } if (!this.gMarker) { if (this.isLabel(this.opts)) { this.gMarker = new MarkerWithLabel(this.setLabelOptions(this.opts)); } else { this.gMarker = new google.maps.Marker(this.opts); } } if (this.externalListeners) { this.removeEvents(this.externalListeners); } if (this.internalListeners) { this.removeEvents(this.internalListeners); } this.externalListeners = this.setEvents(this.gMarker, this.scope, this.model, ['dragend']); this.internalListeners = this.setEvents(this.gMarker, { events: this.internalEvents(), $evalAsync: function() {} }, this.model); if (this.id != null) { this.gMarker.key = this.id; } this.gMarkerManager.add(this.gMarker); if (this.gMarker && (this.gMarker.getMap() || this.gMarkerManager.type !== MarkerManager.type)) { this.deferred.resolve(this.gMarker); } else { if (!this.gMarker) { this.deferred.reject("gMarker is null"); } if (!(this.gMarker.getMap() && this.gMarkerManager.type === MarkerManager.type)) { $log.warn('gMarker has no map yet'); this.deferred.resolve(this.gMarker); } } if (this.model[this.fitKey]) { return this.gMarkerManager.fit(); } }; MarkerChildModel.prototype.setLabelOptions = function(opts) { opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor); return opts; }; MarkerChildModel.prototype.internalEvents = function() { return { dragend: (function(_this) { return function(marker, eventName, model, mousearg) { var events, modelToSet, newCoords; modelToSet = _this.trackModel ? _this.scope.model : _this.model; newCoords = _this.setCoordsFromEvent(_this.modelOrKey(modelToSet, _this.coordsKey), _this.gMarker.getPosition()); modelToSet = _this.setVal(model, _this.coordsKey, newCoords); events = _this.scope.events; if ((events != null ? events.dragend : void 0) != null) { events.dragend(marker, eventName, modelToSet, mousearg); } return _this.scope.$apply(); }; })(this), click: (function(_this) { return function(marker, eventName, model, mousearg) { var click; click = _.isFunction(_this.clickKey) ? _this.clickKey : _this.getProp(_this.clickKey, _this.model); if (_this.doClick && (click != null)) { return _this.scope.$evalAsync(click(marker, eventName, _this.model, mousearg)); } }; })(this) }; }; return MarkerChildModel; })(ModelKey); return MarkerChildModel; } ]); }).call(this); (function() { var __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".ns()).factory("PolygonChildModel".ns(), [ "PolygonOptionsBuilder".ns(), "Logger".ns(), "$timeout", "array-sync".ns(), "GmapUtil".ns(), "EventsHelper".ns(), function(Builder, $log, $timeout, arraySync, GmapUtil, EventsHelper) { var PolygonChildModel; return PolygonChildModel = (function(_super) { __extends(PolygonChildModel, _super); PolygonChildModel.include(GmapUtil); PolygonChildModel.include(EventsHelper); function PolygonChildModel(scope, attrs, map, defaults, model) { var arraySyncer, pathPoints, polygon; this.scope = scope; this.attrs = attrs; this.map = map; this.defaults = defaults; this.model = model; this.listeners = void 0; if (angular.isUndefined(scope.path) || scope.path === null || !this.validatePath(scope.path)) { $log.error("polygon: no valid path attribute found"); return; } pathPoints = this.convertPathPoints(scope.path); polygon = new google.maps.Polygon(this.buildOpts(pathPoints)); if (scope.fit) { this.extendMapBounds(this.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(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", (function(_this) { return function(newValue, oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.color)) { scope.$watch("fill.color", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.opacity)) { scope.$watch("fill.opacity", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.zIndex)) { scope.$watch("zIndex", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(_this.buildOpts(polygon.getPath())); } }; })(this)); } if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { this.listeners = EventsHelper.setEvents(polygon, scope, scope); } arraySyncer = arraySync(polygon.getPath(), scope, "path", (function(_this) { return function(pathPoints) { if (scope.fit) { return _this.extendMapBounds(_this.map, pathPoints); } }; })(this)); scope.$on("$destroy", (function(_this) { return function() { polygon.setMap(null); _this.removeEvents(_this.listeners); if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }; })(this)); } return PolygonChildModel; })(Builder); } ]); }).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".ns()).factory("PolylineChildModel".ns(), [ "PolylineOptionsBuilder".ns(), "Logger".ns(), "$timeout", "array-sync".ns(), "GmapUtil".ns(), "EventsHelper".ns(), function(Builder, $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 createPolyline; this.scope = scope; this.attrs = attrs; this.map = map; this.defaults = defaults; this.model = model; this.clean = __bind(this.clean, this); createPolyline = (function(_this) { return function() { var pathPoints; pathPoints = _this.convertPathPoints(_this.scope.path); if (_this.polyline != null) { _this.clean(); } if (pathPoints.length > 0) { _this.polyline = new google.maps.Polyline(_this.buildOpts(pathPoints)); } if (_this.polyline) { if (_this.scope.fit) { _this.extendMapBounds(map, pathPoints); } arraySync(_this.polyline.getPath(), _this.scope, "path", function(pathPoints) { if (_this.scope.fit) { return _this.extendMapBounds(map, pathPoints); } }); return _this.listeners = _this.model ? _this.setEvents(_this.polyline, _this.scope, _this.model) : _this.setEvents(_this.polyline, _this.scope, _this.scope); } }; })(this); createPolyline(); scope.$watch('path', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue) || !_this.polyline) { return createPolyline(); } }; })(this)); if (!scope["static"] && angular.isDefined(scope.editable)) { scope.$watch("editable", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setEditable(newValue) : void 0; } }; })(this)); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setDraggable(newValue) : void 0; } }; })(this)); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setVisible(newValue) : void 0; } }; })(this)); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } if (angular.isDefined(scope.icons)) { scope.$watch("icons", (function(_this) { return function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }; })(this)); } scope.$on("$destroy", (function(_this) { return function() { _this.clean(); return _this.scope = null; }; })(this)); $log.info(this); } PolylineChildModel.prototype.clean = function() { var arraySyncer, _ref; this.removeEvents(this.listeners); if ((_ref = this.polyline) != null) { _ref.setMap(null); } this.polyline = null; if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }; PolylineChildModel.prototype.destroy = function() { return this.scope.$destroy(); }; return PolylineChildModel; })(Builder); } ]); }).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".ns()).factory("WindowChildModel".ns(), [ "BaseObject".ns(), "GmapUtil".ns(), "Logger".ns(), "$compile", "$http", "$templateCache", function(BaseObject, GmapUtil, $log, $compile, $http, $templateCache) { var WindowChildModel; WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(GmapUtil); function WindowChildModel(model, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element, needToManualDestroy, markerIsVisibleAfterWindowClose) { this.model = model; this.scope = scope; this.opts = opts; this.isIconVisibleOnClick = isIconVisibleOnClick; this.mapCtrl = mapCtrl; this.markerScope = markerScope; this.element = element; this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false; this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true; this.destroy = __bind(this.destroy, this); this.remove = __bind(this.remove, this); this.getLatestPosition = __bind(this.getLatestPosition, this); this.hideWindow = __bind(this.hideWindow, this); this.showWindow = __bind(this.showWindow, this); this.handleClick = __bind(this.handleClick, this); this.watchOptions = __bind(this.watchOptions, this); this.watchCoords = __bind(this.watchCoords, this); this.createGWin = __bind(this.createGWin, this); this.watchElement = __bind(this.watchElement, this); this.watchAndDoShow = __bind(this.watchAndDoShow, this); this.doShow = __bind(this.doShow, this); this.getGmarker = function() { var _ref, _ref1; if (((_ref = this.markerScope) != null ? _ref['getGMarker'] : void 0) != null) { return (_ref1 = this.markerScope) != null ? _ref1.getGMarker() : void 0; } }; this.googleMapsHandles = []; this.createGWin(); if (this.getGmarker() != null) { this.getGmarker().setClickable(true); } this.watchElement(); this.watchOptions(); this.watchCoords(); this.watchAndDoShow(); this.scope.$on("$destroy", (function(_this) { return function() { return _this.destroy(); }; })(this)); $log.info(this); } WindowChildModel.prototype.doShow = function() { if (this.scope.show) { return this.showWindow(); } else { return this.hideWindow(); } }; WindowChildModel.prototype.watchAndDoShow = function() { if (this.model.show != null) { this.scope.show = this.model.show; } this.scope.$watch('show', this.doShow, true); return this.doShow(); }; WindowChildModel.prototype.watchElement = function() { return this.scope.$watch((function(_this) { return function() { var _ref; if (!(_this.element || _this.html)) { return; } if (_this.html !== _this.element.html() && _this.gWin) { if ((_ref = _this.opts) != null) { _ref.content = void 0; } _this.remove(); return _this.createGWin(); } }; })(this)); }; WindowChildModel.prototype.createGWin = function() { var defaults, _opts, _ref, _ref1; 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.getGmarker(), this.markerScope || 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); } this.handleClick((_ref = this.scope) != null ? (_ref1 = _ref.options) != null ? _ref1.forceClick : void 0 : void 0); this.doShow(); return this.googleMapsHandles.push(google.maps.event.addListener(this.gWin, 'closeclick', (function(_this) { return function() { if (_this.getGmarker()) { _this.getGmarker().setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { _this.getGmarker().setVisible(false); return _this.getGmarker().setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _this.gWin.isOpen(false); _this.model.show = false; if (_this.scope.closeClick != null) { return _this.scope.$apply(_this.scope.closeClick()); } else { return _this.scope.$apply(); } }; })(this))); } }; WindowChildModel.prototype.watchCoords = function() { var scope; scope = this.markerScope != null ? this.markerScope : this.scope; return scope.$watch('coords', (function(_this) { return function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { _this.hideWindow(); } else if (!_this.validateCoords(newValue)) { $log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.gWin.setPosition(pos); if (_this.opts) { return _this.opts.position = pos; } } }; })(this), true); }; WindowChildModel.prototype.watchOptions = function() { return this.scope.$watch('options', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.opts = newValue; if (_this.gWin != null) { _this.gWin.setOptions(_this.opts); if ((_this.opts.visible != null) && _this.opts.visible) { return _this.showWindow(); } else if (_this.opts.visible != null) { return _this.hideWindow(); } } } }; })(this), true); }; WindowChildModel.prototype.handleClick = function(forceClick) { var click; if (this.gWin == null) { return; } click = (function(_this) { return function() { var pos, _ref, _ref1; if (_this.gWin == null) { _this.createGWin(); } pos = _this.scope.coords != null ? (_ref = _this.gWin) != null ? _ref.getPosition() : void 0 : (_ref1 = _this.getGmarker()) != null ? _ref1.getPosition() : void 0; if (!pos) { return; } if (_this.gWin != null) { _this.gWin.setPosition(pos); if (_this.opts) { _this.opts.position = pos; } _this.showWindow(); } if (_this.getGmarker() != null) { _this.initialMarkerVisibility = _this.getGmarker().getVisible(); _this.oldMarkerAnimation = _this.getGmarker().getAnimation(); return _this.getGmarker().setVisible(_this.isIconVisibleOnClick); } }; })(this); if (forceClick) { click(); } if (this.getGmarker()) { return this.googleMapsHandles.push(google.maps.event.addListener(this.getGmarker(), 'click', click)); } }; WindowChildModel.prototype.showWindow = function() { var compiled, templateScope; if (this.gWin != null) { if (this.scope.templateUrl) { $http.get(this.scope.templateUrl, { cache: $templateCache }).then((function(_this) { return function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = $compile(content.data)(templateScope); return _this.gWin.setContent(compiled[0]); }; })(this)); } else if (this.scope.template) { templateScope = this.scope.$new(); if (angular.isDefined(this.scope.templateParameter)) { templateScope.parameter = this.scope.templateParameter; } compiled = $compile(this.scope.template)(templateScope); this.gWin.setContent(compiled[0]); } if (!this.gWin.isOpen()) { this.gWin.open(this.mapCtrl, this.getGmarker() ? this.getGmarker() : void 0); return this.model.show = this.gWin.isOpen(); } } }; WindowChildModel.prototype.hideWindow = function() { if ((this.gWin != null) && this.gWin.isOpen()) { return this.gWin.close(); } }; WindowChildModel.prototype.getLatestPosition = function(overridePos) { if ((this.gWin != null) && (this.getGmarker() != null) && !overridePos) { return this.gWin.setPosition(this.getGmarker().getPosition()); } else { if (overridePos) { return this.gWin.setPosition(overridePos); } } }; 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, _ref; if (manualOverride == null) { manualOverride = false; } this.remove(); if ((this.scope != null) && ((_ref = this.scope) != null ? _ref.$$destroyed : void 0) && (this.needToManualDestroy || manualOverride)) { this.scope.$destroy(); } return self = void 0; }; return WindowChildModel; })(BaseObject); return WindowChildModel; } ]); }).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.models.parent".ns()).factory("CircleParentModel".ns(), [ 'Logger'.ns(), '$timeout', "GmapUtil".ns(), "EventsHelper".ns(), "CircleOptionsBuilder".ns(), function($log, $timeout, GmapUtil, EventsHelper, Builder) { var CircleParentModel; return CircleParentModel = (function(_super) { __extends(CircleParentModel, _super); CircleParentModel.include(GmapUtil); CircleParentModel.include(EventsHelper); function CircleParentModel(scope, element, attrs, map, DEFAULTS) { var circle, listeners; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; circle = new google.maps.Circle(this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { return circle.setOptions(_this.buildOpts(GmapUtil.getCoords(scope.center), scope.radius)); } }; })(this); this.props = this.props.concat([ { prop: 'center', isColl: true }, { prop: 'fill', isColl: true }, 'radius' ]); this.watchProps(); listeners = this.setEvents(circle, scope, scope); google.maps.event.addListener(circle, 'radius_changed', function() { return scope.$evalAsync(function() { return scope.radius = circle.getRadius(); }); }); google.maps.event.addListener(circle, 'center_changed', function() { return scope.$evalAsync(function() { if (angular.isDefined(scope.center.type)) { scope.center.coordinates[1] = circle.getCenter().lat(); return scope.center.coordinates[0] = circle.getCenter().lng(); } else { scope.center.latitude = circle.getCenter().lat(); return scope.center.longitude = circle.getCenter().lng(); } }); }); scope.$on("$destroy", (function(_this) { return function() { _this.removeEvents(listeners); return circle.setMap(null); }; })(this)); $log.info(this); } return CircleParentModel; })(Builder); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.models.parent".ns()).factory("DrawingManagerParentModel".ns(), [ 'Logger'.ns(), '$timeout', function($log, $timeout) { var DrawingManagerParentModel; return DrawingManagerParentModel = (function() { function DrawingManagerParentModel(scope, element, attrs, map) { var drawingManager; this.scope = scope; this.attrs = attrs; this.map = map; drawingManager = new google.maps.drawing.DrawingManager(this.scope.options); drawingManager.setMap(this.map); if (this.scope.control != null) { this.scope.control.getDrawingManager = (function(_this) { return function() { return drawingManager; }; })(this); } if (!this.scope["static"] && this.scope.options) { this.scope.$watch("options", (function(_this) { return function(newValue) { return drawingManager != null ? drawingManager.setOptions(newValue) : void 0; }; })(this), true); } scope.$on("$destroy", (function(_this) { return function() { drawingManager.setMap(null); return drawingManager = null; }; })(this)); } return DrawingManagerParentModel; })(); } ]); }).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("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapIMarkerParentModel", [ "uiGmapModelKey", "uiGmapLogger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope, element, attrs, map) { this.scope = scope; this.element = element; this.attrs = attrs; this.map = map; 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); 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(_this) { return function() { return _this.onDestroy(scope); }; })(this)); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope, equalityCheck) { if (equalityCheck == null) { equalityCheck = true; } return scope.$watch(propNameToWatch, (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }; })(this), equalityCheck); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) {}; 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".ns()).factory("IWindowParentModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(), "Logger".ns(), function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(GmapUtil); function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { IWindowParentModel.__super__.constructor.call(this, scope); this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.DEFAULTS = {}; if (scope.options != null) { this.DEFAULTS = scope.options; } } 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".ns()).factory("LayerParentModel".ns(), [ "BaseObject".ns(), "Logger".ns(), '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = __bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info("type attribute for the layer directive is mandatory. Layer creation aborted!!"); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.layer.setMap(this.gMap); } this.scope.$watch("show", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.layer.setMap(_this.gMap); } else { return _this.layer.setMap(null); } } }; })(this), true); this.scope.$watch("options", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.layer.setMap(null); _this.layer = null; return _this.createGoogleLayer(); } }; })(this), true); this.scope.$on("$destroy", (function(_this) { return function() { return _this.layer.setMap(null); }; })(this)); } 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); (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".ns()).factory("MapTypeParentModel".ns(), [ "BaseObject".ns(), "Logger".ns(), '$timeout', function(BaseObject, Logger, $timeout) { var MapTypeParentModel; MapTypeParentModel = (function(_super) { __extends(MapTypeParentModel, _super); function MapTypeParentModel(scope, element, attrs, gMap, $log) { this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.$log = $log != null ? $log : Logger; this.hideOverlay = __bind(this.hideOverlay, this); this.showOverlay = __bind(this.showOverlay, this); this.refreshMapType = __bind(this.refreshMapType, this); this.createMapType = __bind(this.createMapType, this); if (this.attrs.options == null) { this.$log.info("options attribute for the map-type directive is mandatory. Map type creation aborted!!"); return; } this.id = this.gMap.overlayMapTypesCount = this.gMap.overlayMapTypesCount + 1 || 0; this.doShow = true; this.createMapType(); if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.showOverlay(); } this.scope.$watch("show", (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.showOverlay(); } else { return _this.hideOverlay(); } } }; })(this), true); this.scope.$watch("options", (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); if (angular.isDefined(this.attrs.refresh)) { this.scope.$watch("refresh", (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.refreshMapType(); } }; })(this), true); } this.scope.$on("$destroy", (function(_this) { return function() { _this.hideOverlay(); return _this.mapType = null; }; })(this)); } MapTypeParentModel.prototype.createMapType = function() { if (this.scope.options.getTile != null) { this.mapType = this.scope.options; } else if (this.scope.options.getTileUrl != null) { this.mapType = new google.maps.ImageMapType(this.scope.options); } else { this.$log.info("options should provide either getTile or getTileUrl methods. Map type creation aborted!!"); return; } if (this.attrs.id && this.scope.id) { this.gMap.mapTypes.set(this.scope.id, this.mapType); if (!angular.isDefined(this.attrs.show)) { this.doShow = false; } } return this.mapType.layerId = this.id; }; MapTypeParentModel.prototype.refreshMapType = function() { this.hideOverlay(); this.mapType = null; this.createMapType(); if (this.doShow && (this.gMap != null)) { return this.showOverlay(); } }; MapTypeParentModel.prototype.showOverlay = function() { return this.gMap.overlayMapTypes.push(this.mapType); }; MapTypeParentModel.prototype.hideOverlay = function() { var found; found = false; return this.gMap.overlayMapTypes.forEach((function(_this) { return function(mapType, index) { if (!found && mapType.layerId === _this.id) { found = true; _this.gMap.overlayMapTypes.removeAt(index); } }; })(this)); }; return MapTypeParentModel; })(BaseObject); return MapTypeParentModel; } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapMarkersParentModel", [ "uiGmapIMarkerParentModel", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapMarkerChildModel", "uiGmap_async", "uiGmapClustererMarkerManager", "uiGmapMarkerManager", "$timeout", "uiGmapIMarker", "uiGmapPromise", "uiGmapGmapUtil", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, _async, ClustererMarkerManager, MarkerManager, $timeout, IMarker, uiGmapPromise, GmapUtil) { var MarkersParentModel; MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(GmapUtil); MarkersParentModel.include(ModelsWatcher); function MarkersParentModel(scope, element, attrs, map) { this.onDestroy = __bind(this.onDestroy, this); this.newChildMarker = __bind(this.newChildMarker, this); this.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; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map); self = this; this.scope.markerModels = new PropMap(); this.$log.info(this); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; this.setIdKey(scope); this.scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); this.watch('models', scope, !this.isTrue(attrs.modelsbyref)); 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) { if (scope.doCluster) { if (scope.clusterEvents) { this.clusterInternalOptions = _.once((function(_this) { return 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'); } }); } }; })(this))(); } 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.waitOrGo(this, (function(_this) { return function() { return _async.each(scope.models, function(model) { return _this.newChildMarker(model, scope); }, false).then(function() { _this.gMarkerManager.draw(); if (scope.fit) { return _this.gMarkerManager.fit(); } }); }; })(this)).then((function(_this) { return function() { return _this.existingPieces = void 0; }; })(this)); }; MarkersParentModel.prototype.reBuildMarkers = function(scope) { var _ref; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } if ((_ref = this.scope.markerModels) != null ? _ref.length : void 0) { this.onDestroy(scope); } return this.createMarkersFromScratch(scope); }; MarkersParentModel.prototype.pieceMeal = function(scope) { var doChunk; doChunk = this.existingPieces != null ? false : _async.defaultChunkSize; 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(_this) { return function(state) { var payload; payload = state; return _async.waitOrGo(_this, function() { return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } return _this.scope.markerModels.remove(child.id); } }, doChunk).then(function() { return _async.each(payload.adds, function(modelToAdd) { return _this.newChildMarker(modelToAdd, scope); }, doChunk); }).then(function() { return _async.each(payload.updates, function(update) { return _this.updateChild(update.child, update.model); }, doChunk); }).then(function() { if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) { _this.gMarkerManager.draw(); scope.markerModels = _this.scope.markerModels; if (scope.fit) { return _this.gMarkerManager.fit(); } } }); }).then(function() { return _this.existingPieces = void 0; }); }; })(this)); } 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, childScope, doDrawSelf, keys; if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.$log.info('child', child, 'markers', this.scope.markerModels); childScope = scope.$new(true); childScope.events = scope.events; keys = {}; _.each(IMarker.scopeKeys, function(v, k) { return keys[k] = scope[k]; }); child = new MarkerChildModel(childScope, model, keys, this.map, this.DEFAULTS, this.doClick, this.gMarkerManager, doDrawSelf = false); this.scope.markerModels.put(model[this.idKey], child); return child; }; MarkersParentModel.prototype.onDestroy = function(scope) { return _async.waitOrGo(this, (function(_this) { return function() { _.each(_this.scope.markerModels.values(), function(model) { if (model != null) { return model.destroy(false); } }); delete _this.scope.markerModels; if (_this.gMarkerManager != null) { _this.gMarkerManager.clear(); } _this.scope.markerModels = new PropMap(); return uiGmapPromise.resolve(); }; })(this)); }; 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; gMarkers = cluster.getMarkers().values(); mapped = gMarkers.map((function(_this) { return function(g) { return _this.scope.markerModels[g.key].model; }; })(this)); return { cluster: cluster, mapped: mapped }; }; return MarkersParentModel; })(IMarkerParentModel); return MarkersParentModel; } ]); }).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("uiGmapgoogle-maps.directives.api.models.parent").factory("uiGmapPolylinesParentModel", [ "$timeout", "uiGmapLogger", "uiGmapModelKey", "uiGmapModelsWatcher", "uiGmapPropMap", "uiGmapPolylineChildModel", "uiGmap_async", function($timeout, Logger, ModelKey, ModelsWatcher, PropMap, PolylineChildModel, _async) { var PolylinesParentModel; return PolylinesParentModel = (function(_super) { __extends(PolylinesParentModel, _super); PolylinesParentModel.include(ModelsWatcher); function PolylinesParentModel(scope, element, attrs, gMap, defaults) { var self; 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(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.models = void 0; this.firstTime = true; this.$log.info(this); this.watchOurScope(scope); this.createChildScopes(); } PolylinesParentModel.prototype.watch = function(scope, name, nameKey) { return scope.$watch(name, (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { _this[nameKey] = typeof newValue === 'function' ? newValue() : newValue; return _async.waitOrGo(_this, function() { return _async.each(_.values(_this.plurals), function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; }); }); } }; })(this)); }; PolylinesParentModel.prototype.watchModels = function(scope) { return scope.$watch('models', (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (_this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }; })(this), 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) { return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(_this.plurals.values(), function(model) { return model.destroy(); }).then(function() { if (doDelete) { delete _this.plurals; } _this.plurals = new PropMap(); if (doCreate) { return _this.createChildScopes(); } }); }; })(this)); }; PolylinesParentModel.prototype.watchDestroy = function(scope) { return scope.$on("$destroy", (function(_this) { return function() { return _this.rebuildAll(scope, false, true); }; })(this)); }; PolylinesParentModel.prototype.watchOurScope = function(scope) { return _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; return _this.watch(scope, name, nameKey); }; })(this)); }; 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) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; PolylinesParentModel.prototype.createAllNew = function(scope, isArray) { if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(scope.models, function(model) { return _this.createChild(model, _this.gMap); }); }; })(this)).then((function(_this) { return function() { _this.firstTime = false; return _this.existingPieces = void 0; }; })(this)); }; PolylinesParentModel.prototype.pieceMeal = function(scope, isArray) { var doChunk; if (isArray == null) { isArray = true; } doChunk = this.existingPieces != null ? false : _async.defaultChunkSize; 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(_this) { return function(state) { var payload; payload = state; return _async.waitOrGo(_this, function() { return _async.each(payload.removals, function(id) { var child; child = _this.plurals[id]; if (child != null) { child.destroy(); return _this.plurals.remove(id); } }).then(function() { return _async.each(payload.adds, function(modelToAdd) { return _this.createChild(modelToAdd, _this.gMap); }); }).then(function() { return _this.existingPieces = void 0; }); }); }; })(this)); } else { return this.rebuildAll(this.scope, true, true); } }; PolylinesParentModel.prototype.createChild = function(model, gMap) { var child, childScope; childScope = this.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); 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) { _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; 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); (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".ns()).factory("RectangleParentModel".ns(), [ "Logger".ns(), "GmapUtil".ns(), "EventsHelper".ns(), "RectangleOptionsBuilder".ns(), function($log, GmapUtil, EventsHelper, Builder) { var RectangleParentModel; return RectangleParentModel = (function(_super) { __extends(RectangleParentModel, _super); RectangleParentModel.include(GmapUtil); RectangleParentModel.include(EventsHelper); function RectangleParentModel(scope, element, attrs, map, DEFAULTS) { var bounds, clear, createBounds, dragging, fit, init, listeners, myListeners, rectangle, settingBoundsFromScope, updateBounds; this.scope = scope; this.attrs = attrs; this.map = map; this.DEFAULTS = DEFAULTS; bounds = void 0; dragging = false; myListeners = []; listeners = void 0; fit = (function(_this) { return function() { if (_this.isTrue(attrs.fit)) { return _this.fitMapBounds(_this.map, bounds); } }; })(this); createBounds = (function(_this) { return function() { var _ref, _ref1; if ((scope.bounds != null) && (((_ref = scope.bounds) != null ? _ref.sw : void 0) != null) && (((_ref1 = scope.bounds) != null ? _ref1.ne : void 0) != null) && _this.validateBoundPoints(scope.bounds)) { bounds = _this.convertBoundPoints(scope.bounds); return $log.info("new new bounds created: " + rectangle); } else if ((scope.bounds.getNorthEast != null) && (scope.bounds.getSouthWest != null)) { return bounds = scope.bounds; } else { if (typeof bound !== "undefined" && bound !== null) { return $log.error("Invalid bounds for newValue: " + (JSON.stringify(scope.bounds))); } } }; })(this); createBounds(); rectangle = new google.maps.Rectangle(this.buildOpts(bounds)); $log.info("rectangle created: " + rectangle); settingBoundsFromScope = false; updateBounds = (function(_this) { return function() { var b, ne, sw; b = rectangle.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return scope.$evalAsync(function(s) { if ((s.bounds != null) && (s.bounds.sw != null) && (s.bounds.ne != null)) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } if ((s.bounds.getNorthEast != null) && (s.bounds.getSouthWest != null)) { return s.bounds = b; } }); }; })(this); init = (function(_this) { return function() { fit(); _this.removeEvents(myListeners); myListeners.push(google.maps.event.addListener(rectangle, "dragstart", function() { return dragging = true; })); myListeners.push(google.maps.event.addListener(rectangle, "dragend", function() { dragging = false; return updateBounds(); })); return myListeners.push(google.maps.event.addListener(rectangle, "bounds_changed", function() { if (dragging) { return; } return updateBounds(); })); }; })(this); clear = (function(_this) { return function() { _this.removeEvents(myListeners); if (listeners != null) { _this.removeEvents(listeners); } return rectangle.setMap(null); }; })(this); if (bounds != null) { init(); } scope.$watch("bounds", (function(newValue, oldValue) { var isNew; if (_.isEqual(newValue, oldValue) && (bounds != null) || dragging) { return; } settingBoundsFromScope = true; if (newValue == null) { clear(); return; } if (bounds == null) { isNew = true; } else { fit(); } createBounds(); rectangle.setBounds(bounds); settingBoundsFromScope = false; if (isNew && (bounds != null)) { return init(); } }), true); this.setMyOptions = (function(_this) { return function(newVals, oldVals) { if (!_.isEqual(newVals, oldVals)) { if ((bounds != null) && (newVals != null)) { return rectangle.setOptions(_this.buildOpts(bounds)); } } }; })(this); this.props.push('bounds'); this.watchProps(this.props); if (attrs.events != null) { listeners = this.setEvents(rectangle, scope, scope); scope.$watch("events", (function(_this) { return function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (listeners != null) { _this.removeEvents(listeners); } return listeners = _this.setEvents(rectangle, scope, scope); } }; })(this)); } scope.$on("$destroy", (function(_this) { return function() { return clear(); }; })(this)); $log.info(this); } return RectangleParentModel; })(Builder); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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".ns()).factory("SearchBoxParentModel".ns(), [ "BaseObject".ns(), "Logger".ns(), "EventsHelper".ns(), '$timeout', '$http', '$templateCache', function(BaseObject, Logger, EventsHelper, $timeout, $http, $templateCache) { var SearchBoxParentModel; SearchBoxParentModel = (function(_super) { __extends(SearchBoxParentModel, _super); SearchBoxParentModel.include(EventsHelper); function SearchBoxParentModel(scope, element, attrs, gMap, ctrlPosition, template, $log) { var controlDiv; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.ctrlPosition = ctrlPosition; this.template = template; this.$log = $log != null ? $log : Logger; this.getBounds = __bind(this.getBounds, this); this.setBounds = __bind(this.setBounds, this); this.createSearchBox = __bind(this.createSearchBox, this); this.addToParentDiv = __bind(this.addToParentDiv, this); this.addAsMapControl = __bind(this.addAsMapControl, this); this.init = __bind(this.init, this); if (this.attrs.template == null) { this.$log.error("template attribute for the search-box directive is mandatory. Places Search Box creation aborted!!"); return; } controlDiv = angular.element('<div></div>'); controlDiv.append(this.template); this.input = controlDiv.find('input')[0]; this.init(); } SearchBoxParentModel.prototype.init = function() { this.createSearchBox(); if (this.attrs.parentdiv != null) { this.addToParentDiv(); } else { this.addAsMapControl(); } this.listener = google.maps.event.addListener(this.searchBox, 'places_changed', (function(_this) { return function() { return _this.places = _this.searchBox.getPlaces(); }; })(this)); this.listeners = this.setEvents(this.searchBox, this.scope, this.scope); this.$log.info(this); this.scope.$watch("options", (function(_this) { return function(newValue, oldValue) { if (angular.isObject(newValue)) { if (newValue.bounds != null) { return _this.setBounds(newValue.bounds); } } }; })(this), true); return this.scope.$on("$destroy", (function(_this) { return function() { return _this.searchBox = null; }; })(this)); }; SearchBoxParentModel.prototype.addAsMapControl = function() { return this.gMap.controls[google.maps.ControlPosition[this.ctrlPosition]].push(this.input); }; SearchBoxParentModel.prototype.addToParentDiv = function() { this.parentDiv = angular.element(document.getElementById(this.scope.parentdiv)); return this.parentDiv.append(this.input); }; SearchBoxParentModel.prototype.createSearchBox = function() { return this.searchBox = new google.maps.places.SearchBox(this.input, this.scope.options); }; SearchBoxParentModel.prototype.setBounds = function(bounds) { if (angular.isUndefined(bounds.isEmpty)) { this.$log.error("Error: SearchBoxParentModel setBounds. Bounds not an instance of LatLngBounds."); } else { if (bounds.isEmpty() === false) { if (this.searchBox != null) { return this.searchBox.setBounds(bounds); } } } }; SearchBoxParentModel.prototype.getBounds = function() { return this.searchBox.getBounds(); }; return SearchBoxParentModel; })(BaseObject); return SearchBoxParentModel; } ]); }).call(this); /* WindowsChildModel generator where there are many ChildModels to a parent. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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".ns()).factory("WindowsParentModel".ns(), [ "IWindowParentModel".ns(), "ModelsWatcher".ns(), "PropMap".ns(), "WindowChildModel".ns(), "Linked".ns(), "_async".ns(), "Logger".ns(), '$timeout', '$compile', '$http', '$templateCache', '$interpolate', 'uiGmapPromise', function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked, _async, $log, $timeout, $compile, $http, $templateCache, $interpolate, uiGmapPromise) { var WindowsParentModel; WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, gMap, markersScope) { var self; this.gMap = gMap; this.markersScope = markersScope; 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.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 = ['coords', 'template', 'templateUrl', 'templateParameter', 'isIconVisibleOnClick', 'closeClick', 'options', 'show']; _.each(this.scopePropNames, (function(_this) { return function(name) { return _this[name + 'Key'] = void 0; }; })(this)); this.linked = new Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.firstWatchModels = true; this.$log.info(self); this.parentScope = void 0; this.go(scope); } WindowsParentModel.prototype.go = function(scope) { this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }; })(this)); return this.createChildScopesWindows(); }; WindowsParentModel.prototype.watchModels = function(scope) { return scope.$watch('models', (function(_this) { return function(newValue, oldValue) { var doScratch; if (!_.isEqual(newValue, oldValue) || _this.firstWatchModels) { _this.firstWatchModels = false; if (_this.doRebuildAll || _this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { doScratch = _this.windows.length === 0; if (_this.existingPieces != null) { return _this.existingPieces.then(function() { return _this.createChildScopesWindows(doScratch); }); } else { return _this.createChildScopesWindows(doScratch); } } } }; })(this), true); }; 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) { return _async.waitOrGo(this, (function(_this) { return function() { return _async.each(_this.windows.values(), function(model) { return model.destroy(); }).then(function() { if (doDelete) { delete _this.windows; } _this.windows = new PropMap(); if (doCreate) { _this.createChildScopesWindows(); } return uiGmapPromise.resolve(); }); }; })(this)); }; WindowsParentModel.prototype.watchDestroy = function(scope) { return scope.$on("$destroy", (function(_this) { return function() { _this.firstWatchModels = true; _this.firstTime = true; return _this.rebuildAll(scope, false, true); }; })(this)); }; WindowsParentModel.prototype.watchOurScope = function(scope) { return _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey; nameKey = name + 'Key'; return _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; }; })(this)); }; WindowsParentModel.prototype.createChildScopesWindows = function(isCreatingFromScratch) { var modelsNotDefined, _ref, _ref1; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (this.markersScope === void 0 || (((_ref = this.markersScope) != null ? _ref.markerModels : void 0) === void 0 || ((_ref1 = this.markersScope) != null ? _ref1.models : void 0) === void 0))) { this.$log.error("No models to create windows from! Need direct models or models 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 = this.markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNewWindows(this.markersScope, true, 'markerModels', false); } else { return this.pieceMealWindows(this.markersScope, true, 'markerModels', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { this.setIdKey(scope); return scope.$watch('idKey', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }; })(this)); }; WindowsParentModel.prototype.createAllNewWindows = function(scope, hasGMarker, modelsPropToIterate, isArray) { 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.waitOrGo(this, (function(_this) { return function() { return _async.each(scope.models, function(model) { var gMarker, _ref; gMarker = hasGMarker ? (_ref = scope[modelsPropToIterate][[model[_this.idKey]]]) != null ? _ref.gMarker : void 0 : void 0; return _this.createWindow(model, gMarker, _this.gMap); }); }; })(this)).then((function(_this) { return function() { return _this.firstTime = false; }; })(this)); }; WindowsParentModel.prototype.pieceMealWindows = function(scope, hasGMarker, modelsPropToIterate, isArray) { var doChunk; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } doChunk = this.existingPieces != null ? false : _async.defaultChunkSize; 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(_this) { return function(state) { var payload; payload = state; return _async.waitOrGo(_this, function() { return _async.each(payload.removals, function(child) { if (child != null) { _this.windows.remove(child.id); if (child.destroy != null) { return child.destroy(true); } } }, doChunk).then(function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker, _ref; gMarker = (_ref = scope[modelsPropToIterate][modelToAdd[_this.idKey]]) != null ? _ref.gMarker : void 0; if (!gMarker) { throw "Gmarker undefined"; } return _this.createWindow(modelToAdd, gMarker, _this.gMap); }, doChunk); }); }).then(function() { return _this.existingPieces = void 0; })["catch"](function(e) { return $log.error("Error while pieceMealing Windows!"); }); }; })(this)); } 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, _ref, _ref1; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', (function(_this) { return function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }; })(this), true); fakeElement = { html: (function(_this) { return function() { return _this.interpolateContent(_this.linked.element.html(), model); }; })(this) }; this.DEFAULTS = this.markersScope ? model[this.optionsKey] || {} : this.DEFAULTS; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, (_ref = this.markersScope) != null ? (_ref1 = _ref.markerModels[model[this.idKey]]) != null ? _ref1.scope : void 0 : void 0, fakeElement, false, true); if (model[this.idKey] == null) { this.$log.error("Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.windows.put(model[this.idKey], child); return child; }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { _.each(this.scopePropNames, (function(_this) { return function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; })(this)); return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, interpModel, key, _i, _len, _ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = $interpolate(content); interpModel = {}; _ref = this.contentKeys; for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; interpModel[key] = model[key]; } return exp(interpModel); }; return WindowsParentModel; })(IWindowParentModel); return WindowsParentModel; } ]); }).call(this); (function() { angular.module("uiGmapgoogle-maps.directives.api").factory("uiGmapCircle", [ "uiGmapICircle", "uiGmapCircleParentModel", function(ICircle, CircleParentModel) { return _.extend(ICircle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new CircleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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("uiGmapgoogle-maps.directives.api").factory("uiGmapControl", [ "uiGmapIControl", "$http", "$templateCache", "$compile", "$controller", 'uiGmapGoogleMapApi', function(IControl, $http, $templateCache, $compile, $controller, GoogleMapApi) { var Control; return Control = (function(_super) { __extends(Control, _super); function Control() { this.link = __bind(this.link, this); Control.__super__.constructor.call(this); } Control.prototype.link = function(scope, element, attrs, ctrl) { return GoogleMapApi.then((function(_this) { return function(maps) { var index, position; if (angular.isUndefined(scope.template)) { _this.$log.error('mapControl: could not find a valid template property'); return; } index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0; position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER'; if (!maps.ControlPosition[position]) { _this.$log.error('mapControl: invalid position property'); return; } return IControl.mapPromise(scope, ctrl).then(function(map) { var control, controlDiv; control = void 0; controlDiv = angular.element('<div></div>'); return $http.get(scope.template, { cache: $templateCache }).success(function(template) { var templateCtrl, templateScope; templateScope = scope.$new(); controlDiv.append(template); if (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.children())(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]); }); }); }; })(this)); }; return Control; })(IControl); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).factory("DrawingManager".ns(), [ "IDrawingManager".ns(), "DrawingManagerParentModel".ns(), function(IDrawingManager, DrawingManagerParentModel) { return _.extend(IDrawingManager, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new DrawingManagerParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).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".ns()).factory('ApiFreeDrawPolygons'.ns(), [ "Logger".ns(), 'BaseObject'.ns(), "CtrlHandle".ns(), "DrawFreeHandChildModel".ns(), function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel) { var FreeDrawPolygons; return FreeDrawPolygons = (function(_super) { __extends(FreeDrawPolygons, _super); function FreeDrawPolygons() { this.link = __bind(this.link, this); return FreeDrawPolygons.__super__.constructor.apply(this, arguments); } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EMA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^' + 'GoogleMap'.ns(); FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=' }; FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) { return this.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var freeHand, listener; if (!scope.polygons) { return $log.error("No polygons to bind to!"); } if (!_.isArray(scope.polygons)) { return $log.error("Free Draw Polygons must be of type Array!"); } freeHand = new DrawFreeHandChildModel(map, scope.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); }); }); }); }; }; })(this)); }; return FreeDrawPolygons; })(BaseObject); } ]); }).call(this); (function() { angular.module("uiGmapgoogle-maps.directives.api").service("uiGmapICircle", [ function() { var DEFAULTS; DEFAULTS = {}; return { restrict: "EA", replace: true, require: '^' + 'uiGmapGoogleMap', scope: { center: "=center", radius: "=radius", stroke: "=stroke", fill: "=fill", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=", events: "=" } }; } ]); }).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".ns()).factory("IControl".ns(), [ "BaseObject".ns(), "Logger".ns(), "CtrlHandle".ns(), 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'.ns(); this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IControl; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).service("IDrawingManager".ns(), [ function() { return { restrict: "EA", replace: true, require: '^' + 'GoogleMap'.ns(), scope: { "static": "@", control: "=", options: "=" } }; } ]); }).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 __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".ns()).factory("IMarker".ns(), [ "Logger".ns(), "BaseObject".ns(), "CtrlHandle".ns(), function(Logger, BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(_super) { __extends(IMarker, _super); IMarker.scopeKeys = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; IMarker.keys = _.keys(IMarker.scopeKeys); IMarker.extend(CtrlHandle); function IMarker() { this.$log = Logger; this.restrict = 'EMA'; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.replace = true; this.scope = IMarker.scopeKeys; } 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".ns()).factory("IPolygon".ns(), [ "GmapUtil".ns(), "BaseObject".ns(), "Logger".ns(), "CtrlHandle".ns(), function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolygon; return IPolygon = (function(_super) { __extends(IPolygon, _super); IPolygon.include(GmapUtil); IPolygon.extend(CtrlHandle); function IPolygon() {} IPolygon.prototype.restrict = "EMA"; IPolygon.prototype.replace = true; IPolygon.prototype.require = '^' + 'GoogleMap'.ns(); IPolygon.prototype.scope = { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", fill: "=", icons: "=icons", visible: "=", "static": "=", events: "=", zIndex: "=zindex", fit: "=", control: "=control" }; IPolygon.prototype.DEFAULTS = {}; IPolygon.prototype.$log = Logger; return IPolygon; })(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".ns()).factory("IPolyline".ns(), [ "GmapUtil".ns(), "BaseObject".ns(), "Logger".ns(), "CtrlHandle".ns(), 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 = "EMA"; IPolyline.prototype.replace = true; IPolyline.prototype.require = '^' + 'GoogleMap'.ns(); 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); (function() { angular.module("google-maps.directives.api".ns()).service("IRectangle".ns(), [ function() { "use strict"; var DEFAULTS; DEFAULTS = {}; return { restrict: "EMA", require: '^' + 'GoogleMap'.ns(), replace: true, scope: { bounds: "=", stroke: "=", clickable: "=", draggable: "=", editable: "=", fill: "=", visible: "=", events: "=" } }; } ]); }).call(this); /* - interface directive for all window(s) to derive 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("uiGmapgoogle-maps.directives.api").factory("uiGmapIWindow", [ "uiGmapBaseObject", "uiGmapChildEvents", "uiGmapLogger", "uiGmapCtrlHandle", function(BaseObject, ChildEvents, Logger, CtrlHandle) { var IWindow; return IWindow = (function(_super) { __extends(IWindow, _super); IWindow.include(ChildEvents); IWindow.extend(CtrlHandle); function IWindow() { this.restrict = 'EMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = '^' + 'GoogleMap'.ns(); this.replace = true; this.scope = { coords: '=coords', template: '=template', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options', control: '=control', show: '=show' }; this.$log = Logger; } 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("uiGmapgoogle-maps.directives.api").factory("uiGmapMap", [ "$timeout", '$q', "uiGmapLogger", "uiGmapGmapUtil", "uiGmapBaseObject", "uiGmapCtrlHandle", 'uiGmapIsReady', "uiGmapuuid", "uiGmapExtendGWin", "uiGmapExtendMarkerClusterer", "uiGmapGoogleMapsUtilV3", 'uiGmapGoogleMapApi', function($timeout, $q, $log, GmapUtil, BaseObject, CtrlHandle, IsReady, uuid, ExtendGWin, ExtendMarkerClusterer, GoogleMapsUtilV3, GoogleMapApi) { "use strict"; var DEFAULTS, Map, initializeItems; DEFAULTS = void 0; initializeItems = [GoogleMapsUtilV3, ExtendGWin, ExtendMarkerClusterer]; 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, retCtrl; retCtrl = void 0; $scope.$on('$destroy', function() { return IsReady.reset(); }); ctrlObj = CtrlHandle.handle($scope); $scope.ctrlType = 'Map'; $scope.deferred.promise.then(function() { return initializeItems.forEach(function(i) { return i.init(); }); }); ctrlObj.getMap = function() { return $scope.map; }; retCtrl = _.extend(this, ctrlObj); return retCtrl; }; this.controller = ["$scope", ctrlFn]; self = this; } Map.prototype.restrict = "EMA"; Map.prototype.transclude = true; Map.prototype.replace = false; Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>'; Map.prototype.scope = { center: "=", zoom: "=", dragging: "=", control: "=", options: "=", events: "=", eventOpts: "=", styles: "=", bounds: "=", update: '=' }; Map.prototype.link = function(scope, element, attrs) { var unbindCenterWatch; scope.idleAndZoomChanged = false; if (scope.center == null) { unbindCenterWatch = scope.$watch('center', (function(_this) { return function() { if (!scope.center) { return; } unbindCenterWatch(); return _this.link(scope, element, attrs); }; })(this)); return; } return GoogleMapApi.then((function(_this) { return function(maps) { var dragging, el, eventName, getEventHandler, mapOptions, opts, resolveSpawned, settingCenterFromScope, spawned, type, _m; DEFAULTS = { mapTypeId: maps.MapTypeId.ROADMAP }; 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), zoom: scope.zoom, bounds: scope.bounds }); _m = new google.maps.Map(el.find("div")[1], mapOptions); _m['_id'.ns()] = uuid.generate(); dragging = false; google.maps.event.addListenerOnce(_m, 'idle', function() { scope.deferred.resolve(_m); return resolveSpawned(); }); google.maps.event.addListener(_m, "dragstart", function() { var _ref; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { dragging = true; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); } }); google.maps.event.addListener(_m, "dragend", function() { var _ref; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { dragging = false; return scope.$evalAsync(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); } }); google.maps.event.addListener(_m, "drag", function() { var c, _ref, _ref1, _ref2, _ref3; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { c = _m.center; return $timeout(function() { var s; s = scope; 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(); } }, (_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? (_ref3 = _ref2.debounce) != null ? _ref3.dragMs : void 0 : void 0 : void 0); } }); google.maps.event.addListener(_m, "zoom_changed", function() { var _ref, _ref1, _ref2; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { if (scope.zoom !== _m.zoom) { return $timeout(function() { return scope.zoom = _m.zoom; }, (_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.zoomMs : void 0 : void 0); } } }); settingCenterFromScope = false; google.maps.event.addListener(_m, "center_changed", function() { var c, _ref, _ref1, _ref2; if (!((_ref = scope.update) != null ? _ref.lazy : void 0)) { c = _m.center; if (settingCenterFromScope) { return; } return $timeout(function() { var s; s = scope; 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(); } } } }, (_ref1 = scope.eventOpts) != null ? (_ref2 = _ref1.debounce) != null ? _ref2.centerMs : void 0 : void 0); } }); google.maps.event.addListener(_m, "idle", function() { var b, ne, sw; b = _m.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); return scope.$evalAsync(function(s) { var c, _ref; if ((_ref = s.update) != null ? _ref.lazy : void 0) { c = _m.center; 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()) { s.center.coordinates[0] = c.lng(); } } else { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { s.center.longitude = c.lng(); } } } if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } s.zoom = _m.zoom; return scope.idleAndZoomChanged = !scope.idleAndZoomChanged; }); }); 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); } } }; 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 (_.isEqual(newValue, oldValue)) { return; } return $timeout(function() { return _m.setZoom(newValue); }, 0, false); }); 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); }); return ['options', 'styles'].forEach(function(toWatch) { return scope.$watch(toWatch, function(newValue, oldValue) { var watchItem; watchItem = this.exp; if (_.isEqual(newValue, oldValue)) { return; } opts.options = newValue; if (_m != null) { return _m.setOptions(opts); } }); }, true); }; })(this)); }; 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("uiGmapgoogle-maps.directives.api").factory("uiGmapMarker", [ "uiGmapIMarker", "uiGmapMarkerChildModel", "uiGmapMarkerManager", function(IMarker, MarkerChildModel, MarkerManager) { var Marker; return Marker = (function(_super) { __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 _.extend(this, IMarker.handle($scope, $element)); } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { this.mapPromise = IMarker.mapPromise(scope, ctrl); this.mapPromise.then((function(_this) { return function(map) { var doClick, doDrawSelf, keys, m, trackModel; if (!_this.gMarkerManager) { _this.gMarkerManager = new MarkerManager(map); } keys = _.object(IMarker.keys, IMarker.keys); m = new MarkerChildModel(scope, scope, keys, map, {}, doClick = true, _this.gMarkerManager, doDrawSelf = false, trackModel = false); m.deferred.promise.then(function(gMarker) { return scope.deferred.resolve(gMarker); }); if (scope.control != null) { return scope.control.getGMarkers = _this.gMarkerManager.getGMarkers; } }; })(this)); return scope.$on('$destroy', (function(_this) { return function() { var _ref; if ((_ref = _this.gMarkerManager) != null) { _ref.clear(); } return _this.gMarkerManager = null; }; })(this)); }; return Marker; })(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("uiGmapgoogle-maps.directives.api").factory("uiGmapMarkers", [ "uiGmapIMarker", "uiGmapMarkersParentModel", "uiGmap_sync", function(IMarker, MarkersParentModel, _sync) { 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', modelsByRef: '=modelsbyref' }); this.$log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Markers'; return _.extend(this, IMarker.handle($scope, $element)); } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { var parentModel, ready; parentModel = void 0; ready = (function(_this) { return function() { if (scope.control != null) { scope.control.getGMarkers = function() { var _ref; return (_ref = parentModel.gMarkerManager) != null ? _ref.getGMarkers() : void 0; }; scope.control.getChildMarkers = function() { return parentModel.markerModels; }; } return scope.deferred.resolve(); }; })(this); return IMarker.mapPromise(scope, ctrl).then((function(_this) { return function(map) { var mapScope; mapScope = ctrl.getScope(); mapScope.$watch('idleAndZoomChanged', function() { return parentModel.gMarkerManager.draw(); }); parentModel = new MarkersParentModel(scope, element, attrs, map); return parentModel.existingPieces.then(function() { return ready(); }); }; })(this)); }; 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".ns()).factory("Polygon".ns(), [ "IPolygon".ns(), "$timeout", "array-sync".ns(), "PolygonChildModel".ns(), function(IPolygon, $timeout, arraySync, PolygonChild) { var Polygon; return Polygon = (function(_super) { __extends(Polygon, _super); function Polygon() { this.link = __bind(this.link, this); return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.link = function(scope, element, attrs, mapCtrl) { var children, promise; children = []; promise = IPolygon.mapPromise(scope, mapCtrl); if (scope.control != null) { scope.control.getInstance = this; scope.control.polygons = children; scope.control.promise = promise; } return promise.then((function(_this) { return function(map) { return children.push(new PolygonChild(scope, attrs, map, _this.DEFAULTS)); }; })(this)); }; return Polygon; })(IPolygon); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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".ns()).factory("Polyline".ns(), [ "IPolyline".ns(), "$timeout", "array-sync".ns(), "PolylineChildModel".ns(), function(IPolyline, $timeout, arraySync, PolylineChildModel) { var Polyline; return Polyline = (function(_super) { __extends(Polyline, _super); function Polyline() { this.link = __bind(this.link, this); return Polyline.__super__.constructor.apply(this, arguments); } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { 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(_this) { return function(map) { return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS); }; })(this)); }; return Polyline; })(IPolyline); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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".ns()).factory("Polylines".ns(), [ "IPolyline".ns(), "$timeout", "array-sync".ns(), "PolylinesParentModel".ns(), 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) { 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(_this) { return function(map) { return new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS); }; })(this)); }; return Polylines; })(IPolyline); } ]); }).call(this); (function() { angular.module("google-maps.directives.api".ns()).factory("Rectangle".ns(), [ "Logger".ns(), "GmapUtil".ns(), "IRectangle".ns(), "RectangleParentModel".ns(), function($log, GmapUtil, IRectangle, RectangleParentModel) { return _.extend(IRectangle, { link: function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new RectangleParentModel(scope, element, attrs, map); }; })(this)); } }); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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("uiGmapgoogle-maps.directives.api").factory("uiGmapWindow", [ "uiGmapIWindow", "uiGmapGmapUtil", "uiGmapWindowChildModel", function(IWindow, GmapUtil, WindowChildModel) { var Window; return Window = (function(_super) { __extends(Window, _super); Window.include(GmapUtil); function Window() { this.link = __bind(this.link, this); Window.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; this.$log.info(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var markerCtrl, markerScope; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; this.mapPromise = IWindow.mapPromise(scope, ctrls[0]); return this.mapPromise.then((function(_this) { return function(mapCtrl) { var isIconVisibleOnClick; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } if (!markerCtrl) { _this.init(scope, element, isIconVisibleOnClick, mapCtrl); return; } return markerScope.deferred.promise.then(function(gMarker) { return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope); }); }; })(this)); }; Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) { var childWindow, defaults, gMarker, hasScopeCoords, opts; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && this.validateCoords(scope.coords); if ((markerScope != null ? markerScope['getGMarker'] : void 0) != null) { gMarker = markerScope.getGMarker(); } opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults; if (mapCtrl != null) { childWindow = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, markerScope, element); this.childWindows.push(childWindow); scope.$on("$destroy", (function(_this) { return function() { _this.childWindows = _.withoutObjects(_this.childWindows, [childWindow], function(child1, child2) { return child1.scope.$id === child2.scope.$id; }); return _this.childWindows.length = 0; }; })(this)); } if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.gWin; }); }; })(this); scope.control.getChildWindows = (function(_this) { return function() { return _this.childWindows; }; })(this); scope.control.showWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.showWindow(); }); }; })(this); scope.control.hideWindow = (function(_this) { return function() { return _this.childWindows.map(function(child) { return child.hideWindow(); }); }; })(this); } if ((this.onChildCreation != null) && (childWindow != null)) { return this.onChildCreation(childWindow); } }; return Window; })(IWindow); } ]); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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("uiGmapgoogle-maps.directives.api").factory("uiGmapWindows", [ "uiGmapIWindow", "uiGmapWindowsParentModel", "uiGmapPromise", function(IWindow, WindowsParentModel, uiGmapPromise) { /* Windows directive where many windows map to the models property */ var Windows; return Windows = (function(_super) { __extends(Windows, _super); function Windows() { this.init = __bind(this.init, this); this.link = __bind(this.link, this); Windows.__super__.constructor.call(this); this.require = ['^' + 'uiGmapGoogleMap', '^?' + 'uiGmapMarkers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; this.scope.idKey = '=idkey'; this.scope.doRebuildAll = '=dorebuildall'; this.scope.models = '=models'; this.$log.debug(this); } Windows.prototype.link = function(scope, element, attrs, ctrls) { var mapScope, markerCtrl, markerScope; mapScope = ctrls[0].getScope(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; markerScope = markerCtrl != null ? markerCtrl.getScope() : void 0; return mapScope.deferred.promise.then((function(_this) { return function(map) { var promise, _ref; promise = (markerScope != null ? (_ref = markerScope.deferred) != null ? _ref.promise : void 0 : void 0) || uiGmapPromise.resolve(); return promise.then(function() { var pieces, _ref1; pieces = (_ref1 = _this.parentModel) != null ? _ref1.existingPieces : void 0; if (pieces) { return pieces.then(function() { return _this.init(scope, element, attrs, ctrls, map, markerScope); }); } else { return _this.init(scope, element, attrs, ctrls, map, markerScope); } }); }; })(this)); }; Windows.prototype.init = function(scope, element, attrs, ctrls, map, additionalScope) { var parentModel; parentModel = new WindowsParentModel(scope, element, attrs, ctrls, map, additionalScope); if (scope.control != null) { scope.control.getGWindows = (function(_this) { return function() { return parentModel.windows.map(function(child) { return child.gWin; }); }; })(this); return scope.control.getChildWindows = (function(_this) { return function() { return parentModel.windows; }; })(this); } }; 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("uiGmapgoogle-maps").directive("uiGmapGoogleMap", [ "uiGmapMap", function(Map) { return new Map(); } ]); }).call(this); /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps".ns()).directive("Marker".ns(), [ "$timeout", "Marker".ns(), 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".ns()).directive("Markers".ns(), [ "$timeout", "Markers".ns(), 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 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".ns()).directive("Polygon".ns(), [ 'Polygon'.ns(), function(Polygon) { return new Polygon(); } ]); }).call(this); /* @authors Julian Popescu - https://github.com/jpopesculian Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module("google-maps".ns()).directive("Circle".ns(), [ "Circle".ns(), function(Circle) { return Circle; } ]); }).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("uiGmapgoogle-maps").directive("uiGmapPolyline", [ "uiGmapPolyline", 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".ns()).directive("Polylines".ns(), [ "Polylines".ns(), function(Polylines) { return new Polylines(); } ]); }).call(this); /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Chentsu Lin - https://github.com/ChenTsuLin */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapRectangle", [ "uiGmapLogger", "uiGmapRectangle", function($log, Rectangle) { return Rectangle; } ]); }).call(this); /* @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapWindow", [ "$timeout", "$compile", "$http", "$templateCache", "uiGmapWindow", function($timeout, $compile, $http, $templateCache, Window) { return new Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); /* ! 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("uiGmapgoogle-maps").directive("uiGmapWindows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) { return new Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); /* ! 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("uiGmapgoogle-maps").directive("uiGmapLayer", [ "$timeout", "uiGmapLogger", "uiGmapLayerParentModel", function($timeout, Logger, LayerParentModel) { var Layer; Layer = (function() { function Layer() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", type: "=type", namespace: "=namespace", options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { if (scope.onCreated != null) { return new LayerParentModel(scope, element, attrs, map, scope.onCreated); } else { return new LayerParentModel(scope, element, attrs, map); } }; })(this)); }; return Layer; })(); return new Layer(); } ]); }).call(this); /* ! 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, [email protected] */ /* mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements */ (function() { angular.module("uiGmapgoogle-maps").directive("uiGmapMapControl", [ "uiGmapControl", function(Control) { return new Control(); } ]); }).call(this); (function() { angular.module("google-maps".ns()).directive("DrawingManager".ns(), [ "DrawingManager".ns(), function(DrawingManager) { return DrawingManager; } ]); }).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'.ns()).directive('FreeDrawPolygons'.ns(), [ 'ApiFreeDrawPolygons'.ns(), function(FreeDrawPolygons) { return new FreeDrawPolygons(); } ]); }).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("uiGmapgoogle-maps").directive("uiGmapMapType", [ "$timeout", "uiGmapLogger", "uiGmapMapTypeParentModel", function($timeout, Logger, MapTypeParentModel) { var MapType; MapType = (function() { function MapType() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", options: '=options', refresh: '=refresh', id: '@' }; } MapType.prototype.link = function(scope, element, attrs, mapCtrl) { return mapCtrl.getScope().deferred.promise.then((function(_this) { return function(map) { return new MapTypeParentModel(scope, element, attrs, map); }; })(this)); }; return MapType; })(); return new MapType(); } ]); }).call(this); /* @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready - Carrie Kengle - http://about.me/carrie */ /* Places Search Box directive This directive is used to create a Places Search Box. This directive creates a new scope. {attribute input required} HTMLInputElement {attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification) */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("google-maps".ns()).directive("SearchBox".ns(), [ "GoogleMapApi".ns(), "Logger".ns(), "SearchBoxParentModel".ns(), '$http', '$templateCache', function(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache) { var SearchBox; SearchBox = (function() { function SearchBox() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; this.require = '^' + 'GoogleMap'.ns(); this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-search\" ng-transclude></span>'; this.replace = true; this.scope = { template: '=template', position: '=position', options: '=options', events: '=events', parentdiv: '=parentdiv' }; } SearchBox.prototype.link = function(scope, element, attrs, mapCtrl) { return GoogleMapApi.then((function(_this) { return function(maps) { return $http.get(scope.template, { cache: $templateCache }).success(function(template) { return mapCtrl.getScope().deferred.promise.then(function(map) { var ctrlPosition; ctrlPosition = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_LEFT'; if (!maps.ControlPosition[ctrlPosition]) { _this.$log.error('searchBox: invalid position property'); return; } return new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, template); }); }); }; })(this)); }; return SearchBox; })(); return new SearchBox(); } ]); }).call(this); ;angular.module("google-maps.wrapped".ns()).service("uuid".ns(), function() { //BEGIN REPLACE /* Version: core-1.0 The MIT License: Copyright (c) 2012 LiosK. */ function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c}; //END REPLACE return UUID; });;// wrap the utility libraries needed in ./lib // http://google-maps-utility-library-v3.googlecode.com/svn/ angular.module('google-maps.wrapped'.ns()).service('GoogleMapsUtilV3'.ns(), function () { return { init: _.once(function () { //BEGIN REPLACE /*! angular-google-maps 2.0.7 2014-11-04 * AngularJS directives for Google Maps * git: https://github.com/angular-ui/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.nggmap-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.nggmap-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.nggmap-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.nggmap-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.nggmap-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); }; //END REPLACE window.InfoBox = InfoBox; window.Cluster = Cluster; window.ClusterIcon = ClusterIcon; window.MarkerClusterer = MarkerClusterer; window.MarkerLabel_ = MarkerLabel_; window.MarkerWithLabel = MarkerWithLabel; }) }; });;/** * Performance overrides on MarkerClusterer custom to Angular Google Maps * * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14. */ angular.module('google-maps.extensions'.ns()).service('ExtendMarkerClusterer'.ns(), function () { return { init: _.once(function () { (function () { var __hasProp = {}.hasOwnProperty, __extends = function (child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.NgMapCluster = (function (_super) { __extends(NgMapCluster, _super); function NgMapCluster(opts) { NgMapCluster.__super__.constructor.call(this, opts); this.markers_ = new 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 */ NgMapMarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { if (property !== 'constructor') this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; NgMapMarkerClusterer.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"); } }) ]; }; return NgMapMarkerClusterer; })(MarkerClusterer); }).call(this); }) }; });
src/components/DeleteTaskModalComponent.js
Zcyon/lait
'use strict'; import React from 'react'; require('styles//DeleteTaskModal.css'); let DeleteTaskModalComponent = (props) => ( <div id="modalConfirm" className="modal is-active"> <div className="modal-background" onClick={props.toggleModal}> </div> <div className="modal-content"> <div className="card is-fullwidth"> <div className="card-content"> <div className="content"> <h2 className="title is-2">Are you sure you want to delete this task?</h2> <br /> <div className="columns has-text-centered"> <div className="column"> <a className="button is-danger is-medium" onClick={props.toggleModal}>No, I take it back!</a> </div> <div className="column"> <a className="button is-primary is-medium" onClick={props.deleteTask}>Yes, delete this task</a> </div> </div> <div className="has-text-centered"> <small>(You can't undo this action)</small> </div> </div> </div> </div> </div> <button className="modal-close" onClick={props.toggleModal}></button> </div> ); DeleteTaskModalComponent.displayName = 'DeleteTaskModalComponent'; // Uncomment properties you need // DeleteTaskModalComponent.propTypes = {}; // DeleteTaskModalComponent.defaultProps = {}; export default DeleteTaskModalComponent;
src/components/AudioPlayer/svg/SpeakerIcon.js
littlewin-wang/mufly
import React from 'react' const SpeakerIcon = props => ( <svg width="5.36px" height="6.23px" viewBox="0 0 5.36 6.23" {...props}> <polygon fill-rule="evenodd" clip-rule="evenodd" fill="#3F413B" points="0.76,2.08 0,2.08 0,4.34 0.76,4.34 2.29,6.23 3.05,6.23 3.05,0 2.29,0 "/> <rect x="3.62" y="1.6" fill-rule="evenodd" clip-rule="evenodd" fill="#3F413B" width="0.6" height="3.02"/> <rect x="4.76" y="0.85" fill-rule="evenodd" clip-rule="evenodd" fill="#3F413B" width="0.6" height="4.53"/> </svg> ) export default SpeakerIcon
components/app.js
papettoTV/isyo
import React, { Component } from 'react'; import Main from './main' import Header from './header' export default class App extends Component { constructor(props) { super(props); this.state = { value: null, }; this.state.route = "Main"; } componentDidMount() { console.log("componentDidMount app"); } componentWillUnmount() { } viewChange(view){ console.log("call viewChange in app.js",view); // console.log(this.state); // this.setState(state); // var state = {route:view}; this.setState(state); } render(){ return( <div> <Header /> { this.props.children } </div> ) } }
src/js/CreateStepper/Content/BasicDataForm/CustomHandle.js
ludonow/ludo-beta-react
import React from 'react'; import styled from 'styled-components'; import RcSlider from 'rc-slider'; import RcTooltip from 'rc-tooltip'; import sliderHandleIcon from '../../../../images/slider-handle.png' const { Handle } = RcSlider; const HandleIconWrapper = styled.div` left: -130%; position: relative; top: -450%; img { width: 35px; } `; const CustomHandle = ({ dragging, index, value, ...restProps, }) =>( <RcTooltip defaultVisible={true} key={`custom-handle-tooltip-${index}`} overlay={`${value}天`} placement="top" prefixCls="custom-rc-slider-tooltip" visible={true} > <Handle value={value} {...restProps} > <HandleIconWrapper> <img src={sliderHandleIcon} /> </HandleIconWrapper> </Handle> </RcTooltip> ); export default CustomHandle;
src/js/components/pages/reset-password-2/index.js
athill/wimf
import React from 'react'; import { Field, reduxForm} from 'redux-form'; import { Alert, Button, Col, Form, Grid, Panel, Row } from 'react-bootstrap'; import { connect } from 'react-redux'; import { InputField, required, submit, validEmail } from '../../util/form'; import { passwordReset2 } from '../../../modules/user'; const validate = values => { const errors = {}; const requiredErrors = required(['email', 'password'], values); if (requiredErrors.length) { requiredErrors.forEach(field => errors[field] = `${field} is required`); return errors; } if (!validEmail(values.email)) { errors.email = 'Invalid email address' } if (values.password !== values.password_confirmation) { errors.password_confirmation = "Confirm password must match Password"; } return errors; }; const PasswordReset2 = ({ error, handleSubmit, invalid, submitting }) => ( <Grid fluid> <Row> <Col md={8} mdOffset={2}> <Panel header="Reset Password" bsStyle="default"> <Form horizontal onSubmit={handleSubmit(submit(passwordReset2))}> <Field type="hidden" name="token" component="input" /> <Field label="Email" name="email" type="email" component={InputField} /> <Field label="Password" name="password" type="password" component={InputField} /> <Field label="Confirm Password" name="password_confirmation" type="password" component={InputField} /> { error && <Alert bsStyle="danger">{ error }</Alert> } <Col md={4} mdOffset={4}> <Button type="submit" disabled={submitting || invalid}>Reset Password</Button> </Col> </Form> </Panel> </Col> </Row> </Grid> ); const mapStateToProps = () => { const [ url, token ] = window.location.href.split('?'); return { initialValues: { token: token || 'foo' } }; }; export default connect(mapStateToProps)(reduxForm({ form: 'password-reset-2', // a unique identifier for this form validate })(PasswordReset2));
view/src/components/ChartCard.js
reliablejs/reliable-master
import React from 'react'; import { Card, Spin } from 'antd'; import './chartCard.less'; class ChartCard extends React.Component { render () { return ( <Card className="chartcard" bodyStyle={{ padding: '20px 24px 8px 24px' }} > { <Spin spinning={this.props.loading}> <h3 className="title">{this.props.title}</h3> <div className="content">{this.props.content}</div> </Spin> } </Card> ); } } export default ChartCard;
test/specs/views/Card/Card-test.js
aabustamante/Semantic-UI-React
import faker from 'faker' import React from 'react' import { SUI } from 'src/lib' import Card from 'src/views/Card/Card' import CardContent from 'src/views/Card/CardContent' import CardDescription from 'src/views/Card/CardDescription' import CardGroup from 'src/views/Card/CardGroup' import CardHeader from 'src/views/Card/CardHeader' import CardMeta from 'src/views/Card/CardMeta' import * as common from 'test/specs/commonTests' import { sandbox } from 'test/utils' describe('Card', () => { common.isConformant(Card) common.hasSubComponents(Card, [CardContent, CardDescription, CardGroup, CardHeader, CardMeta]) common.hasUIClassName(Card) common.rendersChildren(Card) common.propKeyOnlyToClassName(Card, 'centered') common.propKeyOnlyToClassName(Card, 'fluid') common.propKeyOnlyToClassName(Card, 'link') common.propKeyOnlyToClassName(Card, 'raised') common.propValueOnlyToClassName(Card, 'color', SUI.COLORS) it('renders a <div> by default', () => { shallow(<Card />).should.have.tagName('div') }) describe('href', () => { it('renders an <a> with an href attr', () => { const url = faker.internet.url() const wrapper = shallow(<Card href={url} />) wrapper.should.have.tagName('a') wrapper.should.have.attr('href', url) }) }) describe('onClick', () => { it('renders <a> instead of <div>', () => { const handleClick = sandbox.spy() const wrapper = shallow(<Card onClick={handleClick} />) wrapper.should.have.tagName('a') }) }) describe('extra', () => { it('renders a CardContent', () => { const wrapper = shallow(<Card extra={faker.hacker.phrase()} />) wrapper.should.have.descendants('CardContent') }) }) })
hera/client/src/layouts/CoreLayout/CoreLayout.js
bottydim/detect-credit-card-fraud
import React from 'react'; import Header from '../../components/Header'; import classes from './CoreLayout.scss'; import '../../styles/core.scss'; export const CoreLayout = ({ children }) => ( <div className='container'> <Header /> <div className={classes.mainContainer}> {children} </div> </div> ); CoreLayout.propTypes = { children: React.PropTypes.element.isRequired }; export default CoreLayout;
js/components/about/AboutTab.js
kort/kort-reloaded
import React from 'react'; import { View, Text, StyleSheet, ScrollView, Image } from 'react-native'; import I18n from 'react-native-i18n'; import Config from '../../constants/Config'; const gitHubUrl = Config.KORT_GITHUB; const uservoiceUrl = Config.KORT_USERVOICE; const version = Config.KORT_VERSION; const kortUrl = Config.KORT_WEBSITE; const styles = StyleSheet.create({ scrollView: { marginBottom: 46, }, container: { flex: 1, padding: 20, }, containerAbout: { justifyContent: 'flex-start', alignItems: 'flex-start', }, textTitle: { textAlign: 'center', fontSize: 18, marginTop: 7, }, textSubTitle: { marginTop: 5, }, kortlogo: { alignSelf: 'center', marginTop: 7, height: 64, width: 64, }, hsrlogo: { marginTop: 5, height: 23, width: 87, }, }); const AboutTab = React.createClass({ getInitialState() { return { title: '', }; }, render() { return ( <ScrollView automaticallyAdjustContentInsets={false} scrollEventThrottle={200} style={styles.scrollView} > <View style={styles.container}> <View style={styles.containerAbout}> <Image style={styles.kortlogo} source={require('../../assets/img/kort-logo.png')} /> <Text style={styles.textTitle}>{I18n.t('about_version_title')}</Text> <Text style={styles.textSubTitle}>{version}</Text> <Text style={styles.textTitle}>{I18n.t('about_information_title')}</Text> <Text style={styles.textSubTitle}> {`${I18n.t('about_information_homepage')} ${kortUrl}`} </Text> <Text style={styles.textSubTitle}> {`${I18n.t('about_information_feedback')} ${uservoiceUrl}`} </Text> <Text style={styles.textSubTitle}> {`${I18n.t('about_information_bugs')} ${gitHubUrl}`} </Text> <Text style={styles.textTitle}>{I18n.t('about_developers_title')}</Text> <Text style={styles.textSubTitle}>Dominic Mülhaupt</Text> <Text style={styles.textSubTitle}>Marino Melchiori</Text> <Text style={styles.textSubTitle}>Jürg Hunziker</Text> <Text style={styles.textSubTitle}>Stefan Oderbolz</Text> <Text style={styles.textTitle}>{I18n.t('about_project_title')}</Text> <Text style={styles.textSubTitle}>Bachelorarbeit FS2016</Text> <Text style={styles.textSubTitle}>HSR Hochschule für Technik Rapperswil</Text> <Text style={styles.textSubTitle}> {I18n.t('about_project_advisor')} Prof. Stefan Keller </Text> <Image style={styles.hsrlogo} source={require('../../assets/img/hsr_logo.png')} /> <Text style={styles.textTitle}>{I18n.t('about_credits_title')}</Text> <Text style={styles.textSubTitle}>{I18n.t('about_credits_partner')} Liip AG</Text> <Text style={styles.textSubTitle}> {I18n.t('about_credits_tiledata')} https://github.com/manuelroth/maps </Text> <Text style={styles.textSubTitle}> {I18n.t('about_credits_markers')} https://mapicons.mapsmarker.com/ </Text> <Text style={styles.textTitle}>{I18n.t('about_legal_title')}</Text> <Text style={styles.textSubTitle}>{I18n.t('about_legal_message')}</Text> </View> </View> </ScrollView> ); }, }); module.exports = AboutTab;
src/routes/register/index.js
brytree/reach
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Register from './Register'; const title = 'New User Registration'; export default { path: '/register', action() { return { title, component: <Layout><Register title={title} /></Layout>, }; }, };
ajax/libs/jquery.fancytree/2.8.0/jquery.fancytree-all.js
dakshshah96/cdnjs
/*! * jquery.fancytree.js * Dynamic tree view control, with support for lazy loading of branches. * https://github.com/mar10/fancytree/ * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ /** Core Fancytree module. */ // Start of local namespace ;(function($, window, document, undefined) { "use strict"; // prevent duplicate loading if ( $.ui && $.ui.fancytree ) { $.ui.fancytree.warn("Fancytree: ignored duplicate include"); return; } /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; // consoleApply("assert", [!!cond, msg]); $.error("Fancytree assertion failed" + msg); } } _assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)"); function consoleApply(method, args){ var i, s, fn = window.console ? window.console[method] : null; if(fn){ try{ fn.apply(window.console, args); } catch(e) { // IE 8? s = ""; for( i=0; i<args.length; i++){ s += args[i]; } fn(s); } } } /*Return true if x is a FancytreeNode.*/ function _isNode(x){ return !!(x.tree && x.statusNodeType !== undefined); } /** Return true if dotted version string is equal or higher than requested version. * * See http://jsfiddle.net/mar10/FjSAN/ */ function isVersionAtLeast(dottedVersion, major, minor, patch){ var i, v, t, verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }), testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); }); for( i = 0; i < testParts.length; i++ ){ v = verParts[i] || 0; t = testParts[i] || 0; if( v !== t ){ return ( v > t ); } } return true; } /** Return a wrapper that calls sub.methodName() and exposes * this : tree * this._local : tree.ext.EXTNAME * this._super : base.methodName() */ function _makeVirtualFunction(methodName, tree, base, extension, extName){ // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName); // if(rexTestSuper && !rexTestSuper.test(func)){ // // extension.methodName() doesn't call _super(), so no wrapper required // return func; // } // Use an immediate function as closure var proxy = (function(){ var prevFunc = tree[methodName], // org. tree method or prev. proxy baseFunc = extension[methodName], // _local = tree.ext[extName], _super = function(){ return prevFunc.apply(tree, arguments); }, _superApply = function(args){ return prevFunc.apply(tree, args); }; // Return the wrapper function return function(){ var prevLocal = tree._local, prevSuper = tree._super, prevSuperApply = tree._superApply; try{ tree._local = _local; tree._super = _super; tree._superApply = _superApply; return baseFunc.apply(tree, arguments); }finally{ tree._local = prevLocal; tree._super = prevSuper; tree._superApply = prevSuperApply; } }; })(); // end of Immediate Function return proxy; } /** * Subclass `base` by creating proxy functions */ function _subclassObject(tree, base, extension, extName){ // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName); for(var attrName in extension){ if(typeof extension[attrName] === "function"){ if(typeof tree[attrName] === "function"){ // override existing method tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else if(attrName.charAt(0) === "_"){ // Create private methods in tree.ext.EXTENSION namespace tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else{ $.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName); } }else{ // Create member variables in tree.ext.EXTENSION namespace if(attrName !== "options"){ tree.ext[extName][attrName] = extension[attrName]; } } } } function _getResolvedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.resolve();}).promise(); }else{ return $.Deferred(function(){this.resolveWith(context, argArray);}).promise(); } } function _getRejectedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.reject();}).promise(); }else{ return $.Deferred(function(){this.rejectWith(context, argArray);}).promise(); } } function _makeResolveFunc(deferred, context){ return function(){ deferred.resolveWith(context); }; } function _getElementDataAsDict($el){ // Evaluate 'data-NAME' attributes with special treatment for 'data-json'. var d = $.extend({}, $el.data()), json = d.json; delete d.fancytree; // added to container by widget factory if( json ) { delete d.json; // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5) d = $.extend(d, json); } return d; } // TODO: use currying function _makeNodeTitleMatcher(s){ s = s.toLowerCase(); return function(node){ return node.title.toLowerCase().indexOf(s) >= 0; }; } function _makeNodeTitleStartMatcher(s){ var reMatch = new RegExp("^" + s, "i"); return function(node){ return reMatch.test(node.title); }; } var i, FT = null, // initialized below ENTITY_MAP = {"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;", "/": "&#x2F;"}, IGNORE_KEYCODES = { 16: true, 17: true, 18: true }, SPECIAL_KEYCODES = { 8: "backspace", 9: "tab", 10: "return", 13: "return", // 16: null, 17: null, 18: null, // ignore shift, ctrl, alt 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"}, MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" }, //boolean attributes that can be set with equivalent class names in the LI tags CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "), CLASS_ATTR_MAP = {}, // Top-level Fancytree node attributes, that can be set by dict NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "), NODE_ATTR_MAP = {}, // Attribute names that should NOT be added to node.data NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true}; for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; } for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; } /* ***************************************************************************** * FancytreeNode */ /** * Creates a new FancytreeNode * * @class FancytreeNode * @classdesc A FancytreeNode represents the hierarchical data model and operations. * * @param {FancytreeNode} parent * @param {NodeData} obj * * @property {Fancytree} tree The tree instance * @property {FancytreeNode} parent The parent node * @property {string} key Node id (must be unique inside the tree) * @property {string} title Display name (may contain HTML) * @property {object} data Contains all extra data that was passed on node creation * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br> * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array * to define a node that has no children. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property. * @property {string} extraClasses Addtional CSS classes, added to the node's `&lt;span>` * @property {boolean} folder Folder nodes have different default icons and click behavior.<br> * Note: Also non-folders may have children. * @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion. * @property {boolean} selected Use isSelected(), setSelected() to access this property. * @property {string} tooltip Alternative description used as hover banner */ function FancytreeNode(parent, obj){ var i, l, name, cl; this.parent = parent; this.tree = parent.tree; this.ul = null; this.li = null; // <li id='key' ftnode=this> tag this.statusNodeType = null; // if this is a temp. node to display the status of its parent this._isLoading = false; // if this node itself is loading this._error = null; // {message: '...'} if a load error occured this.data = {}; // TODO: merge this code with node.toDict() // copy attributes from obj object for(i=0, l=NODE_ATTRS.length; i<l; i++){ name = NODE_ATTRS[i]; this[name] = obj[name]; } // node.data += obj.data if(obj.data){ $.extend(this.data, obj.data); } // copy all other attributes to this.data.NAME for(name in obj){ if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = obj.NAME this.data[name] = obj[name]; } } // Fix missing key if( this.key == null ){ // test for null OR undefined if( this.tree.options.defaultKey ) { this.key = this.tree.options.defaultKey(this); _assert(this.key, "defaultKey() must return a unique key"); } else { this.key = "_" + (FT._nextNodeKey++); } } else { this.key = "" + this.key; // Convert to string (#217) } // Fix tree.activeNode // TODO: not elegant: we use obj.active as marker to set tree.activeNode // when loading from a dictionary. if(obj.active){ _assert(this.tree.activeNode === null, "only one active node allowed"); this.tree.activeNode = this; } if( obj.selected ){ // #186 this.tree.lastSelectedNode = this; } // TODO: handle obj.focus = true // Create child nodes this.children = null; cl = obj.children; if(cl && cl.length){ this._setChildren(cl); } // Add to key/ref map (except for root node) // if( parent ) { this.tree._callHook("treeRegisterNode", this.tree, true, this); // } } FancytreeNode.prototype = /** @lends FancytreeNode# */{ /* Return the direct child FancytreeNode with a given key, index. */ _findDirectChild: function(ptr){ var i, l, cl = this.children; if(cl){ if(typeof ptr === "string"){ for(i=0, l=cl.length; i<l; i++){ if(cl[i].key === ptr){ return cl[i]; } } }else if(typeof ptr === "number"){ return this.children[ptr]; }else if(ptr.parent === this){ return ptr; } } return null; }, // TODO: activate() // TODO: activateSilently() /* Internal helper called in recursive addChildren sequence.*/ _setChildren: function(children){ _assert(children && (!this.children || this.children.length === 0), "only init supported"); this.children = []; for(var i=0, l=children.length; i<l; i++){ this.children.push(new FancytreeNode(this, children[i])); } }, /** * Append (or insert) a list of child nodes. * * @param {NodeData[]} children array of child node definitions (also single child accepted) * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such). * If omitted, the new children are appended. * @returns {FancytreeNode} first child added * * @see FancytreeNode#applyPatch */ addChildren: function(children, insertBefore){ var i, l, pos, firstNode = null, nodeList = []; if($.isPlainObject(children) ){ children = [children]; } if(!this.children){ this.children = []; } for(i=0, l=children.length; i<l; i++){ nodeList.push(new FancytreeNode(this, children[i])); } firstNode = nodeList[0]; if(insertBefore == null){ this.children = this.children.concat(nodeList); }else{ insertBefore = this._findDirectChild(insertBefore); pos = $.inArray(insertBefore, this.children); _assert(pos >= 0, "insertBefore must be an existing child"); // insert nodeList after children[pos] this.children.splice.apply(this.children, [pos, 0].concat(nodeList)); } if( !this.parent || this.parent.ul || this.tr ){ // render if the parent was rendered (or this is a root node) this.render(); } if( this.tree.options.selectMode === 3 ){ this.fixSelection3FromEndNodes(); } return firstNode; }, /** * Append or prepend a node, or append a child node. * * This a convenience function that calls addChildren() * * @param {NodeData} node node definition * @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child') * @returns {FancytreeNode} new node */ addNode: function(node, mode){ if(mode === undefined || mode === "over"){ mode = "child"; } switch(mode){ case "after": return this.getParent().addChildren(node, this.getNextSibling()); case "before": return this.getParent().addChildren(node, this); case "firstChild": // Insert before the first child if any var insertBefore = (this.children ? this.children[0] : null); return this.addChildren(node, insertBefore); case "child": case "over": return this.addChildren(node); } _assert(false, "Invalid mode: " + mode); }, /** * Append new node after this. * * This a convenience function that calls addNode(node, 'after') * * @param {NodeData} node node definition * @returns {FancytreeNode} new node */ appendSibling: function(node){ return this.addNode(node, "after"); }, /** * Modify existing child nodes. * * @param {NodePatch} patch * @returns {$.Promise} * @see FancytreeNode#addChildren */ applyPatch: function(patch) { // patch [key, null] means 'remove' if(patch === null){ this.remove(); return _getResolvedPromise(this); } // TODO: make sure that root node is not collapsed or modified // copy (most) attributes to node.ATTR or node.data.ATTR var name, promise, v, IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global for(name in patch){ v = patch[name]; if( !IGNORE_MAP[name] && !$.isFunction(v)){ if(NODE_ATTR_MAP[name]){ this[name] = v; }else{ this.data[name] = v; } } } // Remove and/or create children if(patch.hasOwnProperty("children")){ this.removeChildren(); if(patch.children){ // only if not null and not empty list // TODO: addChildren instead? this._setChildren(patch.children); } // TODO: how can we APPEND or INSERT child nodes? } if(this.isVisible()){ this.renderTitle(); this.renderStatus(); } // Expand collapse (final step, since this may be async) if(patch.hasOwnProperty("expanded")){ promise = this.setExpanded(patch.expanded); }else{ promise = _getResolvedPromise(this); } return promise; }, /** Collapse all sibling nodes. * @returns {$.Promise} */ collapseSiblings: function() { return this.tree._callHook("nodeCollapseSiblings", this); }, /** Copy this node as sibling or child of `node`. * * @param {FancytreeNode} node source node * @param {string} [mode=child] 'before' | 'after' | 'child' * @param {Function} [map] callback function(NodeData) that could modify the new node * @returns {FancytreeNode} new */ copyTo: function(node, mode, map) { return node.addNode(this.toDict(true, map), mode); }, /** Count direct and indirect children. * * @param {boolean} [deep=true] pass 'false' to only count direct children * @returns {int} number of child nodes */ countChildren: function(deep) { var cl = this.children, i, l, n; if( !cl ){ return 0; } n = cl.length; if(deep !== false){ for(i=0, l=n; i<l; i++){ n += cl[i].countChildren(); } } return n; }, // TODO: deactivate() /** Write to browser console if debugLevel >= 2 (prepending node info) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.tree.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, /** Deprecated. * @deprecated since 2014-02-16. Use resetLazy() instead. */ discard: function(){ this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."); return this.resetLazy(); }, // TODO: expand(flag) /**Find all nodes that contain `match` in the title. * * @param {string | function(node)} match string to search for, of a function that * returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) * @see FancytreeNode#findAll */ findAll: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = []; this.visit(function(n){ if(match(n)){ res.push(n); } }); return res; }, /**Find first node that contains `match` in the title (not including self). * * @param {string | function(node)} match string to search for, of a function that * returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @example * <b>fat</b> text */ findFirst: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = null; this.visit(function(n){ if(match(n)){ res = n; return false; } }); return res; }, /* Apply selection state (internal use only) */ _changeSelectStatusAttrs: function (state) { var changed = false; switch(state){ case false: changed = ( this.selected || this.partsel ); this.selected = false; this.partsel = false; break; case true: changed = ( !this.selected || !this.partsel ); this.selected = true; this.partsel = true; break; case undefined: changed = ( this.selected || !this.partsel ); this.selected = false; this.partsel = true; break; default: _assert(false, "invalid state: " + state); } // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed); if( changed ){ this.renderStatus(); } return changed; }, /** * Fix selection status, after this node was (de)selected in multi-hier mode. * This includes (de)selecting all children. */ fixSelection3AfterClick: function() { var flag = this.isSelected(); // this.debug("fixSelection3AfterClick()"); this.visit(function(node){ node._changeSelectStatusAttrs(flag); }); this.fixSelection3FromEndNodes(); }, /** * Fix selection status for multi-hier mode. * Only end-nodes are considered to update the descendants branch and parents. * Should be called after this node has loaded new children or after * children have been modified using the API. */ fixSelection3FromEndNodes: function() { // this.debug("fixSelection3FromEndNodes()"); _assert(this.tree.options.selectMode === 3, "expected selectMode 3"); // Visit all end nodes and adjust their parent's `selected` and `partsel` // attributes. Return selection state true, false, or undefined. function _walk(node){ var i, l, child, s, state, allSelected,someSelected, children = node.children; if( children && children.length ){ // check all children recursively allSelected = true; someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // the selection state of a node is not relevant; we need the end-nodes s = _walk(child); if( s !== false ) { someSelected = true; } if( s !== true ) { allSelected = false; } } state = allSelected ? true : (someSelected ? undefined : false); }else{ // This is an end-node: simply report the status // state = ( node.unselectable ) ? undefined : !!node.selected; state = !!node.selected; } node._changeSelectStatusAttrs(state); return state; } _walk(this); // Update parent's state this.visitParents(function(node){ var i, l, child, state, children = node.children, allSelected = true, someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // When fixing the parents, we trust the sibling status (i.e. // we don't recurse) if( child.selected || child.partsel ) { someSelected = true; } if( !child.unselectable && !child.selected ) { allSelected = false; } } state = allSelected ? true : (someSelected ? undefined : false); node._changeSelectStatusAttrs(state); }); }, // TODO: focus() /** * Update node data. If dict contains 'children', then also replace * the hole sub tree. * @param {NodeData} dict * * @see FancytreeNode#addChildren * @see FancytreeNode#applyPatch */ fromDict: function(dict) { // copy all other attributes to this.data.xxx for(var name in dict){ if(NODE_ATTR_MAP[name]){ // node.NAME = dict.NAME this[name] = dict[name]; }else if(name === "data"){ // node.data += dict.data $.extend(this.data, dict.data); }else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = dict.NAME this.data[name] = dict[name]; } } if(dict.children){ // recursively set children and render this.removeChildren(); this.addChildren(dict.children); } this.renderTitle(); /* var children = dict.children; if(children === undefined){ this.data = $.extend(this.data, dict); this.render(); return; } dict = $.extend({}, dict); dict.children = undefined; this.data = $.extend(this.data, dict); this.removeChildren(); this.addChild(children); */ }, /** Return the list of child nodes (undefined for unexpanded lazy nodes). * @returns {FancytreeNode[] | undefined} */ getChildren: function() { if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes? return undefined; // Lazy node: unloaded, currently loading, or load error } return this.children; }, /** Return the first child node or null. * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.children ? this.children[0] : null; }, /** Return the 0-based child index. * @returns {int} */ getIndex: function() { // return this.parent.children.indexOf(this); return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7 }, /** Return the hierarchical child index (1-based, e.g. '3.2.4'). * @returns {string} */ getIndexHier: function(separator) { separator = separator || "."; var res = []; $.each(this.getParentList(false, true), function(i, o){ res.push(o.getIndex() + 1); }); return res.join(separator); }, /** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32". * @param {boolean} [excludeSelf=false] * @returns {string} */ getKeyPath: function(excludeSelf) { var path = [], sep = this.tree.options.keyPathSeparator; this.visitParents(function(n){ if(n.parent){ path.unshift(n.key); } }, !excludeSelf); return sep + path.join(sep); }, /** Return the last child of this node or null. * @returns {FancytreeNode | null} */ getLastChild: function() { return this.children ? this.children[this.children.length - 1] : null; }, /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... . * @returns {int} */ getLevel: function() { var level = 0, dtn = this.parent; while( dtn ) { level++; dtn = dtn.parent; } return level; }, /** Return the successor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getNextSibling: function() { // TODO: use indexOf, if available: (not in IE6) if( this.parent ){ var i, l, ac = this.parent.children; for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null if( ac[i] === this ){ return ac[i+1]; } } } return null; }, /** Return the parent node (null for the system root node). * @returns {FancytreeNode | null} */ getParent: function() { // TODO: return null for top-level nodes? return this.parent; }, /** Return an array of all parent nodes (top-down). * @param {boolean} [includeRoot=false] Include the invisible system root node. * @param {boolean} [includeSelf=false] Include the node itself. * @returns {FancytreeNode[]} */ getParentList: function(includeRoot, includeSelf) { var l = [], dtn = includeSelf ? this : this.parent; while( dtn ) { if( includeRoot || dtn.parent ){ l.unshift(dtn); } dtn = dtn.parent; } return l; }, /** Return the predecessor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getPrevSibling: function() { if( this.parent ){ var i, l, ac = this.parent.children; for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null if( ac[i] === this ){ return ac[i-1]; } } } return null; }, /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded). * @returns {boolean | undefined} */ hasChildren: function() { if(this.lazy){ if(this.children == null ){ // null or undefined: Not yet loaded return undefined; }else if(this.children.length === 0){ // Loaded, but response was empty return false; }else if(this.children.length === 1 && this.children[0].isStatusNode() ){ // Currently loading or load error return undefined; } return true; } return !!( this.children && this.children.length ); }, /** Return true if node has keyboard focus. * @returns {boolean} */ hasFocus: function() { return (this.tree.hasFocus() && this.tree.focusNode === this); }, /** Write to browser console if debugLevel >= 1 (prepending node info) * * @param {*} msg string or object or array of such */ info: function(msg){ if( this.tree.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /** Return true if node is active (see also FancytreeNode#isSelected). * @returns {boolean} */ isActive: function() { return (this.tree.activeNode === this); }, /** Return true if node is a direct child of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isChildOf: function(otherNode) { return (this.parent && this.parent === otherNode); }, /** Return true, if node is a direct or indirect sub node of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isDescendantOf: function(otherNode) { if(!otherNode || otherNode.tree !== this.tree){ return false; } var p = this.parent; while( p ) { if( p === otherNode ){ return true; } p = p.parent; } return false; }, /** Return true if node is expanded. * @returns {boolean} */ isExpanded: function() { return !!this.expanded; }, /** Return true if node is the first node of its parent's children. * @returns {boolean} */ isFirstSibling: function() { var p = this.parent; return !p || p.children[0] === this; }, /** Return true if node is a folder, i.e. has the node.folder attribute set. * @returns {boolean} */ isFolder: function() { return !!this.folder; }, /** Return true if node is the last node of its parent's children. * @returns {boolean} */ isLastSibling: function() { var p = this.parent; return !p || p.children[p.children.length-1] === this; }, /** Return true if node is lazy (even if data was already loaded) * @returns {boolean} */ isLazy: function() { return !!this.lazy; }, /** Return true if node is lazy and loaded. For non-lazy nodes always return true. * @returns {boolean} */ isLoaded: function() { return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node }, /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending. * @returns {boolean} */ isLoading: function() { return !!this._isLoading; }, /** * @deprecated since v2.4.0: Use isRootNode() instead */ isRoot: function() { return this.isRootNode(); }, /** Return true if this is the (invisible) system root node. * @returns {boolean} */ isRootNode: function() { return (this.tree.rootNode === this); }, /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive). * @returns {boolean} */ isSelected: function() { return !!this.selected; }, /** Return true if this node is a temporarily generated system node like * 'loading', or 'error' (node.statusNodeType contains the type). * @returns {boolean} */ isStatusNode: function() { return !!this.statusNodeType; }, /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node. * @returns {boolean} */ isTopLevel: function() { return (this.tree.rootNode === this.parent); }, /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false. * @returns {boolean} */ isUndefined: function() { return this.hasChildren() === undefined; // also checks if the only child is a status node }, /** Return true if all parent nodes are expanded. Note: this does not check * whether the node is scrolled into the visible part of the screen. * @returns {boolean} */ isVisible: function() { var i, l, parents = this.getParentList(false, false); for(i=0, l=parents.length; i<l; i++){ if( ! parents[i].expanded ){ return false; } } return true; }, /** Deprecated. * @deprecated since 2014-02-16: use load() instead. */ lazyLoad: function(discard) { this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."); return this.load(discard); }, /** * Load all children of a lazy node if neccessary. The *expanded* state is maintained. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. * @returns {$.Promise} */ load: function(forceReload) { var res, source, that = this; _assert( this.isLazy(), "load() requires a lazy node" ); // _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" ); if( !forceReload && !this.isUndefined() ) { return _getResolvedPromise(this); } if( this.isLoaded() ){ this.resetLazy(); // also collapses } // This method is also called by setExpanded() and loadKeyPath(), so we // have to avoid recursion. source = this.tree._triggerNodeEvent("lazyLoad", this); if( source === false ) { // #69 return _getResolvedPromise(this); } _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); res = this.tree._callHook("nodeLoadChildren", this, source); if( this.expanded ) { res.always(function(){ that.render(); }); } return res; }, /** Expand all parents and optionally scroll into visible area as neccessary. * Promise is resolved, when lazy loading and animations are done. * @param {object} [opts] passed to `setExpanded()`. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true} * @returns {$.Promise} */ makeVisible: function(opts) { var i, that = this, deferreds = [], dfd = new $.Deferred(), parents = this.getParentList(false, false), len = parents.length, effects = !(opts && opts.noAnimation === true), scroll = !(opts && opts.scrollIntoView === false); // Expand bottom-up, so only the top node is animated for(i = len - 1; i >= 0; i--){ // that.debug("pushexpand" + parents[i]); deferreds.push(parents[i].setExpanded(true, opts)); } $.when.apply($, deferreds).done(function(){ // All expands have finished // that.debug("expand DONE", scroll); if( scroll ){ that.scrollIntoView(effects).done(function(){ // that.debug("scroll DONE"); dfd.resolve(); }); } else { dfd.resolve(); } }); return dfd.promise(); }, /** Move this node to targetNode. * @param {FancytreeNode} targetNode * @param {string} mode <pre> * 'child': append this node as last child of targetNode. * This is the default. To be compatble with the D'n'd * hitMode, we also accept 'over'. * 'before': add this node as sibling before targetNode. * 'after': add this node as sibling after targetNode.</pre> * @param {function} [map] optional callback(FancytreeNode) to allow modifcations */ moveTo: function(targetNode, mode, map) { if(mode === undefined || mode === "over"){ mode = "child"; } var pos, prevParent = this.parent, targetParent = (mode === "child") ? targetNode : targetNode.parent; if(this === targetNode){ return; }else if( !this.parent ){ throw "Cannot move system root"; }else if( targetParent.isDescendantOf(this) ){ throw "Cannot move a node to its own descendant"; } // Unlink this node from current parent if( this.parent.children.length === 1 ) { if( this.parent === targetParent ){ return; // #258 } this.parent.children = this.parent.lazy ? [] : null; this.parent.expanded = false; } else { pos = $.inArray(this, this.parent.children); _assert(pos >= 0); this.parent.children.splice(pos, 1); } // Remove from source DOM parent // if(this.parent.ul){ // this.parent.ul.removeChild(this.li); // } // Insert this node to target parent's child list this.parent = targetParent; if( targetParent.hasChildren() ) { switch(mode) { case "child": // Append to existing target children targetParent.children.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0); targetParent.children.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0); targetParent.children.splice(pos+1, 0, this); break; default: throw "Invalid mode " + mode; } } else { targetParent.children = [ this ]; } // Parent has no <ul> tag yet: // if( !targetParent.ul ) { // // This is the parent's first child: create UL tag // // (Hidden, because it will be // targetParent.ul = document.createElement("ul"); // targetParent.ul.style.display = "none"; // targetParent.li.appendChild(targetParent.ul); // } // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded)) // if(this.li){ // targetParent.ul.appendChild(this.li); // }^ // Let caller modify the nodes if( map ){ targetNode.visit(map, true); } // Handle cross-tree moves if( this.tree !== targetNode.tree ) { // Fix node.tree for all source nodes // _assert(false, "Cross-tree move is not yet implemented."); this.warn("Cross-tree moveTo is experimantal!"); this.visit(function(n){ // TODO: fix selection state and activation, ... n.tree = targetNode.tree; }, true); } // A collaposed node won't re-render children, so we have to remove it manually // if( !targetParent.expanded ){ // prevParent.ul.removeChild(this.li); // } // Update HTML markup if( !prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) { targetParent.render(); } // TODO: fix selection state // TODO: fix active state /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel()); if ( opts.minExpandLevel >= ftnode.getLevel() ) { // tree.logDebug ("Force expand for %o", ftnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // DT issue #82: only if not initializing, because the children may not exist yet // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing ) // ftnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( ftnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return ftnode; */ }, /** Set focus relative to this node and optionally activate. * * @param {number} where The keyCode that would normally trigger this move, * e.g. `$.ui.keyCode.LEFT` would collapse the node if it * is expanded or move to the parent oterwise. * @param {boolean} [activate=true] * @returns {$.Promise} */ // navigate: function(where, activate) { // console.time("navigate") // this._navigate(where, activate) // console.timeEnd("navigate") // }, navigate: function(where, activate) { var i, parents, handled = true, KC = $.ui.keyCode, sib = null; // Navigate to node function _goto(n){ if( n ){ try { n.makeVisible(); } catch(e) {} // #272 // Node may still be hidden by a filter if( ! $(n.span).is(":visible") ) { n.debug("Navigate: skipping hidden node"); n.navigate(where, activate); return; } return activate === false ? n.setFocus() : n.setActive(); } } switch( where ) { case KC.BACKSPACE: if( this.parent && this.parent.parent ) { _goto(this.parent); } break; case KC.LEFT: if( this.expanded ) { this.setExpanded(false); _goto(this); } else if( this.parent && this.parent.parent ) { _goto(this.parent); } break; case KC.RIGHT: if( !this.expanded && (this.children || this.lazy) ) { this.setExpanded(); _goto(this); } else if( this.children && this.children.length ) { _goto(this.children[0]); } break; case KC.UP: sib = this.getPrevSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getPrevSibling(); } while( sib && sib.expanded && sib.children && sib.children.length ) { sib = sib.children[sib.children.length - 1]; } if( !sib && this.parent && this.parent.parent ){ sib = this.parent; } _goto(sib); break; case KC.DOWN: if( this.expanded && this.children && this.children.length ) { sib = this.children[0]; } else { parents = this.getParentList(false, true); for(i=parents.length-1; i>=0; i--) { sib = parents[i].getNextSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getNextSibling(); } if( sib ){ break; } } } _goto(sib); break; default: handled = false; } }, /** * Remove this node (not allowed for system root). */ remove: function() { return this.parent.removeChild(this); }, /** * Remove childNode from list of direct children. * @param {FancytreeNode} childNode */ removeChild: function(childNode) { return this.tree._callHook("nodeRemoveChild", this, childNode); }, /** * Remove all child nodes and descendents. This converts the node into a leaf.<br> * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy() * in order to trigger lazyLoad on next expand. */ removeChildren: function() { return this.tree._callHook("nodeRemoveChildren", this); }, /** * This method renders and updates all HTML markup that is required * to display this node in its current state.<br> * Note: * <ul> * <li>It should only be neccessary to call this method after the node object * was modified by direct access to its properties, because the common * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...) * already handle this. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus} * are implied. If changes are more local, calling only renderTitle() or * renderStatus() may be sufficient and faster. * <li>If a node was created/removed, node.render() must be called <i>on the parent</i>. * </ul> * * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed */ render: function(force, deep) { return this.tree._callHook("nodeRender", this, force, deep); }, /** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title). * @see Fancytree_Hooks#nodeRenderTitle */ renderTitle: function() { return this.tree._callHook("nodeRenderTitle", this); }, /** Update element's CSS classes according to node state. * @see Fancytree_Hooks#nodeRenderStatus */ renderStatus: function() { return this.tree._callHook("nodeRenderStatus", this); }, /** * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad * event is triggered on next expand. */ resetLazy: function() { this.removeChildren(); this.expanded = false; this.lazy = true; this.children = undefined; this.renderStatus(); }, /** Schedule activity for delayed execution (cancel any pending request). * scheduleAction('cancel') will only cancel a pending request (if any). * @param {string} mode * @param {number} ms */ scheduleAction: function(mode, ms) { if( this.tree.timer ) { clearTimeout(this.tree.timer); // this.tree.debug("clearTimeout(%o)", this.tree.timer); } this.tree.timer = null; var self = this; // required for closures switch (mode) { case "cancel": // Simply made sure that timer was cleared break; case "expand": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger expand"); self.setExpanded(true); }, ms); break; case "activate": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger activate"); self.setActive(true); }, ms); break; default: throw "Invalid mode " + mode; } // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer); }, /** * * @param {boolean | PlainObject} [effects=false] animation options. * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in * any case, even if `this` is outside the scroll pane. * @returns {$.Promise} */ scrollIntoView: function(effects, options) { if( options !== undefined && _isNode(options) ) { this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."); options = {topNode: options}; } // this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent); // this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container; var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop, opts = $.extend({ effects: (effects === true) ? {duration: 200, queue: false} : effects, scrollOfs: this.tree.options.scrollOfs, scrollParent: this.tree.options.scrollParent || this.tree.$container, topNode: null }, options), dfd = new $.Deferred(), that = this, nodeHeight = $(this.span).height(), $container = $(opts.scrollParent), topOfs = opts.scrollOfs.top || 0, bottomOfs = opts.scrollOfs.bottom || 0, containerHeight = $container.height(),// - topOfs - bottomOfs, scrollTop = $container.scrollTop(), $animateTarget = $container, isParentWindow = $container[0] === window, topNode = opts.topNode || null, newScrollTop = null; // this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs); // _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets if( !$(this.span).is(":visible") ) { // We cannot calc offsets for hidden elements this.warn("scrollIntoView(): node is invisible."); return _getResolvedPromise(); } if( isParentWindow ) { nodeY = $(this.span).offset().top; topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0; $animateTarget = $("html,body"); } else { _assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body."); containerOffsetTop = $container.offset().top, nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0; horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight)); containerHeight -= horzScrollbarHeight; } // this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight); if( nodeY < (scrollTop + topOfs) ){ // Node is above visible container area newScrollTop = nodeY - topOfs; // this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop); }else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){ newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs; // this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop); // If a topNode was passed, make sure that it is never scrolled // outside the upper border if(topNode){ _assert(topNode.isRoot() || $(topNode.span).is(":visible"), "topNode must be visible"); if( topNodeY < newScrollTop ){ newScrollTop = topNodeY - topOfs; // this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop); } } } if(newScrollTop !== null){ // this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop); if(opts.effects){ opts.effects.complete = function(){ dfd.resolveWith(that); }; $animateTarget.stop(true).animate({ scrollTop: newScrollTop }, opts.effects); }else{ $animateTarget[0].scrollTop = newScrollTop; dfd.resolveWith(this); } }else{ dfd.resolveWith(this); } return dfd.promise(); }, /**Activate this node. * @param {boolean} [flag=true] pass false to deactivate * @param {object} [opts] additional options. Defaults to {noEvents: false} * @returns {$.Promise} */ setActive: function(flag, opts){ return this.tree._callHook("nodeSetActive", this, flag, opts); }, /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done. * @param {boolean} [flag=true] pass false to collapse * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} */ setExpanded: function(flag, opts){ return this.tree._callHook("nodeSetExpanded", this, flag, opts); }, /**Set keyboard focus to this node. * @param {boolean} [flag=true] pass false to blur * @see Fancytree#setFocus */ setFocus: function(flag){ return this.tree._callHook("nodeSetFocus", this, flag); }, /**Select this node, i.e. check the checkbox. * @param {boolean} [flag=true] pass false to deselect */ setSelected: function(flag){ return this.tree._callHook("nodeSetSelected", this, flag); }, /**Mark a lazy node as 'error', 'loading', or 'ok'. * @param {string} status 'error', 'ok' * @param {string} [message] * @param {string} [details] */ setStatus: function(status, message, details){ return this.tree._callHook("nodeSetStatus", this, status, message, details); }, /**Rename this node. * @param {string} title */ setTitle: function(title){ this.title = title; this.renderTitle(); }, /**Sort child list by title. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title). * @param {boolean} [deep=false] pass true to sort all descendant nodes */ sortChildren: function(cmp, deep) { var i,l, cl = this.children; if( !cl ){ return; } cmp = cmp || function(a, b) { var x = a.title.toLowerCase(), y = b.title.toLowerCase(); return x === y ? 0 : x > y ? 1 : -1; }; cl.sort(cmp); if( deep ){ for(i=0, l=cl.length; i<l; i++){ if( cl[i].children ){ cl[i].sortChildren(cmp, "$norender$"); } } } if( deep !== "$norender$" ){ this.render(); } }, /** Convert node (or whole branch) into a plain object. * * The result is compatible with node.addChildren(). * * @param {boolean} [recursive=false] include child nodes * @param {function} [callback] callback(dict) is called for every node, in order to allow modifications * @returns {NodeData} */ toDict: function(recursive, callback) { var i, l, node, dict = {}, self = this; $.each(NODE_ATTRS, function(i, a){ if(self[a] || self[a] === false){ dict[a] = self[a]; } }); if(!$.isEmptyObject(this.data)){ dict.data = $.extend({}, this.data); if($.isEmptyObject(dict.data)){ delete dict.data; } } if( callback ){ callback(dict); } if( recursive ) { if(this.hasChildren()){ dict.children = []; for(i=0, l=this.children.length; i<l; i++ ){ node = this.children[i]; if( !node.isStatusNode() ){ dict.children.push(node.toDict(true, callback)); } } }else{ // dict.children = null; } } return dict; }, /** Flip expanded status. */ toggleExpanded: function(){ return this.tree._callHook("nodeToggleExpanded", this); }, /** Flip selection status. */ toggleSelected: function(){ return this.tree._callHook("nodeToggleSelected", this); }, toString: function() { return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>"; }, /** Call fn(node) for all child nodes.<br> * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visit: function(fn, includeSelf) { var i, l, res = true, children = this.children; if( includeSelf === true ) { res = fn(this); if( res === false || res === "skip" ){ return res; } } if(children){ for(i=0, l=children.length; i<l; i++){ res = children[i].visit(fn, true); if( res === false ){ break; } } } return res; }, /** Call fn(node) for all child nodes and recursively load lazy children.<br> * <b>Note:</b> If you need this method, you probably should consider to review * your architecture! Recursivley loading nodes is a perfect way for lazy * programmers to flood the server with requests ;-) * * @param {function} [fn] optional callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {$.Promise} */ visitAndLoad: function(fn, includeSelf, _recursion) { var dfd, res, loaders, node = this; // node.debug("visitAndLoad"); if( fn && includeSelf === true ) { res = fn(node); if( res === false || res === "skip" ) { return _recursion ? res : _getResolvedPromise(); } } if( !node.children && !node.lazy ) { return _getResolvedPromise(); } dfd = new $.Deferred(); loaders = []; // node.debug("load()..."); node.load().done(function(){ // node.debug("load()... done."); for(var i=0, l=node.children.length; i<l; i++){ res = node.children[i].visitAndLoad(fn, true, true); if( res === false ) { dfd.reject(); break; } else if ( res !== "skip" ) { loaders.push(res); // Add promise to the list } } $.when.apply(this, loaders).then(function(){ dfd.resolve(); }); }); return dfd.promise(); }, /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitParents: function(fn, includeSelf) { // Visit parent nodes (bottom up) if(includeSelf && fn(this) === false){ return false; } var p = this.parent; while( p ) { if(fn(p) === false){ return false; } p = p.parent; } return true; }, /** Write warning to browser console (prepending node info) * * @param {*} msg string or object or array of such */ warn: function(msg){ Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }; /* ***************************************************************************** * Fancytree */ /** * Construct a new tree object. * * @class Fancytree * @classdesc The controller behind a fancytree. * This class also contains 'hook methods': see {@link Fancytree_Hooks}. * * @param {Widget} widget * * @property {FancytreeOptions} options * @property {FancytreeNode} rootNode * @property {FancytreeNode} activeNode * @property {FancytreeNode} focusNode * @property {jQueryObject} $div * @property {object} widget * @property {object} ext * @property {object} data * @property {object} options * @property {string} _id * @property {string} statusClassPropName * @property {string} ariaPropName * @property {string} nodeContainerAttrName * @property {string} $container * @property {FancytreeNode} lastSelectedNode */ function Fancytree(widget) { this.widget = widget; this.$div = widget.element; this.options = widget.options; if( this.options ) { if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) { this.options.lazyLoad = function() { FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."); return widget.options.lazyload.apply(this, arguments); }; } if( $.isFunction(this.options.loaderror) ) { $.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."); } if( this.options.fx !== undefined ) { FT.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30."); } } this.ext = {}; // Active extension instances // allow to init tree.data.foo from <div data-foo=''> this.data = _getElementDataAsDict(this.$div); this._id = $.ui.fancytree._nextId++; this._ns = ".fancytree-" + this._id; // append for namespaced events this.activeNode = null; this.focusNode = null; this._hasFocus = null; this.lastSelectedNode = null; this.systemFocusElement = null; this.lastQuicksearchTerm = ""; this.lastQuicksearchTime = 0; this.statusClassPropName = "span"; this.ariaPropName = "li"; this.nodeContainerAttrName = "li"; // Remove previous markup if any this.$div.find(">ul.fancytree-container").remove(); // Create a node without parent. var fakeParent = { tree: this }, $ul; this.rootNode = new FancytreeNode(fakeParent, { title: "root", key: "root_" + this._id, children: null, expanded: true }); this.rootNode.parent = null; // Create root markup $ul = $("<ul>", { "class": "ui-fancytree fancytree-container" }).appendTo(this.$div); this.$container = $ul; this.rootNode.ul = $ul[0]; if(this.options.debugLevel == null){ this.options.debugLevel = FT.debugLevel; } // Add container to the TAB chain // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1"); if(this.options.aria){ this.$container .attr("role", "tree") .attr("aria-multiselectable", true); } } Fancytree.prototype = /** @lends Fancytree# */{ /* Return a context object that can be re-used for _callHook(). * @param {Fancytree | FancytreeNode | EventData} obj * @param {Event} originalEvent * @param {Object} extra * @returns {EventData} */ _makeHookContext: function(obj, originalEvent, extra) { var ctx, tree; if(obj.node !== undefined){ // obj is already a context object if(originalEvent && obj.originalEvent !== originalEvent){ $.error("invalid args"); } ctx = obj; }else if(obj.tree){ // obj is a FancytreeNode tree = obj.tree; ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent }; }else if(obj.widget){ // obj is a Fancytree ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent }; }else{ $.error("invalid args"); } if(extra){ $.extend(ctx, extra); } return ctx; }, /* Trigger a hook function: funcName(ctx, [...]). * * @param {string} funcName * @param {Fancytree|FancytreeNode|EventData} contextObject * @param {any} [_extraArgs] optional additional arguments * @returns {any} */ _callHook: function(funcName, contextObject, _extraArgs) { var ctx = this._makeHookContext(contextObject), fn = this[funcName], args = Array.prototype.slice.call(arguments, 2); if(!$.isFunction(fn)){ $.error("_callHook('" + funcName + "') is not a function"); } args.unshift(ctx); // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args); return fn.apply(this, args); }, /* Check if current extensions dependencies are met and throw an error if not. * * This method may be called inside the `treeInit` hook for custom extensions. * * @param {string} extension name of the required extension * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter) * @param {string} [message] optional error message (defaults to a descriptve error message) */ _requireExtension: function(name, required, before, message) { before = !!before; var thisName = this._local.name, extList = this.options.extensions, isBefore = $.inArray(name, extList) < $.inArray(thisName, extList), isMissing = required && this.ext[name] == null, badOrder = !isMissing && before != null && (before !== isBefore); _assert(thisName && thisName !== name); if( isMissing || badOrder ){ if( !message ){ if( isMissing || required ){ message = "'" + thisName + "' extension requires '" + name + "'"; if( badOrder ){ message += " to be registered " + (before ? "before" : "after") + " itself"; } }else{ message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`"; } } $.error(message); return false; } return true; }, /** Activate node with a given key and fire focus and activate events. * * A prevously activated node will be deactivated. * If activeVisible option is set, all parents will be expanded as necessary. * Pass key = false, to deactivate the current node only. * @param {string} key * @returns {FancytreeNode} activated node (null, if not found) */ activateKey: function(key) { var node = this.getNodeByKey(key); if(node){ node.setActive(); }else if(this.activeNode){ this.activeNode.setActive(false); } return node; }, /** (experimental) * * @param {Array} patchList array of [key, NodePatch] arrays * @returns {$.Promise} resolved, when all patches have been applied * @see TreePatch */ applyPatch: function(patchList) { var dfd, i, p2, key, patch, node, patchCount = patchList.length, deferredList = []; for(i=0; i<patchCount; i++){ p2 = patchList[i]; _assert(p2.length === 2, "patchList must be an array of length-2-arrays"); key = p2[0]; patch = p2[1]; node = (key === null) ? this.rootNode : this.getNodeByKey(key); if(node){ dfd = new $.Deferred(); deferredList.push(dfd); node.applyPatch(patch).always(_makeResolveFunc(dfd, node)); }else{ this.warn("could not find node with key '" + key + "'"); } } // Return a promise that is resolved, when ALL patches were applied return $.when.apply($, deferredList).promise(); }, /* TODO: implement in dnd extension cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } }, */ /** Return the number of nodes. * @returns {integer} */ count: function() { return this.rootNode.countChildren(); }, /** Write to browser console if debugLevel >= 2 (prepending tree name) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, // TODO: disable() // TODO: enable() // TODO: enableUpdate() /** Find the next visible node that starts with `match`, starting at `startNode` * and wrap-around at the end. * * @param {string|function} match * @param {FancytreeNode} [startNode] defaults to first node * @returns {FancytreeNode} matching node or null */ findNextNode: function(match, startNode, visibleOnly) { var stopNode = null, parentChildren = startNode.parent.children, matchingNode = null, walkVisible = function(parent, idx, fn) { var i, grandParent, parentChildren = parent.children, siblingCount = parentChildren.length, node = parentChildren[idx]; // visit node itself if( node && fn(node) === false ) { return false; } // visit descendants if( node && node.children && node.expanded ) { if( walkVisible(node, 0, fn) === false ) { return false; } } // visit subsequent siblings for( i = idx + 1; i < siblingCount; i++ ) { if( walkVisible(parent, i, fn) === false ) { return false; } } // visit parent's subsequent siblings grandParent = parent.parent; if( grandParent ) { return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn); } else { // wrap-around: restart with first node return walkVisible(parent, 0, fn); } }; match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match; startNode = startNode || this.getFirstChild(); walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){ // Stop iteration if we see the start node a second time if( node === stopNode ) { return false; } stopNode = stopNode || node; // Ignore nodes hidden by a filter if( ! $(node.span).is(":visible") ) { node.debug("quicksearch: skipping hidden node"); return; } // Test if we found a match, but search for a second match if this // was the currently active node if( match(node) ) { // node.debug("quicksearch match " + node.title, startNode); matchingNode = node; if( matchingNode !== startNode ) { return false; } } }); return matchingNode; }, // TODO: fromDict /** * Generate INPUT elements that can be submitted with html forms. * * In selectMode 3 only the topmost selected nodes are considered. * * @param {boolean | string} [selected=true] * @param {boolean | string} [active=true] */ generateFormElements: function(selected, active) { // TODO: test case var nodeList, selectedName = (selected !== false) ? "ft_" + this._id + "[]" : selected, activeName = (active !== false) ? "ft_" + this._id + "_active" : active, id = "fancytree_result_" + this._id, $result = $("#" + id); if($result.length){ $result.empty(); }else{ $result = $("<div>", { id: id }).hide().insertAfter(this.$container); } if(selectedName){ nodeList = this.getSelectedNodes( this.options.selectMode === 3 ); $.each(nodeList, function(idx, node){ $result.append($("<input>", { type: "checkbox", name: selectedName, value: node.key, checked: true })); }); } if(activeName && this.activeNode){ $result.append($("<input>", { type: "radio", name: activeName, value: this.activeNode.key, checked: true })); } }, /** * Return the currently active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.activeNode; }, /** Return the first top level node if any (not the invisible root node). * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.rootNode.getFirstChild(); }, /** * Return node that has keyboard focus or null. * @returns {FancytreeNode} */ getFocusNode: function() { return this.focusNode; }, /** * Return node with a given key or null if not found. * @param {string} key * @param {FancytreeNode} [searchRoot] only search below this node * @returns {FancytreeNode | null} */ getNodeByKey: function(key, searchRoot) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). // $("#...") has problems, if the key contains '.', so we use getElementById() var el, match; if(!searchRoot){ el = document.getElementById(this.options.idPrefix + key); if( el ){ return el.ftnode ? el.ftnode : null; } } // Not found in the DOM, but still may be in an unrendered part of tree // TODO: optimize with specialized loop // TODO: consider keyMap? searchRoot = searchRoot || this.rootNode; match = null; searchRoot.visit(function(node){ // window.console.log("getNodeByKey(" + key + "): ", node.key); if(node.key === key) { match = node; return false; } }, true); return match; }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.rootNode; }, /** * Return an array of selected nodes. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { var nodeList = []; this.rootNode.visit(function(node){ if( node.selected ) { nodeList.push(node); if( stopOnParents === true ){ return "skip"; // stop processing this branch } } }); return nodeList; }, /** Return true if the tree control has keyboard focus * @returns {boolean} */ hasFocus: function(){ return !!this._hasFocus; }, /** Write to browser console if debugLevel >= 1 (prepending tree name) * @param {*} msg string or object or array of such */ info: function(msg){ if( this.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /* TODO: isInitializing: function() { return ( this.phase=="init" || this.phase=="postInit" ); }, TODO: isReloading: function() { return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound; }, TODO: isUserEvent: function() { return ( this.phase=="userEvent" ); }, */ /** * Make sure that a node with a given ID is loaded, by traversing - and * loading - its parents. This method is ment for lazy hierarchies. * A callback is executed for every node as we go. * @example * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){ * if(status === "loaded") { * console.log("loaded intermiediate node " + node); * }else if(status === "ok") { * node.activate(); * } * }); * * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7') * @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error') * @returns {$.Promise} */ loadKeyPath: function(keyPathList, callback, _rootNode) { var deferredList, dfd, i, path, key, loadMap, node, root, segList, sep = this.options.keyPathSeparator, self = this; if(!$.isArray(keyPathList)){ keyPathList = [keyPathList]; } // Pass 1: handle all path segments for nodes that are already loaded // Collect distinct top-most lazy nodes in a map loadMap = {}; for(i=0; i<keyPathList.length; i++){ root = _rootNode || this.rootNode; path = keyPathList[i]; // strip leading slash if(path.charAt(0) === sep){ path = path.substr(1); } // traverse and strip keys, until we hit a lazy, unloaded node segList = path.split(sep); while(segList.length){ key = segList.shift(); // node = _findDirectChild(root, key); node = root._findDirectChild(key); if(!node){ this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")"); callback.call(this, key, "error"); break; }else if(segList.length === 0){ callback.call(this, node, "ok"); break; }else if(!node.lazy || (node.hasChildren() !== undefined )){ callback.call(this, node, "loaded"); root = node; }else{ callback.call(this, node, "loaded"); // segList.unshift(key); if(loadMap[key]){ loadMap[key].push(segList.join(sep)); }else{ loadMap[key] = [segList.join(sep)]; } break; } } } // alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap)); // Now load all lazy nodes and continue itearation for remaining paths deferredList = []; // Avoid jshint warning 'Don't make functions within a loop.': function __lazyload(key, node, dfd){ callback.call(self, node, "loading"); node.load().done(function(){ self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self)); }).fail(function(errMsg){ self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")"); callback.call(self, node, "error"); dfd.reject(); }); } for(key in loadMap){ node = root._findDirectChild(key); // alert("loadKeyPath: lazy node(" + key + ") = " + node); dfd = new $.Deferred(); deferredList.push(dfd); __lazyload(key, node, dfd); } // Return a promise that is resolved, when ALL paths were loaded return $.when.apply($, deferredList).promise(); }, /** Re-fire beforeActivate and activate events. */ reactivate: function(setFocus) { var res, node = this.activeNode; if( !node ) { return _getResolvedPromise(); } this.activeNode = null; // Force re-activating res = node.setActive(); if( setFocus ){ node.setFocus(); } return res; }, /** Reload tree from source and return a promise. * @param [source] optional new source (defaults to initial source data) * @returns {$.Promise} */ reload: function(source) { this._callHook("treeClear", this); return this._callHook("treeLoad", this, source); }, /**Render tree (i.e. create DOM elements for all top-level nodes). * @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed * @param {boolean} [deep=false] */ render: function(force, deep) { return this.rootNode.render(force, deep); }, // TODO: selectKey: function(key, select) // TODO: serializeArray: function(stopOnParents) /** * @param {boolean} [flag=true] */ setFocus: function(flag) { return this._callHook("treeSetFocus", this, flag); }, /** * Return all nodes as nested list of {@link NodeData}. * * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children) * @param {function} [callback(node)] Called for every node * @returns {Array | object} * @see FancytreeNode#toDict */ toDict: function(includeRoot, callback){ var res = this.rootNode.toDict(true, callback); return includeRoot ? res : res.children; }, /* Implicitly called for string conversions. * @returns {string} */ toString: function(){ return "<Fancytree(#" + this._id + ")>"; }, /* _trigger a widget event with additional node ctx. * @see EventData */ _triggerNodeEvent: function(type, node, originalEvent, extra) { // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx); var ctx = this._makeHookContext(node, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /* _trigger a widget event with additional tree data. */ _triggerTreeEvent: function(type, originalEvent, extra) { // this.debug("_trigger(" + type + ")", ctx); var ctx = this._makeHookContext(this, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /** Call fn(node) for all nodes. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @returns {boolean} false, if the iterator was stopped. */ visit: function(fn) { return this.rootNode.visit(fn, false); }, /** Write warning to browser console (prepending tree info) * * @param {*} msg string or object or array of such */ warn: function(msg){ Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }; /** * These additional methods of the {@link Fancytree} class are 'hook functions' * that can be used and overloaded by extensions. * (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.) * @mixin Fancytree_Hooks */ $.extend(Fancytree.prototype, /** @lends Fancytree_Hooks# */ { /** Default handling for mouse click events. * * @param {EventData} ctx */ nodeClick: function(ctx) { // this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which); var activate, expand, // event = ctx.originalEvent, targetType = ctx.targetType, node = ctx.node; // TODO: use switch // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample) if( targetType === "expander" ) { // Clicking the expander icon always expands/collapses this._callHook("nodeToggleExpanded", ctx); } else if( targetType === "checkbox" ) { // Clicking the checkbox always (de)selects this._callHook("nodeToggleSelected", ctx); if( ctx.options.focusOnSelect ) { // #358 this._callHook("nodeSetFocus", ctx, true); } } else { // Honor `clickFolderMode` for expand = false; activate = true; if( node.folder ) { switch( ctx.options.clickFolderMode ) { case 2: // expand only expand = true; activate = false; break; case 3: // expand and activate activate = true; expand = true; //!node.isExpanded(); break; // else 1 or 4: just activate } } if( activate ) { this.nodeSetFocus(ctx); this._callHook("nodeSetActive", ctx, true); } if( expand ) { if(!activate){ // this._callHook("nodeSetFocus", ctx); } // this._callHook("nodeSetExpanded", ctx, true); this._callHook("nodeToggleExpanded", ctx); } } // Make sure that clicks stop, otherwise <a href='#'> jumps to the top // if(event.target.localName === "a" && event.target.className === "fancytree-title"){ // event.preventDefault(); // } // TODO: return promise? }, /** Collapse all other children of same parent. * * @param {EventData} ctx * @param {object} callOpts */ nodeCollapseSiblings: function(ctx, callOpts) { // TODO: return promise? var ac, i, l, node = ctx.node; if( node.parent ){ ac = node.parent.children; for (i=0, l=ac.length; i<l; i++) { if ( ac[i] !== node && ac[i].expanded ){ this._callHook("nodeSetExpanded", ac[i], false, callOpts); } } } }, /** Default handling for mouse douleclick events. * @param {EventData} ctx */ nodeDblclick: function(ctx) { // TODO: return promise? if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) { // this.nodeSetFocus(ctx); // this._callHook("nodeSetActive", ctx, true); this._callHook("nodeToggleExpanded", ctx); } // TODO: prevent text selection on dblclicks if( ctx.targetType === "title" ) { ctx.originalEvent.preventDefault(); } }, /** Default handling for mouse keydown events. * * NOTE: this may be called with node == null if tree (but no node) has focus. * @param {EventData} ctx */ nodeKeydown: function(ctx) { // TODO: return promise? var matchNode, stamp, res, event = ctx.originalEvent, node = ctx.node, tree = ctx.tree, opts = ctx.options, which = event.which, whichChar = String.fromCharCode(which), clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey), $target = $(event.target), handled = true, activate = !(event.ctrlKey || !opts.autoActivate ); // (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); // FT.debug("eventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.eventToString(event) + '"'); // Set focus to active (or first node) if no other node has the focus yet if( !node ){ (this.getActiveNode() || this.getFirstChild()).setFocus(); node = ctx.node = this.focusNode; node.debug("Keydown force focus on active node"); } if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) { // Allow to search for longer streaks if typed in quickly stamp = new Date().getTime(); if( stamp - tree.lastQuicksearchTime > 500 ) { tree.lastQuicksearchTerm = ""; } tree.lastQuicksearchTime = stamp; tree.lastQuicksearchTerm += whichChar; // tree.debug("quicksearch find", tree.lastQuicksearchTerm); matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode()); if( matchNode ) { matchNode.setActive(); } event.preventDefault(); return; } switch( FT.eventToString(event) ) { case "+": case "=": // 187: '+' @ Chrome, Safari tree.nodeSetExpanded(ctx, true); break; case "-": tree.nodeSetExpanded(ctx, false); break; case "space": if(opts.checkbox){ tree.nodeToggleSelected(ctx); }else{ tree.nodeSetActive(ctx, true); } break; case "enter": tree.nodeSetActive(ctx, true); break; case "backspace": case "left": case "right": case "up": case "down": res = node.navigate(event.which, activate); break; default: handled = false; } if(handled){ event.preventDefault(); } }, // /** Default handling for mouse keypress events. */ // nodeKeypress: function(ctx) { // var event = ctx.originalEvent; // }, // /** Trigger lazyLoad event (async). */ // nodeLazyLoad: function(ctx) { // var node = ctx.node; // if(this._triggerNodeEvent()) // }, /** Load child nodes (async). * * @param {EventData} ctx * @param {object[]|object|string|$.Promise|function} source * @returns {$.Promise} The deferred will be resolved as soon as the (ajax) * data was rendered. */ nodeLoadChildren: function(ctx, source) { var ajax, delay, dfd, tree = ctx.tree, node = ctx.node; if($.isFunction(source)){ source = source(); } // TOTHINK: move to 'ajax' extension? if(source.url){ // `source` is an Ajax options object ajax = $.extend({}, ctx.options.ajax, source); if(ajax.debugDelay){ // simulate a slow server delay = ajax.debugDelay; if($.isArray(delay)){ // random delay range [min..max] delay = delay[0] + Math.random() * (delay[1] - delay[0]); } node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms"); ajax.debugDelay = false; dfd = $.Deferred(function (dfd) { setTimeout(function () { $.ajax(ajax) .done(function () { dfd.resolveWith(this, arguments); }) .fail(function () { dfd.rejectWith(this, arguments); }); }, delay); }); }else{ dfd = $.ajax(ajax); } // Defer the deferred: we want to be able to reject, even if ajax // resolved ok. source = new $.Deferred(); dfd.done(function (data, textStatus, jqXHR) { var errorObj, res; if(typeof data === "string"){ $.error("Ajax request returned a string (did you get the JSON dataType wrong?)."); } // postProcess is similar to the standard ajax dataFilter hook, // but it is also called for JSONP if( ctx.options.postProcess ){ res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType}); if( res.error ) { errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error}; errorObj = tree._makeHookContext(node, null, errorObj); source.rejectWith(this, [errorObj]); return; } data = $.isArray(res) ? res : data; } else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) { // Process ASPX WebMethod JSON object inside "d" property data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d; } source.resolveWith(this, [data]); }).fail(function (jqXHR, textStatus, errorThrown) { var errorObj = tree._makeHookContext(node, null, { error: jqXHR, args: Array.prototype.slice.call(arguments), message: errorThrown, details: jqXHR.status + ": " + errorThrown }); source.rejectWith(this, [errorObj]); }); } // #383: accept and convert ECMAScript 6 Promise if( $.isFunction(source.then) && $.isFunction(source["catch"]) ) { dfd = source; source = new $.Deferred(); dfd.then(function(value){ source.resolve(value); }, function(reason){ source.reject(reason); }); } if($.isFunction(source.promise)){ // `source` is a deferred, i.e. ajax request _assert(!node.isLoading()); // node._isLoading = true; tree.nodeSetStatus(ctx, "loading"); source.done(function (children) { tree.nodeSetStatus(ctx, "ok"); }).fail(function(error){ var ctxErr; if (error.node && error.error && error.message) { // error is already a context object ctxErr = error; } else { ctxErr = tree._makeHookContext(node, null, { error: error, // it can be jqXHR or any custom error args: Array.prototype.slice.call(arguments), message: error ? (error.message || error.toString()) : "" }); } if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) { tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details); } }); } // $.when(source) resolves also for non-deferreds return $.when(source).done(function(children){ var metaData; if( $.isPlainObject(children) ){ // We got {foo: 'abc', children: [...]} // Copy extra properties to tree.data.foo _assert($.isArray(children.children), "source must contain (or be) an array of children"); _assert(node.isRoot(), "source may only be an object for root nodes"); metaData = children; children = children.children; delete metaData.children; $.extend(tree.data, metaData); } _assert($.isArray(children), "expected array of children"); node._setChildren(children); // trigger fancytreeloadchildren tree._triggerNodeEvent("loadChildren", node); // }).always(function(){ // node._isLoading = false; }); }, /** [Not Implemented] */ nodeLoadKeyPath: function(ctx, keyPathList) { // TODO: implement and improve // http://code.google.com/p/dynatree/issues/detail?id=222 }, /** * Remove a single direct child of ctx.node. * @param {EventData} ctx * @param {FancytreeNode} childNode dircect child of ctx.node */ nodeRemoveChild: function(ctx, childNode) { var idx, node = ctx.node, opts = ctx.options, subCtx = $.extend({}, ctx, {node: childNode}), children = node.children; // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString()); if( children.length === 1 ) { _assert(childNode === children[0]); return this.nodeRemoveChildren(ctx); } if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveMarkup(subCtx); this.nodeRemoveChildren(subCtx); idx = $.inArray(childNode, children); _assert(idx >= 0); // Unlink to support GC childNode.visit(function(n){ n.parent = null; }, true); this._callHook("treeRegisterNode", this, false, childNode); if ( opts.removeNode ){ opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx); } // remove from child list children.splice(idx, 1); }, /**Remove HTML markup for all descendents of ctx.node. * @param {EventData} ctx */ nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveChildMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.ul){ if( node.isRoot() ) { $(node.ul).empty(); } else { $(node.ul).remove(); node.ul = null; } node.visit(function(n){ n.li = n.ul = null; }); } }, /**Remove all descendants of ctx.node. * @param {EventData} ctx */ nodeRemoveChildren: function(ctx) { var subCtx, tree = ctx.tree, node = ctx.node, children = node.children, opts = ctx.options; // FT.debug("nodeRemoveChildren()", node.toString()); if(!children){ return; } if( this.activeNode && this.activeNode.isDescendantOf(node)){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && this.focusNode.isDescendantOf(node)){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveChildMarkup(ctx); // Unlink children to support GC // TODO: also delete this.children (not possible using visit()) subCtx = $.extend({}, ctx); node.visit(function(n){ n.parent = null; tree._callHook("treeRegisterNode", tree, false, n); if ( opts.removeNode ){ subCtx.node = n; opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx); } }); if( node.lazy ){ // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes node.children = []; } else{ node.children = null; } this.nodeRenderStatus(ctx); }, /**Remove HTML markup for ctx.node and all its descendents. * @param {EventData} ctx */ nodeRemoveMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.li){ $(node.li).remove(); node.li = null; } this.nodeRemoveChildMarkup(ctx); }, /** * Create `&lt;li>&lt;span>..&lt;/span> .. &lt;/li>` tags for this node. * * This method takes care that all HTML markup is created that is required * to display this node in it's current state. * * Call this method to create new nodes, or after the strucuture * was changed (e.g. after moving this node or adding/removing children) * nodeRenderTitle() and nodeRenderStatus() are implied. * * Note: if a node was created/removed, nodeRender() must be called for the * parent. * <code> * <li id='KEY' ftnode=NODE> * <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'> * <span class="fancytree-expander"></span> * <span class="fancytree-checkbox"></span> // only present in checkbox mode * <span class="fancytree-icon"></span> * <a href="#" class="fancytree-title"> Node 1 </a> * </span> * <ul> // only present if node has children * <li id='KEY' ftnode=NODE> child1 ... </li> * <li id='KEY' ftnode=NODE> child2 ... </li> * </ul> * </li> * </code> * * @param {EventData} ctx * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { /* This method must take care of all cases where the current data mode * (i.e. node hierarchy) does not match the current markup. * * - node was not yet rendered: * create markup * - node was rendered: exit fast * - children have been added * - childern have been removed */ var childLI, childNode1, childNode2, i, l, next, subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, firstTime = false, parent = node.parent, isRootNode = !parent, children = node.children; // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString()); if( ! isRootNode && ! parent.ul ) { // Calling node.collapse on a deep, unrendered node return; } _assert(isRootNode || parent.ul, "parent UL must exist"); // Render the node if( !isRootNode ){ // Discard markup on force-mode, or if it is not linked to parent <ul> if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){ if(node.li.parentNode !== node.parent.ul){ // May happen, when a top-level node was dropped over another this.debug("Unlinking " + node + " (must be child of " + node.parent + ")"); } // this.debug("nodeRemoveMarkup..."); this.nodeRemoveMarkup(ctx); } // Create <li><span /> </li> // node.debug("render..."); if( !node.li ) { // node.debug("render... really"); firstTime = true; node.li = document.createElement("li"); node.li.ftnode = node; if(aria){ // TODO: why doesn't this work: // node.li.role = "treeitem"; // $(node.li).attr("role", "treeitem") // .attr("aria-labelledby", "ftal_" + node.key); } if( node.key && opts.generateIds ){ node.li.id = opts.idPrefix + node.key; } node.span = document.createElement("span"); node.span.className = "fancytree-node"; if(aria){ $(node.span).attr("aria-labelledby", "ftal_" + node.key); } node.li.appendChild(node.span); // Create inner HTML for the <span> (expander, checkbox, icon, and title) this.nodeRenderTitle(ctx); // Allow tweaking and binding, after node was created for the first time if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } }else{ // this.nodeRenderTitle(ctx); this.nodeRenderStatus(ctx); } // Allow tweaking after node state was rendered if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } } // Visit child nodes if( children ){ if( isRootNode || node.expanded || deep === true ) { // Create a UL to hold the children if( !node.ul ){ node.ul = document.createElement("ul"); if((collapsed === true && !_recursive) || !node.expanded){ // hide top UL, so we can use an animation to show it later node.ul.style.display = "none"; } if(aria){ $(node.ul).attr("role", "group"); } if ( node.li ) { // issue #67 node.li.appendChild(node.ul); } else { node.tree.$div.append(node.ul); } } // Add child markup for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); this.nodeRender(subCtx, force, deep, false, true); } // Remove <li> if nodes have moved to another parent childLI = node.ul.firstChild; while( childLI ){ childNode2 = childLI.ftnode; if( childNode2 && childNode2.parent !== node ) { node.debug("_fixParent: remove missing " + childNode2, childLI); next = childLI.nextSibling; childLI.parentNode.removeChild(childLI); childLI = next; }else{ childLI = childLI.nextSibling; } } // Make sure, that <li> order matches node.children order. childLI = node.ul.firstChild; for(i=0, l=children.length-1; i<l; i++) { childNode1 = children[i]; childNode2 = childLI.ftnode; if( childNode1 !== childNode2 ) { // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2); node.ul.insertBefore(childNode1.li, childNode2.li); } else { childLI = childLI.nextSibling; } } } }else{ // No children: remove markup if any if( node.ul ){ // alert("remove child markup for " + node); this.warn("remove child markup for " + node); this.nodeRemoveChildMarkup(ctx); } } if( !isRootNode ){ // Update element classes according to node state // this.nodeRenderStatus(ctx); // Finally add the whole structure to the DOM, so the browser can render if(firstTime){ parent.ul.appendChild(node.li); } } }, /** Create HTML for the node's outer <span> (expander, checkbox, icon, and title). * * nodeRenderStatus() is implied. * @param {EventData} ctx * @param {string} [title] optinal new title */ nodeRenderTitle: function(ctx, title) { // set node connector images, links and text var id, iconSpanClass, nodeTitle, role, tabindex, tooltip, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, level = node.getLevel(), ares = [], iconSrc = node.data.icon; if(title !== undefined){ node.title = title; } if(!node.span){ // Silently bail out if node was not rendered yet, assuming // node.render() will be called as the node becomes visible return; } // connector (expanded, expandable or simple) // TODO: optimize this if clause if( level < opts.minExpandLevel ) { if( !node.lazy ) { node.expanded = true; } if(level > 1){ if(aria){ ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>"); }else{ ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>"); } } // .. else (i.e. for root level) skip expander/connector alltogether } else { if(aria){ ares.push("<span role='button' class='fancytree-expander'></span>"); }else{ ares.push("<span class='fancytree-expander'></span>"); } } // Checkbox mode if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) { if(aria){ ares.push("<span role='checkbox' class='fancytree-checkbox'></span>"); }else{ ares.push("<span class='fancytree-checkbox'></span>"); } } // folder or doctype icon role = aria ? " role='img'" : ""; if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) { // opts.icons defines the default behavior, node.icon == true/false can override this if ( iconSrc && typeof iconSrc === "string" ) { // node.icon is an image url iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc); ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />"); } else { // See if node.iconClass or opts.iconClass() define a class name iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null; if( iconSpanClass ) { ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>"); } else { ares.push("<span " + role + " class='fancytree-icon'></span>"); } } } // node title nodeTitle = ""; if ( opts.renderTitle ){ nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || ""; } if(!nodeTitle){ tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : ""; id = aria ? " id='ftal_" + node.key + "'" : ""; role = aria ? " role='treeitem'" : ""; tabindex = opts.titlesTabbable ? " tabindex='0'" : ""; nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>"; } ares.push(nodeTitle); // Note: this will trigger focusout, if node had the focus //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly node.span.innerHTML = ares.join(""); // Update CSS classes this.nodeRenderStatus(ctx); }, /** Update element classes according to node state. * @param {EventData} ctx */ nodeRenderStatus: function(ctx) { // Set classes for current status var node = ctx.node, tree = ctx.tree, opts = ctx.options, // nodeContainer = node[tree.nodeContainerAttrName], hasChildren = node.hasChildren(), isLastSib = node.isLastSibling(), aria = opts.aria, // $ariaElem = aria ? $(node[tree.ariaPropName]) : null, $ariaElem = $(node.span).find(".fancytree-title"), cn = opts._classNames, cnList = [], statusElem = node[tree.statusClassPropName]; if( !statusElem ){ // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway) return; } // Build a list of class names that we will add to the node <span> cnList.push(cn.node); if( tree.activeNode === node ){ cnList.push(cn.active); // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // tree.$container.removeAttr("tabindex"); // }else{ // $(">span.fancytree-title", statusElem).removeAttr("tabindex"); // tree.$container.attr("tabindex", "0"); } if( tree.focusNode === node ){ cnList.push(cn.focused); if(aria){ // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // $(">span.fancytree-title", statusElem).attr("tabindex", "-1"); // TODO: is this the right element for this attribute? $ariaElem .attr("aria-activedescendant", true); // .attr("tabindex", "-1"); } }else if(aria){ // $(">span.fancytree-title", statusElem).attr("tabindex", "-1"); $ariaElem .removeAttr("aria-activedescendant"); // .removeAttr("tabindex"); } if( node.expanded ){ cnList.push(cn.expanded); if(aria){ $ariaElem.attr("aria-expanded", true); } }else if(aria){ $ariaElem.removeAttr("aria-expanded"); } if( node.folder ){ cnList.push(cn.folder); } if( hasChildren !== false ){ cnList.push(cn.hasChildren); } // TODO: required? if( isLastSib ){ cnList.push(cn.lastsib); } if( node.lazy && node.children == null ){ cnList.push(cn.lazy); } if( node.partsel ){ cnList.push(cn.partsel); } if( node.unselectable ){ cnList.push(cn.unselectable); } if( node._isLoading ){ cnList.push(cn.loading); } if( node._error ){ cnList.push(cn.error); } if( node.selected ){ cnList.push(cn.selected); if(aria){ $ariaElem.attr("aria-selected", true); } }else if(aria){ $ariaElem.attr("aria-selected", false); } if( node.extraClasses ){ cnList.push(node.extraClasses); } // IE6 doesn't correctly evaluate multiple class names, // so we create combined class names that can be used in the CSS if( hasChildren === false ){ cnList.push(cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "") ); }else{ cnList.push(cn.combinedExpanderPrefix + (node.expanded ? "e" : "c") + (node.lazy && node.children == null ? "d" : "") + (isLastSib ? "l" : "") ); } cnList.push(cn.combinedIconPrefix + (node.expanded ? "e" : "c") + (node.folder ? "f" : "") ); // node.span.className = cnList.join(" "); statusElem.className = cnList.join(" "); // TODO: we should not set this in the <span> tag also, if we set it here: // Maybe most (all) of the classes should be set in LI instead of SPAN? if(node.li){ node.li.className = isLastSib ? cn.lastsib : ""; } }, /** Activate node. * flag defaults to true. * If flag is true, the node is activated (must be a synchronous operation) * If flag is false, the node is deactivated (must be a synchronous operation) * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false} * @returns {$.Promise} */ nodeSetActive: function(ctx, flag, callOpts) { // Handle user click / [space] / [enter], according to clickFolderMode. callOpts = callOpts || {}; var subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = (callOpts.noEvents === true), noFocus = (callOpts.noFocus === true), isActive = (node === tree.activeNode); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetActive", flag); if(isActive === flag){ // Nothing to do return _getResolvedPromise(node); }else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } if(flag){ if(tree.activeNode){ _assert(tree.activeNode !== node, "node was active (inconsistency)"); subCtx = $.extend({}, ctx, {node: tree.activeNode}); tree.nodeSetActive(subCtx, false); _assert(tree.activeNode === null, "deactivate was out of sync?"); } if(opts.activeVisible){ // tree.nodeMakeVisible(ctx); node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll } tree.activeNode = node; tree.nodeRenderStatus(ctx); if( !noFocus ) { tree.nodeSetFocus(ctx); } if( !noEvents ) { tree._triggerNodeEvent("activate", node, ctx.originalEvent); } }else{ _assert(tree.activeNode === node, "node was not active (inconsistency)"); tree.activeNode = null; this.nodeRenderStatus(ctx); if( !noEvents ) { ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent); } } }, /** Expand or collapse node, return Deferred.promise. * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} The deferred will be resolved as soon as the (lazy) * data was retrieved, rendered, and the expand animation finshed. */ nodeSetExpanded: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var _afterLoad, dfd, i, l, parents, prevAC, node = ctx.node, tree = ctx.tree, opts = ctx.options, noAnimation = (callOpts.noAnimation === true), noEvents = (callOpts.noEvents === true); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetExpanded(" + flag + ")"); if((node.expanded && flag) || (!node.expanded && !flag)){ // Nothing to do // node.debug("nodeSetExpanded(" + flag + "): nothing to do"); return _getResolvedPromise(node); }else if(flag && !node.lazy && !node.hasChildren() ){ // Prevent expanding of empty nodes // return _getRejectedPromise(node, ["empty"]); return _getResolvedPromise(node); }else if( !flag && node.getLevel() < opts.minExpandLevel ) { // Prevent collapsing locked levels return _getRejectedPromise(node, ["locked"]); }else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } // If this node inside a collpased node, no animation and scrolling is needed if( !noAnimation && !node.isVisible() ) { noAnimation = callOpts.noAnimation = true; } dfd = new $.Deferred(); // Auto-collapse mode: collapse all siblings if( flag && !node.expanded && opts.autoCollapse ) { parents = node.getParentList(false, true); prevAC = opts.autoCollapse; try{ opts.autoCollapse = false; for(i=0, l=parents.length; i<l; i++){ // TODO: should return promise? this._callHook("nodeCollapseSiblings", parents[i], callOpts); } }finally{ opts.autoCollapse = prevAC; } } // Trigger expand/collapse after expanding dfd.done(function(){ if( flag && opts.autoScroll && !noAnimation ) { // Scroll down to last child, but keep current node visible node.getLastChild().scrollIntoView(true, {topNode: node}).always(function(){ if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } }); } else { if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } } }); // vvv Code below is executed after loading finished: _afterLoad = function(callback){ var isVisible, isExpanded, effect = opts.toggleEffect; node.expanded = flag; // Create required markup, but make sure the top UL is hidden, so we // can animate later tree._callHook("nodeRender", ctx, false, false, true); // If the currently active node is now hidden, deactivate it // if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) { // this.activeNode.deactivate(); // } // Expanding a lazy node: set 'loading...' and call callback // if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) { // this._loadContent(); // return; // } // Hide children, if node is collapsed if( node.ul ) { isVisible = (node.ul.style.display !== "none"); isExpanded = !!node.expanded; if ( isVisible === isExpanded ) { node.warn("nodeSetExpanded: UL.style.display already set"); } else if ( !effect || noAnimation ) { node.ul.style.display = ( node.expanded || !parent ) ? "" : "none"; } else { // The UI toggle() effect works with the ext-wide extension, // while jQuery.animate() has problems when the title span // has positon: absolute // duration = opts.fx.duration || 200; // easing = opts.fx.easing; // $(node.ul).animate(opts.fx, duration, easing, function(){ // node.debug("nodeSetExpanded: animate start..."); $(node.ul).toggle(effect.effect, effect.options, effect.duration, function(){ // node.debug("nodeSetExpanded: animate done"); callback(); }); return; } } callback(); }; // ^^^ Code above is executed after loading finshed. // Load lazy nodes, if any. Then continue with _afterLoad() if(flag && node.lazy && node.hasChildren() === undefined){ // node.debug("nodeSetExpanded: load start..."); node.load().done(function(){ // node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad(function () { dfd.resolveWith(node); }); }).fail(function(errMsg){ _afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); }); /* var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent); _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); node.debug("nodeSetExpanded: load start..."); this._callHook("nodeLoadChildren", ctx, source).done(function(){ node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad.call(tree); }).fail(function(errMsg){ dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); */ }else{ _afterLoad(function () { dfd.resolveWith(node); }); } // node.debug("nodeSetExpanded: returns"); return dfd.promise(); }, /** Focus or blur this node. * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetFocus: function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node; flag = (flag !== false); // Blur previous node if any if(tree.focusNode){ if(tree.focusNode === node && flag){ // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, {node: tree.focusNode}); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if(flag){ if( !this.hasFocus() ){ node.debug("nodeSetFocus: forcing container focus"); this._callHook("treeSetFocus", ctx, true, {calledByNode: true}); } node.makeVisible({scrollIntoView: false}); tree.focusNode = node; // node.debug("FOCUS..."); // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // if(ctx.options.autoActivate){ // tree.nodeSetActive(ctx, true); // } if(ctx.options.autoScroll){ node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }, /** (De)Select node, return new status (sync). * * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetSelected: function(ctx, flag) { var node = ctx.node, tree = ctx.tree, opts = ctx.options; // flag defaults to true flag = (flag !== false); node.debug("nodeSetSelected(" + flag + ")", ctx); if( node.unselectable){ return; } // TODO: !!node.expanded is nicer, but doesn't pass jshint // https://github.com/jshint/jshint/issues/455 // if( !!node.expanded === !!flag){ if((node.selected && flag) || (!node.selected && !flag)){ return !!node.selected; }else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){ return !!node.selected; } if(flag && opts.selectMode === 1){ // single selection mode if(tree.lastSelectedNode){ tree.lastSelectedNode.setSelected(false); } }else if(opts.selectMode === 3){ // multi.hier selection mode node.selected = flag; // this._fixSelectionState(node); node.fixSelection3AfterClick(); } node.selected = flag; this.nodeRenderStatus(ctx); tree.lastSelectedNode = flag ? node : null; tree._triggerNodeEvent("select", ctx); }, /** Show node status (ok, loading, error) using styles and a dummy child node. * * @param {EventData} ctx * @param status * @param message * @param details */ nodeSetStatus: function(ctx, status, message, details) { var node = ctx.node, tree = ctx.tree; // cn = ctx.options._classNames; function _clearStatusNode() { // Remove dedicated dummy node, if any var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { try{ // I've seen exceptions here with loadKeyPath... if(node.ul){ node.ul.removeChild(firstChild.li); firstChild.li = null; // avoid leaks (DT issue 215) } }catch(e){} if( node.children.length === 1 ){ node.children = []; }else{ node.children.shift(); } } } function _setStatusNode(data, type) { // Create/modify the dedicated dummy node for 'loading...' or // 'error!' status. (only called for direct child of the invisible // system root) var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $.extend(firstChild, data); // tree._callHook("nodeRender", firstChild); tree._callHook("nodeRenderTitle", firstChild); } else { data.key = "_statusNode"; node._setChildren([data]); node.children[0].statusNodeType = type; tree.render(); } return node.children[0]; } switch( status ){ case "ok": _clearStatusNode(); // $(node.span).removeClass(cn.loading).removeClass(cn.error); node._isLoading = false; node._error = null; node.renderStatus(); break; case "loading": // $(node.span).removeClass(cn.error).addClass(cn.loading); if( !node.parent ) { _setStatusNode({ title: tree.options.strings.loading + (message ? " (" + message + ") " : ""), tooltip: details, extraClasses: "fancytree-statusnode-wait" }, status); } node._isLoading = true; node._error = null; node.renderStatus(); break; case "error": // $(node.span).removeClass(cn.loading).addClass(cn.error); _setStatusNode({ title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""), tooltip: details, extraClasses: "fancytree-statusnode-error" }, status); node._isLoading = false; node._error = { message: message, details: details }; node.renderStatus(); break; default: $.error("invalid node status " + status); } }, /** * * @param {EventData} ctx */ nodeToggleExpanded: function(ctx) { return this.nodeSetExpanded(ctx, !ctx.node.expanded); }, /** * @param {EventData} ctx */ nodeToggleSelected: function(ctx) { return this.nodeSetSelected(ctx, !ctx.node.selected); }, /** Remove all nodes. * @param {EventData} ctx */ treeClear: function(ctx) { var tree = ctx.tree; tree.activeNode = null; tree.focusNode = null; tree.$div.find(">ul.fancytree-container").empty(); // TODO: call destructors and remove reference loops tree.rootNode.children = null; }, /** Widget was created (called only once, even it re-initialized). * @param {EventData} ctx */ treeCreate: function(ctx) { }, /** Widget was destroyed. * @param {EventData} ctx */ treeDestroy: function(ctx) { }, /** Widget was (re-)initialized. * @param {EventData} ctx */ treeInit: function(ctx) { //this.debug("Fancytree.treeInit()"); this.treeLoad(ctx); }, /** Parse Fancytree from source, as configured in the options. * @param {EventData} ctx * @param {object} [source] optional new source (use last data otherwise) */ treeLoad: function(ctx, source) { var type, $ul, tree = ctx.tree, $container = ctx.widget.element, dfd, // calling context for root node rootCtx = $.extend({}, ctx, {node: this.rootNode}); if(tree.rootNode.children){ this.treeClear(ctx); } source = source || this.options.source; if(!source){ type = $container.data("type") || "html"; switch(type){ case "html": $ul = $container.find(">ul:first"); $ul.addClass("ui-fancytree-source ui-helper-hidden"); source = $.ui.fancytree.parseHtml($ul); // allow to init tree.data.foo from <ul data-foo=''> this.data = $.extend(this.data, _getElementDataAsDict($ul)); break; case "json": // $().addClass("ui-helper-hidden"); source = $.parseJSON($container.text()); if(source.children){ if(source.title){tree.title = source.title;} source = source.children; } break; default: $.error("Invalid data-type: " + type); } }else if(typeof source === "string"){ // TODO: source is an element ID $.error("Not implemented"); } // $container.addClass("ui-widget ui-widget-content ui-corner-all"); // Trigger fancytreeinit after nodes have been loaded dfd = this.nodeLoadChildren(rootCtx, source).done(function(){ tree.render(); if( ctx.options.selectMode === 3 ){ tree.rootNode.fixSelection3FromEndNodes(); } tree._triggerTreeEvent("init", null, { status: true }); }).fail(function(){ tree.render(); tree._triggerTreeEvent("init", null, { status: false }); }); return dfd; }, /** Node was inserted into or removed from the tree. * @param {EventData} ctx * @param {boolean} add * @param {FancytreeNode} node */ treeRegisterNode: function(ctx, add, node) { }, /** Widget got focus. * @param {EventData} ctx * @param {boolean} [flag=true] */ treeSetFocus: function(ctx, flag, callOpts) { flag = (flag !== false); // this.debug("treeSetFocus(" + flag + "), callOpts: " + callOpts); // this.debug(" focusNode: " + this.focusNode); // this.debug(" activeNode: " + this.activeNode); if( flag !== this.hasFocus() ){ this._hasFocus = flag; if( !flag && this.focusNode ) { // Node also looses focus if widget blurs this.focusNode.setFocus(false); } this.$container.toggleClass("fancytree-treefocus", flag); this._triggerTreeEvent(flag ? "focusTree" : "blurTree"); } } }); /* ****************************************************************************** * jQuery UI widget boilerplate */ /** * The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br> * This constructor is not called directly. Use `$(selector).fancytree({})` * to initialize the plugin instead.<br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members: * var tree = $("#tree").fancytree("getTree"); * var node = $("#tree").fancytree("getActiveNode", "1234"); * </pre> * * @mixin Fancytree_Widget */ $.widget("ui.fancytree", /** @lends Fancytree_Widget# */ { /**These options will be used as defaults * @type {FancytreeOptions} */ options: { activeVisible: true, ajax: { type: "GET", cache: false, // false: Append random '_' argument to the request url to prevent caching. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable dataType: "json" // Expect json format and pass json object to callbacks. }, // aria: false, // TODO: default to true autoActivate: true, autoCollapse: false, // autoFocus: false, autoScroll: false, checkbox: false, /**defines click behavior*/ clickFolderMode: 4, debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo) disabled: false, // TODO: required anymore? enableAspx: true, // TODO: document extensions: [], // fx: { height: "toggle", duration: 200 }, // toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 }, // toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 }, toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }, generateIds: false, icons: true, idPrefix: "ft_", focusOnSelect: false, keyboard: true, keyPathSeparator: "/", minExpandLevel: 1, quicksearch: false, scrollOfs: {top: 0, bottom: 0}, scrollParent: null, selectMode: 2, strings: { loading: "Loading&#8230;", loadError: "Load error!" }, tabbable: true, titlesTabbable: false, _classNames: { node: "fancytree-node", folder: "fancytree-folder", combinedExpanderPrefix: "fancytree-exp-", combinedIconPrefix: "fancytree-ico-", hasChildren: "fancytree-has-children", active: "fancytree-active", selected: "fancytree-selected", expanded: "fancytree-expanded", lazy: "fancytree-lazy", focused: "fancytree-focused", partsel: "fancytree-partsel", unselectable: "fancytree-unselectable", lastsib: "fancytree-lastsib", loading: "fancytree-loading", error: "fancytree-error" }, // events lazyLoad: null, postProcess: null }, /* Set up the widget, Called on first $().fancytree() */ _create: function() { this.tree = new Fancytree(this); this.$source = this.source || this.element.data("type") === "json" ? this.element : this.element.find(">ul:first"); // Subclass Fancytree instance with all enabled extensions var extension, extName, i, extensions = this.options.extensions, base = this.tree; for(i=0; i<extensions.length; i++){ extName = extensions[i]; extension = $.ui.fancytree._extensions[extName]; if(!extension){ $.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)"); } // Add extension options as tree.options.EXTENSION // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName); this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]); // Add a namespace tree.ext.EXTENSION, to hold instance data _assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'"); // this.tree[extName] = extension; this.tree.ext[extName] = {}; // Subclass Fancytree methods using proxies. _subclassObject(this.tree, base, extension, extName); // current extension becomes base for the next extension base = extension; } // this.tree._callHook("treeCreate", this.tree); // Note: 'fancytreecreate' event is fired by widget base class // this.tree._triggerTreeEvent("create"); }, /* Called on every $().fancytree() */ _init: function() { this.tree._callHook("treeInit", this.tree); // TODO: currently we call bind after treeInit, because treeInit // might change tree.$container. // It would be better, to move ebent binding into hooks altogether this._bind(); }, /* Use the _setOption method to respond to changes to options */ _setOption: function(key, value) { var callDefault = true, rerender = false; switch( key ) { case "aria": case "checkbox": case "icons": case "minExpandLevel": case "tabbable": // case "nolink": this.tree._callHook("treeCreate", this.tree); rerender = true; break; case "source": callDefault = false; this.tree._callHook("treeLoad", this.tree, value); break; } this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">"); if(callDefault){ // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget $.Widget.prototype._setOption.apply(this, arguments); // TODO: In jQuery UI 1.9 and above, you use the _super method instead // this._super( "_setOption", key, value ); } if(rerender){ this.tree.render(true, false); // force, not-deep } }, /** Use the destroy method to clean up any modifications your widget has made to the DOM */ destroy: function() { this._unbind(); this.tree._callHook("treeDestroy", this.tree); // this.element.removeClass("ui-widget ui-widget-content ui-corner-all"); this.tree.$div.find(">ul.fancytree-container").remove(); this.$source && this.$source.removeClass("ui-helper-hidden"); // In jQuery UI 1.8, you must invoke the destroy method from the base widget $.Widget.prototype.destroy.call(this); // TODO: delete tree and nodes to make garbage collect easier? // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method }, // ------------------------------------------------------------------------- /* Remove all event handlers for our namespace */ _unbind: function() { var ns = this.tree._ns; this.element.unbind(ns); this.tree.$container.unbind(ns); $(document).unbind(ns); }, /* Add mouse and kyboard handlers to the container */ _bind: function() { var that = this, opts = this.options, tree = this.tree, ns = tree._ns // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" ) ; // Remove all previuous handlers for this tree this._unbind(); //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container); // tree.debug("bind events; container: ", tree.$container); tree.$container.on("focusin" + ns + " focusout" + ns, function(event){ var node = FT.getNode(event), flag = (event.type === "focusin"); // tree.debug("Tree container got event " + event.type, node, event); // tree.treeOnFocusInOut.call(tree, event); if(node){ // For example clicking into an <input> that is part of a node tree._callHook("nodeSetFocus", node, flag); }else{ tree._callHook("treeSetFocus", tree, flag); } }).on("selectstart" + ns, "span.fancytree-title", function(event){ // prevent mouse-drags to select text ranges // tree.debug("<span title> got event " + event.type); event.preventDefault(); }).on("keydown" + ns, function(event){ // TODO: also bind keyup and keypress // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus()); // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){ if(opts.disabled || opts.keyboard === false ){ return true; } var res, node = tree.focusNode, // node may be null ctx = tree._makeHookContext(node || tree, event), prevPhase = tree.phase; try { tree.phase = "userEvent"; // If a 'fancytreekeydown' handler returns false, skip the default // handling (implemented by tree.nodeKeydown()). if(node){ res = tree._triggerNodeEvent("keydown", node, event); }else{ res = tree._triggerTreeEvent("keydown", event); } if ( res === "preventNav" ){ res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls } else if ( res !== false ){ res = tree._callHook("nodeKeydown", ctx); } return res; } finally { tree.phase = prevPhase; } }).on("click" + ns + " dblclick" + ns, function(event){ if(opts.disabled){ return true; } var ctx, et = FT.getEventTarget(event), node = et.node, tree = that.tree, prevPhase = tree.phase; if( !node ){ return true; // Allow bubbling of other events } ctx = tree._makeHookContext(node, event); // that.tree.debug("event(" + event.type + "): node: ", node); try { tree.phase = "userEvent"; switch(event.type) { case "click": ctx.targetType = et.type; return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx); case "dblclick": ctx.targetType = et.type; return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx); } // } catch(e) { // // var _ = null; // DT issue 117 // TODO // $.error(e); } finally { tree.phase = prevPhase; } }); }, /** Return the active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.tree.activeNode; }, /** Return the matching node or null. * @param {string} key * @returns {FancytreeNode} */ getNodeByKey: function(key) { return this.tree.getNodeByKey(key); }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.tree.rootNode; }, /** Return the current tree instance. * @returns {Fancytree} */ getTree: function() { return this.tree; } }); // $.ui.fancytree was created by the widget factory. Create a local shortcut: FT = $.ui.fancytree; /** * Static members in the `$.ui.fancytree` namespace.<br> * <br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access static members: * var node = $.ui.fancytree.getNode(element); * alert($.ui.fancytree.version); * </pre> * * @mixin Fancytree_Static */ $.extend($.ui.fancytree, /** @lends Fancytree_Static# */ { /** @type {string} */ version: "2.8.0", // Set to semver by 'grunt release' /** @type {string} */ buildType: "production", // Set to 'production' by 'grunt build' /** @type {int} */ debugLevel: 1, // Set to 1 by 'grunt build' // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel _nextId: 1, _nextNodeKey: 1, _extensions: {}, // focusTree: null, /** Expose class object as $.ui.fancytree._FancytreeClass */ _FancytreeClass: Fancytree, /** Expose class object as $.ui.fancytree._FancytreeNodeClass */ _FancytreeNodeClass: FancytreeNode, /* Feature checks to provide backwards compatibility */ jquerySupports: { // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at positionMyOfs: isVersionAtLeast($.ui.version, 1, 9) }, /** Throw an error if condition fails (debug method). * @param {boolean} cond * @param {string} msg */ assert: function(cond, msg){ return _assert(cond, msg); }, /** Return a function that executes *fn* at most every *timeout* ms. * @param {integer} timeout * @param {function} fn * @param {boolean} [invokeAsap=false] * @param {any} [ctx] */ debounce: function(timeout, fn, invokeAsap, ctx) { var timer; if(arguments.length === 3 && typeof invokeAsap !== "boolean") { ctx = invokeAsap; invokeAsap = false; } return function() { var args = arguments; ctx = ctx || this; invokeAsap && !timer && fn.apply(ctx, args); clearTimeout(timer); timer = setTimeout(function() { invokeAsap || fn.apply(ctx, args); timer = null; }, timeout); }; }, /** Write message to console if debugLevel >= 2 * @param {string} msg */ debug: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments); }, /** Write error message to console. * @param {string} msg */ error: function(msg){ consoleApply("error", arguments); }, /** Convert &lt;, &gt;, &amp;, &quot;, &#39;, &#x2F; to the equivalent entitites. * * @param {string} s * @returns {string} */ escapeHtml: function(s){ return ("" + s).replace(/[&<>"'\/]/g, function (s) { return ENTITY_MAP[s]; }); }, /** Make jQuery.position() arguments backwards compatible, i.e. if * jQuery UI version <= 1.8, convert * { my: "left+3 center", at: "left bottom", of: $target } * to * { my: "left center", at: "left bottom", of: $target, offset: "3 0" } * * See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at * and http://jsfiddle.net/mar10/6xtu9a4e/ */ fixPositionOptions: function(opts) { if( opts.offset || ("" + opts.my + opts.at ).indexOf("%") >= 0 ) { $.error("expected new position syntax (but '%' is not supported)"); } if( ! $.ui.fancytree.jquerySupports.positionMyOfs ) { var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined] myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.my), atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.at), // convert to numbers dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0), dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0); opts = $.extend({}, opts, { // make a copy and overwrite my: myParts[1] + " " + myParts[3], at: atParts[1] + " " + atParts[3] }); if( dx || dy ) { opts.offset = "" + dx + " " + dy; } } return opts; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTargetType: function(event){ return this.getEventTarget(event).type; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {object} Return a {node: FancytreeNode, type: TYPE} object * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTarget: function(event){ var tcn = event && event.target ? event.target.className : "", res = {node: this.getNode(event.target), type: undefined}; // We use a fast version of $(res.node).hasClass() // See http://jsperf.com/test-for-classname/2 if( /\bfancytree-title\b/.test(tcn) ){ res.type = "title"; }else if( /\bfancytree-expander\b/.test(tcn) ){ res.type = (res.node.hasChildren() === false ? "prefix" : "expander"); }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){ res.type = "checkbox"; }else if( /\bfancytree-icon\b/.test(tcn) ){ res.type = "icon"; }else if( /\bfancytree-node\b/.test(tcn) ){ // Somewhere near the title res.type = "title"; }else if( event && event.target && $(event.target).closest(".fancytree-title").length ) { // #228: clicking an embedded element inside a title res.type = "title"; } return res; }, /** Return a FancytreeNode instance from element. * * @param {Element | jQueryObject | Event} el * @returns {FancytreeNode} matching node or null */ getNode: function(el){ if(el instanceof FancytreeNode){ return el; // el already was a FancytreeNode }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } while( el ) { if(el.ftnode) { return el.ftnode; } el = el.parentNode; } return null; }, /* Return a Fancytree instance from element. * TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem * @param {Element | jQueryObject | Event} el * @returns {Fancytree} matching tree or null * / getTree: function(el){ if(el instanceof Fancytree){ return el; // el already was a Fancytree }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } ... return null; }, */ /** Write message to console if debugLevel >= 1 * @param {string} msg */ info: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments); }, /** Convert a keydown or mouse event to a canonical string like 'ctrl+a', 'ctrl+shift+f2', 'shift+leftdblclick'. * This is especially handy for switch-statements in event handlers. * @param {event} * @returns {string} */ eventToString: function(event) { // Poor-man's hotkeys. See here for a complete implementation: // https://github.com/jeresig/jquery.hotkeys var which = event.which, et = event.type, s = []; if( event.altKey ) { s.push("alt"); } if( event.ctrlKey ) { s.push("ctrl"); } if( event.metaKey ) { s.push("meta"); } if( event.shiftKey ) { s.push("shift"); } if( et === "click" || et === "dblclick" ) { s.push(MOUSE_BUTTONS[event.button] + et); } else { if( !IGNORE_KEYCODES[which] ) { s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() ); } } return s.join("+"); }, /* @deprecated: use eventToString(event) instead. */ keyEventToString: function(event) { this.warn("keyEventToString() is deprecated: use eventToString()"); return this.eventToString(event); }, /** * Parse tree data from HTML <ul> markup * * @param {jQueryObject} $ul * @returns {NodeData[]} */ parseHtml: function($ul) { // TODO: understand this: /*jshint validthis:true */ var extraClasses, i, l, iPos, tmp, tmp2, classes, className, $children = $ul.find(">li"), children = []; $children.each(function() { var allData, $li = $(this), $liSpan = $li.find(">span:first", this), $liA = $liSpan.length ? null : $li.find(">a:first"), d = { tooltip: null, data: {} }; if( $liSpan.length ) { d.title = $liSpan.html(); } else if( $liA && $liA.length ) { // If a <li><a> tag is specified, use it literally and extract href/target. d.title = $liA.html(); d.data.href = $liA.attr("href"); d.data.target = $liA.attr("target"); d.tooltip = $liA.attr("title"); } else { // If only a <li> tag is specified, use the trimmed string up to // the next child <ul> tag. d.title = $li.html(); iPos = d.title.search(/<ul/i); if( iPos >= 0 ){ d.title = d.title.substring(0, iPos); } } d.title = $.trim(d.title); // Make sure all fields exist for(i=0, l=CLASS_ATTRS.length; i<l; i++){ d[CLASS_ATTRS[i]] = undefined; } // Initialize to `true`, if class is set and collect extraClasses classes = this.className.split(" "); extraClasses = []; for(i=0, l=classes.length; i<l; i++){ className = classes[i]; if(CLASS_ATTR_MAP[className]){ d[className] = true; }else{ extraClasses.push(className); } } d.extraClasses = extraClasses.join(" "); // Parse node options from ID, title and class attributes tmp = $li.attr("title"); if( tmp ){ d.tooltip = tmp; // overrides <a title='...'> } tmp = $li.attr("id"); if( tmp ){ d.key = tmp; } // Add <li data-NAME='...'> as node.data.NAME allData = _getElementDataAsDict($li); if(allData && !$.isEmptyObject(allData)) { // #56: Allow to set special node.attributes from data-... for(i=0, l=NODE_ATTRS.length; i<l; i++){ tmp = NODE_ATTRS[i]; tmp2 = allData[tmp]; if( tmp2 != null ) { delete allData[tmp]; d[tmp] = tmp2; } } // All other data-... goes to node.data... $.extend(d.data, allData); } // Recursive reading of child nodes, if LI tag contains an UL tag $ul = $li.find(">ul:first"); if( $ul.length ) { d.children = $.ui.fancytree.parseHtml($ul); }else{ d.children = d.lazy ? undefined : null; } children.push(d); // FT.debug("parse ", d, children); }); return children; }, /** Add Fancytree extension definition to the list of globally available extensions. * * @param {object} definition */ registerExtension: function(definition){ _assert(definition.name != null, "extensions must have a `name` property."); _assert(definition.version != null, "extensions must have a `version` property."); $.ui.fancytree._extensions[definition.name] = definition; }, /** Inverse of escapeHtml(). * * @param {string} s * @returns {string} */ unescapeHtml: function(s){ var e = document.createElement("div"); e.innerHTML = s; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; }, /** Write warning message to console. * @param {string} msg */ warn: function(msg){ consoleApply("warn", arguments); } }); }(jQuery, window, document)); // Extending Fancytree // =================== // // See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code. // // Every extension should have a comment header containing some information // about the author, copyright and licensing. Also a pointer to the latest // source code. // Prefix with `/*!` so the comment is not removed by the minifier. /*! * jquery.fancytree.childcounter.js * * Add a child counter bubble to tree nodes. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ // To keep the global namespace clean, we wrap everything in a closure ;(function($, undefined) { // Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) "use strict"; // The [coding guidelines](http://contribute.jquery.org/style-guide/js/) // require jshint compliance. // But for this sample, we want to allow unused variables for demonstration purpose. /*jshint unused:false */ // Adding methods // -------------- // New member functions can be added to the `Fancytree` class. // This function will be available for every tree instance. // // var tree = $("#tree").fancytree("getTree"); // tree.countSelected(false); $.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){ var tree = this, treeOptions = tree.options; return tree.getSelectedNodes(topOnly).length; }; // The `FancytreeNode` class can also be easily extended. This would be called // like // // node.toUpper(); $.ui.fancytree._FancytreeNodeClass.prototype.toUpper = function(){ var node = this; return node.setTitle(node.title.toUpperCase()); }; // Finally, we can extend the widget API and create functions that are called // like so: // // $("#tree").fancytree("widgetMethod1", "abc"); $.ui.fancytree.prototype.widgetMethod1 = function(arg1){ var tree = this.tree; return arg1; }; // Register a Fancytree extension // ------------------------------ // A full blown extension, extension is available for all trees and can be // enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)): // // <script src="../src/jquery.fancytree.js" type="text/javascript"></script> // <script src="../src/jquery.fancytree.childcounter.js" type="text/javascript"></script> // ... // // $("#tree").fancytree({ // extensions: ["childcounter"], // childcounter: { // hideExpanded: true // }, // ... // }); // /* 'childcounter' extension */ $.ui.fancytree.registerExtension({ // Every extension must be registered by a unique name. name: "childcounter", // Version information should be compliant with [semver](http://semver.org) version: "1.0.0", // Extension specific options and their defaults. // This options will be available as `tree.options.childcounter.hideExpanded` options: { deep: true, hideZeros: true, hideExpanded: false }, // Attributes other than `options` (or functions) can be defined here, and // will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`. // They can also be accessed as `this._local.foo` from within the extension // methods. foo: 42, // Local functions are prefixed with an underscore '_'. // Callable as `this._local._appendCounter()`. _appendCounter: function(bar){ var tree = this; }, // **Override virtual methods for this extension.** // // Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'. // with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData) // for details) and an extended calling context:<br> // `this` : the Fancytree instance<br> // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br> // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree) // // See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html). /* Init */ // `treeInit` is triggered when a tree is initalized. We can set up classes or // bind event handlers here... treeInit: function(ctx){ var tree = this, // same as ctx.tree, opts = ctx.options, extOpts = ctx.options.childcounter; // Optionally check for dependencies with other extensions /* this._requireExtension("glyph", false, false); */ // Call the base implementation this._superApply(arguments); // Add a class to the tree container this.$container.addClass("fancytree-ext-childcounter"); }, // Destroy this tree instance (we only call the default implementation, so // this method could as well be omitted). treeDestroy: function(ctx){ this._superApply(arguments); }, // Overload the `renderTitle` hook, to append a counter badge nodeRenderTitle: function(ctx, title) { var node = ctx.node, extOpts = ctx.options.childcounter, count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter; // Let the base implementation render the title this._superApply(arguments); // Append a counter badge if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){ $("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count)); } }, // Overload the `setExpanded` hook, so the counters are updated nodeSetExpanded: function(ctx, flag, opts) { var tree = ctx.tree, node = ctx.node; // Let the base implementation expand/collapse the node, then redraw the title // after the animation has finished return this._superApply(arguments).always(function(){ tree.nodeRenderTitle(ctx); }); } // End of extension definition }); // End of namespace closure }(jQuery)); /*! * * jquery.fancytree.clones.js * Support faster lookup of nodes by key and shared ref-ids. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; $.error("Assertion failed" + msg); } } /* Return first occurrence of member from array. */ function _removeArrayMember(arr, elem) { // TODO: use Array.indexOf for IE >= 9 var i; for (i = arr.length - 1; i >= 0; i--) { if (arr[i] === elem) { arr.splice(i, 1); return true; } } return false; } // /** // * Calculate a 32 bit FNV-1a hash // * Found here: https://gist.github.com/vaiorabbit/5657561 // * Ref.: http://isthe.com/chongo/tech/comp/fnv/ // * // * @param {string} str the input value // * @param {boolean} [asString=false] set to true to return the hash value as // * 8-digit hex string instead of an integer // * @param {integer} [seed] optionally pass the hash of the previous chunk // * @returns {integer | string} // */ // function hashFnv32a(str, asString, seed) { // /*jshint bitwise:false */ // var i, l, // hval = (seed === undefined) ? 0x811c9dc5 : seed; // for (i = 0, l = str.length; i < l; i++) { // hval ^= str.charCodeAt(i); // hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); // } // if( asString ){ // // Convert to 8 digit hex string // return ("0000000" + (hval >>> 0).toString(16)).substr(-8); // } // return hval >>> 0; // } /** * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @author <a href="mailto:[email protected]">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:[email protected]">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} key ASCII only * @param {boolean} [asString=false] * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ function hashMurmur3(key, asString, seed) { /*jshint bitwise:false */ var h1b, k1, remainder = key.length & 3, bytes = key.length - remainder, h1 = seed, c1 = 0xcc9e2d51, c2 = 0x1b873593, i = 0; while (i < bytes) { k1 = ((key.charCodeAt(i) & 0xff)) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); } k1 = 0; switch (remainder) { /*jshint -W086:true */ case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; h1 ^= h1 >>> 16; if( asString ){ // Convert to 8 digit hex string return ("0000000" + (h1 >>> 0).toString(16)).substr(-8); } return h1 >>> 0; } // console.info(hashMurmur3("costarring")); // console.info(hashMurmur3("costarring", true)); // console.info(hashMurmur3("liquid")); // console.info(hashMurmur3("liquid", true)); /* * Return a unique key for node by calculationg the hash of the parents refKey-list */ function calcUniqueKey(node) { var key, path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; }); path = path.join("/"); key = "id_" + hashMurmur3(path, true); // node.debug(path + " -> " + key); return key; } /** * [ext-clones] Return a list of clone-nodes or null. * @param {boolean} [includeSelf=false] * @returns {FancytreeNode[] | null} * * @alias FancytreeNode#getCloneList * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){ var key, tree = this.tree, refList = tree.refMap[this.refKey] || null, keyMap = tree.keyMap; if( refList ) { key = this.key; // Convert key list to node list if( includeSelf ) { refList = $.map(refList, function(val){ return keyMap[val]; }); } else { refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; }); if( refList.length < 1 ) { refList = null; } } } return refList; }; /** * [ext-clones] Return true if this node has at least another clone with same refKey. * @returns {boolean} * * @alias FancytreeNode#isClone * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){ var refKey = this.refKey || null, refList = refKey && this.tree.refMap[refKey] || null; return !!(refList && refList.length > 1); }; /** * [ext-clones] Update key and/or refKey for an existing node. * @param {string} key * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#reRegister * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){ key = (key == null) ? null : "" + key; refKey = (refKey == null) ? null : "" + refKey; // this.debug("reRegister", key, refKey); var tree = this.tree, prevKey = this.key, prevRefKey = this.refKey, keyMap = tree.keyMap, refMap = tree.refMap, refList = refMap[prevRefKey] || null, // curCloneKeys = refList ? node.getCloneList(true), modified = false; // Key has changed: update all references if( key != null && key !== this.key ) { if( keyMap[key] ) { $.error("[ext-clones] reRegister(" + key + "): already exists: " + this); } // Update keyMap delete keyMap[prevKey]; keyMap[key] = this; // Update refMap if( refList ) { refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? key : e; }); } this.key = key; modified = true; } // refKey has changed if( refKey != null && refKey !== this.refKey ) { // Remove previous refKeys if( refList ){ if( refList.length === 1 ){ delete refMap[prevRefKey]; }else{ refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? null : e; }); } } // Add refKey if( refMap[refKey] ) { refMap[refKey].append(key); }else{ refMap[refKey] = [ this.key ]; } this.refKey = refKey; modified = true; } return modified; }; /** * [ext-clones] Return all nodes with a given refKey (null if not found). * @param {string} refKey * @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node * @returns {FancytreeNode[] | null} * @alias Fancytree#getNodesByRef * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){ var keyMap = this.keyMap, refList = this.refMap[refKey] || null; if( refList ) { // Convert key list to node list if( rootNode ) { refList = $.map(refList, function(val){ var node = keyMap[val]; return node.isDescendantOf(rootNode) ? node : null; }); }else{ refList = $.map(refList, function(val){ return keyMap[val]; }); } if( refList.length < 1 ) { refList = null; } } return refList; }; /** * [ext-clones] Replace a refKey with a new one. * @param {string} oldRefKey * @param {string} newRefKey * @alias Fancytree#changeRefKey * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) { var i, node, keyMap = this.keyMap, refList = this.refMap[oldRefKey] || null; if (refList) { for (i = 0; i < refList.length; i++) { node = keyMap[refList[i]]; node.refKey = newRefKey; } delete this.refMap[oldRefKey]; this.refMap[newRefKey] = refList; } }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "clones", version: "0.0.3", // Default options for this extension. options: { highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone }, treeCreate: function(ctx){ this._superApply(arguments); ctx.tree.refMap = {}; ctx.tree.keyMap = {}; }, treeInit: function(ctx){ this.$container.addClass("fancytree-ext-clones"); _assert(ctx.options.defaultKey == null); // Generate unique / reproducible default keys ctx.options.defaultKey = function(node){ return calcUniqueKey(node); }; // The default implementation loads initial data this._superApply(arguments); }, treeClear: function(ctx){ ctx.tree.refMap = {}; ctx.tree.keyMap = {}; return this._superApply(arguments); }, treeRegisterNode: function(ctx, add, node) { var refList, len, tree = ctx.tree, keyMap = tree.keyMap, refMap = tree.refMap, key = node.key, refKey = (node && node.refKey != null) ? "" + node.refKey : null; // ctx.tree.debug("clones.treeRegisterNode", add, node); if( key === "_statusNode" ){ return this._superApply(arguments); } if( add ) { if( keyMap[node.key] != null ) { $.error("clones.treeRegisterNode: node.key already exists: " + node); } keyMap[key] = node; if( refKey ) { refList = refMap[refKey]; if( refList ) { refList.push(key); if( refList.length === 2 && ctx.options.clones.highlightClones ) { // Mark peer node, if it just became a clone (no need to // mark current node, since it will be rendered later anyway) keyMap[refList[0]].renderStatus(); } } else { refMap[refKey] = [key]; } // node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]); } }else { if( keyMap[key] == null ) { $.error("clones.treeRegisterNode: node.key not registered: " + node.key); } delete keyMap[key]; if( refKey ) { refList = refMap[refKey]; // node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]); if( refList ) { len = refList.length; if( len <= 1 ){ _assert(len === 1); _assert(refList[0] === key); delete refMap[refKey]; }else{ _removeArrayMember(refList, key); // Unmark peer node, if this was the only clone if( len === 2 && ctx.options.clones.highlightClones ) { // node.debug("clones.treeRegisterNode: last =>", node.getCloneList()); keyMap[refList[0]].renderStatus(); } } // node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]); } } } return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { var $span, res, node = ctx.node; res = this._superApply(arguments); if( ctx.options.clones.highlightClones ) { $span = $(node[ctx.tree.statusClassPropName]); // Only if span already exists if( $span.length && node.isClone() ){ // node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones); $span.addClass("fancytree-clone"); } } return res; }, nodeSetActive: function(ctx, flag) { var res, scpn = ctx.tree.statusClassPropName, node = ctx.node; res = this._superApply(arguments); if( ctx.options.clones.highlightActiveClones && node.isClone() ) { $.each(node.getCloneList(true), function(idx, n){ // n.debug("clones.nodeSetActive: ", flag !== false); $(n[scpn]).toggleClass("fancytree-active-clone", flag !== false); }); } return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.dnd.js * * Drag-and-drop support. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ var didRegisterDnd = false; /* Convert number to string and prepend +/-; return empty string for 0.*/ function offsetString(n){ return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n)); } /* ***************************************************************************** * Drag and drop support */ function _initDragAndDrop(tree) { var dnd = tree.options.dnd || null; // Register 'connectToFancytree' option with ui.draggable if( dnd ) { _registerDnd(); } // Attach ui.draggable to this Fancytree instance if(dnd && dnd.dragStart ) { tree.widget.element.draggable($.extend({ addClasses: false, // DT issue 244: helper should be child of scrollParent: appendTo: tree.$container, // appendTo: "body", containment: false, delay: 0, distance: 4, revert: false, scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container scrollSpeed: 7, scrollSensitivity: 10, // Delegate draggable.start, drag, and stop events to our handler connectToFancytree: true, // Let source tree create the helper element helper: function(event) { var $helper, sourceNode = $.ui.fancytree.getNode(event.target), $nodeTag = $(sourceNode.span); if(!sourceNode){ // DT issue 211: might happen, if dragging a table *header* return "<div>ERROR?: helper requested but sourceNode not found</div>"; } // Only event and node argument is available $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>") .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar .append($nodeTag.find("span.fancytree-title").clone()); // Attach node reference to helper object $helper.data("ftSourceNode", sourceNode); // we return an unconnected element, so `draggable` will add this // to the parent specified as `appendTo` option return $helper; }, start: function(event, ui) { var sourceNode = ui.helper.data("ftSourceNode"); return !!sourceNode; // Abort dragging if no node could be found } }, tree.options.dnd.draggable)); } // Attach ui.droppable to this Fancytree instance if(dnd && dnd.dragDrop) { tree.widget.element.droppable($.extend({ addClasses: false, tolerance: "intersect", greedy: false /* activate: function(event, ui) { tree.debug("droppable - activate", event, ui, this); }, create: function(event, ui) { tree.debug("droppable - create", event, ui); }, deactivate: function(event, ui) { tree.debug("droppable - deactivate", event, ui); }, drop: function(event, ui) { tree.debug("droppable - drop", event, ui); }, out: function(event, ui) { tree.debug("droppable - out", event, ui); }, over: function(event, ui) { tree.debug("droppable - over", event, ui); } */ }, tree.options.dnd.droppable)); } } //--- Extend ui.draggable event handling -------------------------------------- function _registerDnd() { if(didRegisterDnd){ return; } // Register proxy-functions for draggable.start/drag/stop $.ui.plugin.add("draggable", "connectToFancytree", { start: function(event, ui) { // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 var draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null; if(sourceNode) { // Adjust helper offset, so cursor is slightly outside top/left corner draggable.offset.click.top = -2; draggable.offset.click.left = + 16; // Trigger dragStart event // TODO: when called as connectTo..., the return value is ignored(?) return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable); } }, drag: function(event, ui) { var isHelper, logObject, // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null, prevTargetNode = ui.helper.data("ftTargetNode") || null, targetNode = $.ui.fancytree.getNode(event.target); if(event.target && !targetNode){ // We got a drag event, but the targetNode could not be found // at the event location. This may happen, // 1. if the mouse jumped over the drag helper, // 2. or if a non-fancytree element is dragged // We ignore it: isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0; if(isHelper){ logObject = sourceNode || prevTargetNode || $.ui.fancytree; logObject.debug("Drag event over helper: ignored."); return; } } ui.helper.data("ftTargetNode", targetNode); // Leaving a tree node if(prevTargetNode && prevTargetNode !== targetNode ) { prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); } if(targetNode){ if(!targetNode.tree.options.dnd.dragDrop) { // not enabled as drop target } else if(targetNode === prevTargetNode) { // Moving over same node targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable); }else{ // Entering this node first time targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); } } // else go ahead with standard event handling }, stop: function(event, ui) { // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 var logObject, draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null, targetNode = ui.helper.data("ftTargetNode") || null, // mouseDownEvent = draggable._mouseDownEvent, eventType = event.type, dropped = (eventType === "mouseup" && event.which === 1); if(!dropped){ logObject = sourceNode || targetNode || $.ui.fancytree; logObject.debug("Drag was cancelled"); } if(targetNode) { if(dropped){ targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); } targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); } if(sourceNode){ sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable); } } }); didRegisterDnd = true; } /* ***************************************************************************** * */ $.ui.fancytree.registerExtension({ name: "dnd", version: "0.1.0", // Default options for this extension. options: { // Make tree nodes accept draggables autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering. draggable: null, // Additional options passed to jQuery draggable droppable: null, // Additional options passed to jQuery droppable focusOnClick: false, // Focus, although draggable cancels mousedown event (#270) // helper: null, // Callback // helperParent: null, // jQuery object (defaults to Fancytree container) preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. preventRecursiveMoves: true, // Prevent dropping nodes on own descendants // Events (drag support) dragStart: null, // Callback(sourceNode, data), return true, to enable dnd dragStop: null, // Callback(sourceNode, data) // Events (drop support) dragEnter: null, // Callback(targetNode, data) dragOver: null, // Callback(targetNode, data) dragDrop: null, // Callback(targetNode, data) dragLeave: null // Callback(targetNode, data) }, treeInit: function(ctx){ var tree = ctx.tree; this._superApply(arguments); // issue #270: draggable eats mousedown events if( tree.options.dnd.dragStart ){ tree.$container.on("mousedown", function(event){ if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) { var node = $.ui.fancytree.getNode(event); node.debug("Re-enable focus that was prevented by jQuery UI draggable."); // node.setFocus(); // $(node.span).closest(":tabbable").focus(); // $(event.target).trigger("focus"); // $(event.target).closest(":tabbable").trigger("focus"); setTimeout(function() { // #300 $(event.target).closest(":tabbable").focus(); }, 10); } }); } _initDragAndDrop(tree); }, /* Override key handler in order to cancel dnd on escape.*/ nodeKeydown: function(ctx) { var event = ctx.originalEvent; if( event.which === $.ui.keyCode.ESCAPE) { this._local._cancelDrag(); } return this._superApply(arguments); }, nodeClick: function(ctx) { // if( ctx.options.dnd.dragStart ){ // ctx.tree.$container.focus(); // } return this._superApply(arguments); }, /* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */ _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) { var markerOffsetX = 0, markerAt = "center", instData = this._local, $source = sourceNode ? $(sourceNode.span) : null, $target = $(targetNode.span); if( !instData.$dropMarker ) { instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>") .hide() .css({"z-index": 1000}) .prependTo($(this.$div).parent()); // .prependTo("body"); } // this.$dropMarker.attr("class", hitMode); if(hitMode === "after" || hitMode === "before" || hitMode === "over"){ // $source && $source.addClass("fancytree-drag-source"); // $target.addClass("fancytree-drop-target"); switch(hitMode){ case "before": instData .$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over") .addClass("fancytree-drop-before"); markerAt = "top"; break; case "after": instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over") .addClass("fancytree-drop-after"); markerAt = "bottom"; break; default: instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before") .addClass("fancytree-drop-over"); $target.addClass("fancytree-drop-target"); markerOffsetX = 8; } instData.$dropMarker .show() .position($.ui.fancytree.fixPositionOptions({ my: "left" + offsetString(markerOffsetX) + " center", at: "left " + markerAt, of: $target })); // helper.addClass("fancytree-drop-hover"); } else { // $source && $source.removeClass("fancytree-drag-source"); $target.removeClass("fancytree-drop-target"); instData.$dropMarker.hide(); // helper.removeClass("fancytree-drop-hover"); } if(hitMode === "after"){ $target.addClass("fancytree-drop-after"); } else { $target.removeClass("fancytree-drop-after"); } if(hitMode === "before"){ $target.addClass("fancytree-drop-before"); } else { $target.removeClass("fancytree-drop-before"); } if(accept === true){ if($source){ $source.addClass("fancytree-drop-accept"); } $target.addClass("fancytree-drop-accept"); helper.addClass("fancytree-drop-accept"); }else{ if($source){ $source.removeClass("fancytree-drop-accept"); } $target.removeClass("fancytree-drop-accept"); helper.removeClass("fancytree-drop-accept"); } if(accept === false){ if($source){ $source.addClass("fancytree-drop-reject"); } $target.addClass("fancytree-drop-reject"); helper.addClass("fancytree-drop-reject"); }else{ if($source){ $source.removeClass("fancytree-drop-reject"); } $target.removeClass("fancytree-drop-reject"); helper.removeClass("fancytree-drop-reject"); } }, /* * Handles drag'n'drop functionality. * * A standard jQuery drag-and-drop process may generate these calls: * * draggable helper(): * _onDragEvent("helper", sourceNode, null, event, null, null); * start: * _onDragEvent("start", sourceNode, null, event, ui, draggable); * drag: * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); * stop: * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("stop", sourceNode, null, event, ui, draggable); */ _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) { if(eventName !== "over"){ this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this); } var /*$helper, $helperParent,*/ nodeOfs, relPos, relPos2, enterResponse, hitMode, r, opts = this.options, dnd = opts.dnd, ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}), res = null, $nodeTag = $(node.span); switch (eventName) { // case "helper": // // Only event and node argument is available // $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>") // .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar // .append($nodeTag.find("span.fancytree-title").clone()); // // #345: helper parent is now set using draggable.appendTo // // $helperParent = dnd.helperParent || $("ul.fancytree-container", node.tree.$div); // // DT issue 244: helper should be child of scrollParent // // $helperParent.append($helper); // // Attach node reference to helper object // $helper.data("ftSourceNode", node); // // this.debug("helper=%o", $helper); // // this.debug("helper.sourceNode=%o", $helper.data("ftSourceNode")); // res = $helper; // break; case "start": if( node.isStatusNode() ) { res = false; } else if(dnd.dragStart) { res = dnd.dragStart(node, ctx); } if(res === false) { this.debug("tree.dragStart() cancelled"); //draggable._clear(); // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned) // TODO: call this._cancelDrag()? ui.helper.trigger("mouseup") .hide(); } else { $nodeTag.addClass("fancytree-drag-source"); } break; case "enter": if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){ r = false; }else{ r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null; } if(!r){ // convert null, undefined, false to false res = false; }else if ( $.isArray(r) ) { // TODO: also accept passing an object of this format directly res = { over: ($.inArray("over", r) >= 0), before: ($.inArray("before", r) >= 0), after: ($.inArray("after", r) >= 0) }; }else{ res = { over: ((r === true) || (r === "over")), before: ((r === true) || (r === "before")), after: ((r === true) || (r === "after")) }; } ui.helper.data("enterResponse", res); this.debug("helper.enterResponse: %o", res); break; case "over": enterResponse = ui.helper.data("enterResponse"); hitMode = null; if(enterResponse === false){ // Don't call dragOver if onEnter returned false. // break; } else if(typeof enterResponse === "string") { // Use hitMode from onEnter if provided. hitMode = enterResponse; } else { // Calculate hitMode from relative cursor position. nodeOfs = $nodeTag.offset(); relPos = { x: event.pageX - nodeOfs.left, y: event.pageY - nodeOfs.top }; relPos2 = { x: relPos.x / $nodeTag.width(), y: relPos.y / $nodeTag.height() }; if( enterResponse.after && relPos2.y > 0.75 ){ hitMode = "after"; } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){ hitMode = "after"; } else if(enterResponse.before && relPos2.y <= 0.25) { hitMode = "before"; } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) { hitMode = "before"; } else if(enterResponse.over) { hitMode = "over"; } // Prevent no-ops like 'before source node' // TODO: these are no-ops when moving nodes, but not in copy mode if( dnd.preventVoidMoves ){ if(node === otherNode){ this.debug(" drop over source node prevented"); hitMode = null; }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){ this.debug(" drop after source node prevented"); hitMode = null; }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){ this.debug(" drop before source node prevented"); hitMode = null; }else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){ this.debug(" drop last child over own parent prevented"); hitMode = null; } } // this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling()); ui.helper.data("hitMode", hitMode); } // Auto-expand node (only when 'over' the node, not 'before', or 'after') if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) { node.scheduleAction("expand", dnd.autoExpandMS); } if(hitMode && dnd.dragOver){ // TODO: http://code.google.com/p/dynatree/source/detail?r=625 ctx.hitMode = hitMode; res = dnd.dragOver(node, ctx); } // DT issue 332 // this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false); this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null); break; case "drop": hitMode = ui.helper.data("hitMode"); if(hitMode && dnd.dragDrop){ ctx.hitMode = hitMode; dnd.dragDrop(node, ctx); } break; case "leave": // Cancel pending expand request node.scheduleAction("cancel"); ui.helper.data("enterResponse", null); ui.helper.data("hitMode", null); this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined); if(dnd.dragLeave){ dnd.dragLeave(node, ctx); } break; case "stop": $nodeTag.removeClass("fancytree-drag-source"); if(dnd.dragStop){ dnd.dragStop(node, ctx); } break; default: $.error("Unsupported drag event: " + eventName); } return res; }, _cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } } }); }(jQuery, window, document)); /*! * jquery.fancytree.edit.js * * Make node titles editable. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ var isMac = /Mac/.test(navigator.platform), escapeHtml = $.ui.fancytree.escapeHtml, unescapeHtml = $.ui.fancytree.unescapeHtml; /** * [ext-edit] Start inline editing of current node title. * * @alias FancytreeNode#editStart * @requires Fancytree */ $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){ var $input, node = this, tree = this.tree, local = tree.ext.edit, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), eventData = { node: node, tree: tree, options: tree.options, isNew: $(node.span).hasClass("fancytree-edit-new"), orgTitle: node.title, input: null, dirty: false }; // beforeEdit may want to modify the title before editing if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) { return false; } $.ui.fancytree.assert(!local.currentNode, "recursive edit"); local.currentNode = this; local.eventData = eventData; // Disable standard Fancytree mouse- and key handling tree.widget._unbind(); // #116: ext-dnd prevents the blur event, so we have to catch outer clicks $(document).on("mousedown.fancytree-edit", function(event){ if( ! $(event.target).hasClass("fancytree-edit-input") ){ node.editEnd(true, event); } }); // Replace node with <input> $input = $("<input />", { "class": "fancytree-edit-input", type: "text", value: unescapeHtml(eventData.orgTitle) }); local.eventData.input = $input; if ( instOpts.adjustWidthOfs != null ) { $input.width($title.width() + instOpts.adjustWidthOfs); } if ( instOpts.inputCss != null ) { $input.css(instOpts.inputCss); } $title.html($input); // Focus <input> and bind keyboard handler $input .focus() .change(function(event){ $input.addClass("fancytree-edit-dirty"); }).keydown(function(event){ switch( event.which ) { case $.ui.keyCode.ESCAPE: node.editEnd(false, event); break; case $.ui.keyCode.ENTER: node.editEnd(true, event); return false; // so we don't start editmode on Mac } event.stopPropagation(); }).blur(function(event){ return node.editEnd(true, event); }); instOpts.edit.call(node, {type: "edit"}, eventData); }; /** * [ext-edit] Stop inline editing. * @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified) * @alias FancytreeNode#editEnd * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){ var newVal, node = this, tree = this.tree, local = tree.ext.edit, eventData = local.eventData, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), $input = $title.find("input.fancytree-edit-input"); // eventData.isNew = $(node.span).hasClass("fancytree-edit-new"); if( instOpts.trim ) { $input.val($.trim($input.val())); } newVal = $input.val(); // eventData.dirty = $input.hasClass("fancytree-edit-dirty") || ; eventData.dirty = ( newVal !== node.title ); // Find out, if saving is required if( applyChanges === false ) { // If true/false was passed, honor this (except in rename mode, if unchanged) eventData.save = false; } else if( eventData.isNew ) { // In create mode, we save everyting, except for empty text eventData.save = (newVal !== ""); } else { // In rename mode, we save everyting, except for empty or unchanged text eventData.save = eventData.dirty && (newVal !== ""); } // Allow to break (keep editor open), modify input, or re-define data.save if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){ return false; } if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){ return false; } $input .removeClass("fancytree-edit-dirty") .unbind(); // Unbind outer-click handler $(document).off(".fancytree-edit"); if( eventData.save ) { node.setTitle( escapeHtml(newVal) ); // $(node.span).removeClass("fancytree-edit-new"); node.setFocus(); }else{ if( eventData.isNew ) { node.remove(); node = eventData.node = null; local.relatedNode.setFocus(); } else { node.renderTitle(); node.setFocus(); } } local.eventData = null; local.currentNode = null; local.relatedNode = null; // Re-enable mouse and keyboard handling tree.widget._bind(); // Set keyboard focus, even if setFocus() claims 'nothing to do' $(tree.$container).focus(); eventData.input = null; instOpts.close.call(node, {type: "close"}, eventData); return true; }; /** * [ext-edit] Create a new child or sibling node and start edit mode. * * @param {String} [mode='child'] 'before', 'after', or 'child' * @param {Object} [init] NodeData (or simple title string) * @alias FancytreeNode#editCreateNode * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){ var newNode, that = this; mode = mode || "child"; if( init == null ) { init = { title: "" }; } else if( typeof init === "string" ) { init = { title: init }; } else { $.ui.fancytree.assert($.isPlainObject(init)); } // Make sure node is expanded (and loaded) in 'child' mode if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) { this.setExpanded().done(function(){ that.editCreateNode(mode, init); }); return; } newNode = this.addNode(init, mode); newNode.makeVisible(); $(newNode.span).addClass("fancytree-edit-new"); this.tree.ext.edit.relatedNode = this; newNode.editStart(); }; /** * [ext-edit] Check if any node in this tree in edit mode. * * @returns {FancytreeNode | null} * @alias Fancytree#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeClass.prototype.isEditing = function(){ return this.ext.edit.currentNode; }; /** * [ext-edit] Check if this node is in edit mode. * @returns {Boolean} true if node is currently beeing edited * @alias FancytreeNode#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){ return this.tree.ext.edit.currentNode === this; }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "edit", version: "0.2.0", // Default options for this extension. options: { adjustWidthOfs: 4, // null: don't adjust input size to content allowEmpty: false, // Prevent empty input inputCss: {minWidth: "3em"}, triggerCancel: ["esc", "tab", "click"], // triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"], triggerStart: ["f2", "shift+click", "mac+enter"], trim: true, // Trim whitespace before save // Events: beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available) beforeEdit: $.noop, // Return false to prevent edit mode close: $.noop, // Editor was removed edit: $.noop, // Editor was opened (available as data.input) // keypress: $.noop, // Not yet implemented save: $.noop // Save data.input.val() or return false to keep editor open }, // Local attributes currentNode: null, treeInit: function(ctx){ this._superApply(arguments); this.$container.addClass("fancytree-ext-edit"); }, nodeClick: function(ctx) { if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){ if( ctx.originalEvent.shiftKey ){ ctx.node.editStart(); return false; } } return this._superApply(arguments); }, nodeDblclick: function(ctx) { if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } return this._superApply(arguments); }, nodeKeydown: function(ctx) { switch( ctx.originalEvent.which ) { case 113: // [F2] if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } break; case $.ui.keyCode.ENTER: if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){ ctx.node.editStart(); return false; } break; } return this._superApply(arguments); } }); }(jQuery, window, document)); /*! * jquery.fancytree.filter.js * * Remove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ function _escapeRegex(str){ /*jshint regexdash:true */ return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1"); } $.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, leavesOnly){ var match, re, count = 0, hideMode = this.options.filter.mode === "hide"; // leavesOnly = !branchMode && this.options.filter.leavesOnly; leavesOnly = !!leavesOnly && !branchMode; // Default to 'match title substring (not case sensitive)' if(typeof filter === "string"){ match = _escapeRegex(filter); // make sure a '.' is treated literally re = new RegExp(".*" + match + ".*", "i"); filter = function(node){ return !!re.exec(node.title); }; } this.enableFilter = true; this.lastFilterArgs = arguments; this.$div.addClass("fancytree-ext-filter"); if( hideMode ){ this.$div.addClass("fancytree-ext-filter-hide"); } else { this.$div.addClass("fancytree-ext-filter-dimm"); } // Reset current filter this.visit(function(node){ delete node.match; delete node.subMatch; }); // Adjust node.hide, .match, .subMatch flags this.visit(function(node){ if ((!leavesOnly || node.children == null) && filter(node)) { count++; node.match = true; node.visitParents(function(p){ p.subMatch = true; }); if( branchMode ) { node.visit(function(p){ p.match = true; }); return "skip"; } } }); // Redraw this.render(); return count; }; /** * [ext-filter] Dimm or hide nodes. * * @param {function | string} filter * @param {boolean} [leavesOnly=false] * @returns {integer} count * @alias Fancytree#filterNodes * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, leavesOnly){ return this._applyFilterImpl(filter, false, leavesOnly); }; /** * @deprecated */ $.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){ this.warn("Fancytree.applyFilter() is deprecated since 2014-05-10. Use .filterNodes() instead."); return this.filterNodes.apply(this, arguments); }; /** * [ext-filter] Dimm or hide whole branches. * * @param {function | string} filter * @returns {integer} count * @alias Fancytree#filterBranches * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter){ return this._applyFilterImpl(filter, true, null); }; /** * [ext-filter] Reset the filter. * * @alias Fancytree#clearFilter * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){ this.visit(function(node){ delete node.match; delete node.subMatch; }); this.enableFilter = false; this.lastFilterArgs = null; this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide"); this.render(); }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "filter", version: "0.3.0", // Default options for this extension. options: { autoApply: true, // re-apply last filter if lazy data is loaded mode: "dimm" }, treeInit: function(ctx){ this._superApply(arguments); }, nodeLoadChildren: function(ctx, source) { return this._superApply(arguments).done(function() { if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) { ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs); } }); }, nodeRenderStatus: function(ctx) { // Set classes for current status var res, node = ctx.node, tree = ctx.tree, $span = $(node[tree.statusClassPropName]); res = this._superApply(arguments); // nothing to do, if node was not yet rendered if( !$span.length || !tree.enableFilter ) { return res; } $span .toggleClass("fancytree-match", !!node.match) .toggleClass("fancytree-submatch", !!node.subMatch) .toggleClass("fancytree-hide", !(node.match || node.subMatch)); return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.glyph.js * * Use glyph fonts as instead of icon sprites. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _getIcon(opts, type){ return opts.map[type]; } $.ui.fancytree.registerExtension({ name: "glyph", version: "0.2.0", // Default options for this extension. options: { map: { checkbox: "icon-check-empty", checkboxSelected: "icon-check", checkboxUnknown: "icon-check icon-muted", error: "icon-exclamation-sign", expanderClosed: "icon-caret-right", expanderLazy: "icon-angle-right", expanderOpen: "icon-caret-down", doc: "icon-file-alt", noExpander: "", // Default node icons. // (Use tree.options.iconClass(node) callback to define custom icons // based on node data) docOpen: "icon-file-alt", loading: "icon-refresh icon-spin", folder: "icon-folder-close-alt", folderOpen: "icon-folder-open-alt" } }, treeInit: function(ctx){ var tree = ctx.tree; this._superApply(arguments); tree.$container.addClass("fancytree-ext-glyph"); }, nodeRenderStatus: function(ctx) { var icon, span, node = ctx.node, $span = $(node.span), opts = ctx.options.glyph, // callback = opts.icon, map = opts.map // $span = $(node.span) ; this._superApply(arguments); if( node.isRoot() ){ return; } span = $span.children("span.fancytree-expander").get(0); if( span ){ if( node.isLoading() ){ icon = "loading"; }else if( node.expanded ){ icon = "expanderOpen"; }else if( node.isUndefined() ){ icon = "expanderLazy"; }else if( node.hasChildren() ){ icon = "expanderClosed"; }else{ icon = "noExpander"; } span.className = "fancytree-expander " + map[icon]; } if( node.tr ){ span = $("td", node.tr).children("span.fancytree-checkbox").get(0); }else{ span = $span.children("span.fancytree-checkbox").get(0); } if( span ){ icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox"); span.className = "fancytree-checkbox " + map[icon]; } // Icon (note that this does not match .fancytree-custom-icon, that might // be set by opts.iconClass) span = $span.children("span.fancytree-icon").get(0); if( span ){ if( node.folder ){ icon = node.expanded ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder"); }else{ icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc"); } span.className = "fancytree-icon " + icon; } }, nodeSetStatus: function(ctx, status, message, details) { var span, opts = ctx.options.glyph, node = ctx.node; this._superApply(arguments); if(node.parent){ span = $("span.fancytree-expander", node.span).get(0); }else{ span = $(".fancytree-statusnode-wait, .fancytree-statusnode-error", node[this.nodeContainerAttrName]) .find("span.fancytree-expander").get(0); } if( status === "loading"){ // $("span.fancytree-expander", ctx.node.span).addClass(_getIcon(opts, "loading")); span.className = "fancytree-expander " + _getIcon(opts, "loading"); }else if( status === "error"){ span.className = "fancytree-expander " + _getIcon(opts, "error"); } } }); }(jQuery, window, document)); /*! * jquery.fancytree.gridnav.js * * Support keyboard navigation for trees with embedded input controls. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ // Allow these navigation keys even when input controls are focused var KC = $.ui.keyCode, // which keys are *not* handled by embedded control, but passed to tree // navigation handler: NAV_KEYS = { "text": [KC.UP, KC.DOWN], "checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "select-one": [KC.LEFT, KC.RIGHT], "select-multiple": [KC.LEFT, KC.RIGHT] }; /* Calculate TD column index (considering colspans).*/ function getColIdx($tr, $td) { var colspan, td = $td.get(0), idx = 0; $tr.children().each(function () { if( this === td ) { return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return idx; } /* Find TD at given column index (considering colspans).*/ function findTdAtColIdx($tr, colIdx) { var colspan, res = null, idx = 0; $tr.children().each(function () { if( idx >= colIdx ) { res = $(this); return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return res; } /* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */ function findNeighbourTd($target, keyCode){ var $tr, colIdx, $td = $target.closest("td"), $tdNext = null; switch( keyCode ){ case KC.LEFT: $tdNext = $td.prev(); break; case KC.RIGHT: $tdNext = $td.next(); break; case KC.UP: case KC.DOWN: $tr = $td.parent(); colIdx = getColIdx($tr, $td); while( true ) { $tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next(); if( !$tr.length ) { break; } // Skip hidden rows if( $tr.is(":hidden") ) { continue; } // Find adjacent cell in the same column $tdNext = findTdAtColIdx($tr, colIdx); // Skip cells that don't conatain a focusable element if( $tdNext && $tdNext.find(":input").length ) { break; } } break; } return $tdNext; } /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "gridnav", version: "0.0.1", // Default options for this extension. options: { autofocusInput: false, // Focus first embedded input if node gets activated handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node }, treeInit: function(ctx){ // gridnav requires the table extension to be loaded before itself this._requireExtension("table", true, true); this._superApply(arguments); this.$container.addClass("fancytree-ext-gridnav"); // Activate node if embedded input gets focus (due to a click) this.$container.on("focusin", function(event){ var ctx2, node = $.ui.fancytree.getNode(event.target); if( node && !node.isActive() ){ // Call node.setActive(), but also pass the event ctx2 = ctx.tree._makeHookContext(node, event); ctx.tree._callHook("nodeSetActive", ctx2, true); } }); }, nodeSetActive: function(ctx, flag) { var $outer, opts = ctx.options.gridnav, node = ctx.node, event = ctx.originalEvent || {}, triggeredByInput = $(event.target).is(":input"); flag = (flag !== false); this._superApply(arguments); if( flag ){ if( ctx.options.titlesTabbable ){ if( !triggeredByInput ) { $(node.span).find("span.fancytree-title").focus(); node.setFocus(); } // If one node is tabbable, the container no longer needs to be ctx.tree.$container.attr("tabindex", "-1"); // ctx.tree.$container.removeAttr("tabindex"); } else if( opts.autofocusInput && !triggeredByInput ){ // Set focus to input sub input (if node was clicked, but not // when TAB was pressed ) $outer = $(node.tr || node.span); $outer.find(":input:enabled:first").focus(); } } }, nodeKeydown: function(ctx) { var inputType, handleKeys, $td, opts = ctx.options.gridnav, event = ctx.originalEvent, $target = $(event.target); // jQuery inputType = $target.is(":input:enabled") ? $target.prop("type") : null; // ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType); if( inputType && opts.handleCursorKeys ){ handleKeys = NAV_KEYS[inputType]; if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){ $td = findNeighbourTd($target, event.which); // ctx.node.debug("ignore keydown in input", event.which, handleKeys); if( $td && $td.length ) { $td.find(":input:enabled").focus(); // Prevent Fancytree default navigation return false; } } return true; } // ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType); return this._superApply(arguments); } }); }(jQuery, window, document)); /*! * jquery.fancytree.persist.js * * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @depends: jquery.cookie.js * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ var _assert = $.ui.fancytree.assert, ACTIVE = "active", EXPANDED = "expanded", FOCUS = "focus", SELECTED = "selected"; /* Recursively load lazy nodes * @param {string} mode 'load', 'expand', false */ function _loadLazyNodes(tree, local, keyList, mode, dfd) { var i, key, l, node, foundOne = false, deferredList = [], missingKeyList = []; keyList = keyList || []; dfd = dfd || $.Deferred(); for( i=0, l=keyList.length; i<l; i++ ) { key = keyList[i]; node = tree.getNodeByKey(key); if( node ) { if( mode && node.isUndefined() ) { foundOne = true; tree.debug("_loadLazyNodes: " + node + " is lazy: loading..."); if( mode === "expand" ) { deferredList.push(node.setExpanded()); } else { deferredList.push(node.load()); } } else { tree.debug("_loadLazyNodes: " + node + " already loaded."); node.setExpanded(); } } else { missingKeyList.push(key); tree.debug("_loadLazyNodes: " + node + " was not yet found."); } } $.when.apply($, deferredList).always(function(){ // All lazy-expands have finished if( foundOne && missingKeyList.length > 0 ) { // If we read new nodes from server, try to resolve yet-missing keys _loadLazyNodes(tree, local, missingKeyList, mode, dfd); } else { if( missingKeyList.length ) { tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList); for( i=0, l=missingKeyList.length; i<l; i++ ) { key = keyList[i]; local._appendKey(EXPANDED, keyList[i], false); } } dfd.resolve(); } }); return dfd; } /** * [ext-persist] Remove persistence cookies of the given type(s). * Called like * $("#tree").fancytree("getTree").clearCookies("active expanded focus selected"); * * @alias Fancytree#clearCookies * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){ var local = this.ext.persist, prefix = local.cookiePrefix; types = types || "active expanded focus selected"; if(types.indexOf(ACTIVE) >= 0){ local._data(prefix + ACTIVE, null); } if(types.indexOf(EXPANDED) >= 0){ local._data(prefix + EXPANDED, null); } if(types.indexOf(FOCUS) >= 0){ local._data(prefix + FOCUS, null); } if(types.indexOf(SELECTED) >= 0){ local._data(prefix + SELECTED, null); } }; /** * [ext-persist] Return persistence information from cookies * * Called like * $("#tree").fancytree("getTree").getPersistData(); * * @alias Fancytree#getPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){ var local = this.ext.persist, prefix = local.cookiePrefix, delim = local.cookieDelimiter, res = {}; res[ACTIVE] = local._data(prefix + ACTIVE); res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim); res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim); res[FOCUS] = local._data(prefix + FOCUS); return res; }; /* ***************************************************************************** * Extension code */ $.ui.fancytree.registerExtension({ name: "persist", version: "0.3.0", // Default options for this extension. options: { cookieDelimiter: "~", cookiePrefix: undefined, // 'fancytree-<treeId>-' by default cookie: { raw: false, expires: "", path: "", domain: "", secure: false }, expandLazy: false, // true: recursively expand and load lazy nodes overrideSource: true, // true: cookie takes precedence over `source` data attributes. store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore types: "active expanded focus selected" }, /* Generic read/write string data to cookie, sessionStorage or localStorage. */ _data: function(key, value){ var ls = this._local.localStorage; // null, sessionStorage, or localStorage if( value === undefined ) { return ls ? ls.getItem(key) : $.cookie(key); } else if ( value === null ) { if( ls ) { ls.removeItem(key); } else { $.removeCookie(key); } } else { if( ls ) { ls.setItem(key, value); } else { $.cookie(key, value, this.options.persist.cookie); } } }, /* Append `key` to a cookie. */ _appendKey: function(type, key, flag){ key = "" + key; // #90 var local = this._local, instOpts = this.options.persist, delim = instOpts.cookieDelimiter, cookieName = local.cookiePrefix + type, data = local._data(cookieName), keyList = data ? data.split(delim) : [], idx = $.inArray(key, keyList); // Remove, even if we add a key, so the key is always the last entry if(idx >= 0){ keyList.splice(idx, 1); } // Append key to cookie if(flag){ keyList.push(key); } local._data(cookieName, keyList.join(delim)); }, treeInit: function(ctx){ var tree = ctx.tree, opts = ctx.options, local = this._local, instOpts = this.options.persist; // For 'auto' or 'cookie' mode, the cookie plugin must be available _assert(instOpts.store === "localStore" || $.cookie, "Missing required plugin for 'persist' extension: jquery.cookie.js"); local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-"); local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0; local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0; local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0; local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0; if( instOpts.store === "cookie" || !window.localStorage ) { local.localStorage = null; } else { local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage; } // Bind init-handler to apply cookie state tree.$div.bind("fancytreeinit", function(event){ var cookie, dfd, i, keyList, node, prevFocus = local._data(local.cookiePrefix + FOCUS); // record this before node.setActive() overrides it; // tree.debug("document.cookie:", document.cookie); cookie = local._data(local.cookiePrefix + EXPANDED); keyList = cookie && cookie.split(instOpts.cookieDelimiter); if( local.storeExpanded ) { // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load' // Also remove expand-cookies for unmatched nodes dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null); } else { // nothing to do dfd = new $.Deferred().resolve(); } dfd.done(function(){ if(local.storeSelected){ cookie = local._data(local.cookiePrefix + SELECTED); if(cookie){ keyList = cookie.split(instOpts.cookieDelimiter); for(i=0; i<keyList.length; i++){ node = tree.getNodeByKey(keyList[i]); if(node){ if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){ // node.setSelected(); node.selected = true; node.renderStatus(); } }else{ // node is no longer member of the tree: remove from cookie also local._appendKey(SELECTED, keyList[i], false); } } } // In selectMode 3 we have to fix the child nodes, since we // only stored the selected *top* nodes if( tree.options.selectMode === 3 ){ tree.visit(function(n){ if( n.selected ) { n.fixSelection3AfterClick(); return "skip"; } }); } } if(local.storeActive){ cookie = local._data(local.cookiePrefix + ACTIVE); if(cookie && (opts.persist.overrideSource || !tree.activeNode)){ node = tree.getNodeByKey(cookie); if(node){ node.debug("persist: set active", cookie); // We only want to set the focus if the container // had the keyboard focus before node.setActive(true, {noFocus: true}); } } } if(local.storeFocus && prevFocus){ node = tree.getNodeByKey(prevFocus); if(node){ // node.debug("persist: set focus", cookie); if( tree.options.titlesTabbable ) { $(node.span).find(".fancytree-title").focus(); } else { $(tree.$container).focus(); } // node.setFocus(); } } tree._triggerTreeEvent("restore", null, {}); }); }); // Init the tree return this._superApply(arguments); }, nodeSetActive: function(ctx, flag, opts) { var res, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeActive){ local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null); } return res; }, nodeSetExpanded: function(ctx, flag, opts) { var res, node = ctx.node, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeExpanded){ local._appendKey(EXPANDED, node.key, flag); } return res; }, nodeSetFocus: function(ctx, flag) { var res, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if( local.storeFocus ) { local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null); } return res; }, nodeSetSelected: function(ctx, flag) { var res, selNodes, tree = ctx.tree, node = ctx.node, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeSelected){ if( tree.options.selectMode === 3 ){ // In selectMode 3 we only store the the selected *top* nodes. // De-selecting a node may also de-select some parents, so we // calculate the current status again selNodes = $.map(tree.getSelectedNodes(true), function(n){ return n.key; }); selNodes = selNodes.join(ctx.options.persist.cookieDelimiter); local._data(local.cookiePrefix + SELECTED, selNodes); } else { local._appendKey(SELECTED, node.key, flag); } } return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.table.js * * Render tree as table (aka 'treegrid', 'tabletree'). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ msg = msg || ""; if(!cond){ $.error("Assertion failed " + msg); } } function insertSiblingAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } /* Show/hide all rows that are structural descendants of `parent`. */ function setChildRowVisibility(parent, flag) { parent.visit(function(node){ var tr = node.tr; // currentFlag = node.hide ? false : flag; // fix for ext-filter if(tr){ tr.style.display = (node.hide || !flag) ? "none" : ""; } if(!node.expanded){ return "skip"; } }); } /* Find node that is rendered in previous row. */ function findPrevRowNode(node){ var i, last, prev, parent = node.parent, siblings = parent ? parent.children : null; if(siblings && siblings.length > 1 && siblings[0] !== node){ // use the lowest descendant of the preceeding sibling i = $.inArray(node, siblings); prev = siblings[i - 1]; _assert(prev.tr); // descend to lowest child (with a <tr> tag) while(prev.children){ last = prev.children[prev.children.length - 1]; if(!last.tr){ break; } prev = last; } }else{ // if there is no preceding sibling, use the direct parent prev = parent; } return prev; } $.ui.fancytree.registerExtension({ name: "table", version: "0.2.0", // Default options for this extension. options: { checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx) customStatus: false, // true: generate renderColumns events for status nodes indentation: 16, // indent every node level by 16px nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0) }, // Overide virtual methods for this extension. // `this` : is this extension object // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree) treeInit: function(ctx){ var i, $row, tdRole, tree = ctx.tree, $table = tree.widget.element; $table.addClass("fancytree-container fancytree-ext-table"); tree.tbody = $table.find("> tbody")[0]; tree.columnCount = $("thead >tr >th", $table).length; $(tree.tbody).empty(); tree.rowFragment = document.createDocumentFragment(); $row = $("<tr />"); tdRole = ""; if(ctx.options.aria){ $row.attr("role", "row"); tdRole = " role='gridcell'"; } for(i=0; i<tree.columnCount; i++) { if(ctx.options.table.nodeColumnIdx === i){ $row.append("<td" + tdRole + "><span class='fancytree-node' /></td>"); }else{ $row.append("<td" + tdRole + " />"); } } tree.rowFragment.appendChild($row.get(0)); // Make sure that status classes are set on the node's <tr> elements tree.statusClassPropName = "tr"; tree.ariaPropName = "tr"; this.nodeContainerAttrName = "tr"; this._superApply(arguments); // standard Fancytree created a root UL $(tree.rootNode.ul).remove(); tree.rootNode.ul = null; tree.$container = $table; // Add container to the TAB chain this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1"); if(this.options.aria){ tree.$container .attr("role", "treegrid") .attr("aria-readonly", true); } }, /* Called by nodeRender to sync node order with tag order.*/ // nodeFixOrder: function(ctx) { // }, nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveChildMarkup()"); node.visit(function(n){ if(n.tr){ $(n.tr).remove(); n.tr = null; } }); }, nodeRemoveMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveMarkup()"); if(node.tr){ $(node.tr).remove(); node.tr = null; } this.nodeRemoveChildMarkup(ctx); }, /* Override standard render. */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx, tree = ctx.tree, node = ctx.node, opts = ctx.options, isRootNode = !node.parent; if( !_recursive ){ ctx.hasCollapsedParents = node.parent && !node.parent.expanded; } // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr)); if( !isRootNode ){ if(!node.tr){ if( ctx.hasCollapsedParents /*&& !node.parent.tr*/ ) { // #166: we assume that the parent will be (recursively) rendered // later anyway. node.debug("nodeRender ignored due to unrendered parent"); return; } // Create new <tr> after previous row newRow = tree.rowFragment.firstChild.cloneNode(true); prevNode = findPrevRowNode(node); // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key); _assert(prevNode); if(collapsed === true && _recursive){ // hide all child rows, so we can use an animation to show it later newRow.style.display = "none"; }else if(deep && ctx.hasCollapsedParents){ // also hide this row if deep === true but any parent is collapsed newRow.style.display = "none"; // newRow.style.color = "red"; } if(!prevNode.tr){ _assert(!prevNode.parent, "prev. row must have a tr, or is system root"); tree.tbody.appendChild(newRow); }else{ insertSiblingAfter(prevNode.tr, newRow); } node.tr = newRow; if( node.key && opts.generateIds ){ node.tr.id = opts.idPrefix + node.key; } node.tr.ftnode = node; if(opts.aria){ // TODO: why doesn't this work: // node.li.role = "treeitem"; $(node.tr).attr("aria-labelledby", "ftal_" + node.key); } node.span = $("span.fancytree-node", node.tr).get(0); // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // Allow tweaking, binding, after node was created for the first time // tree._triggerNodeEvent("createNode", ctx); if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } } else { if( force ) { // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // triggers renderColumns() } else { // Update element classes according to node state this.nodeRenderStatus(ctx); } } } // Allow tweaking after node state was rendered // tree._triggerNodeEvent("renderNode", ctx); if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } // Visit child nodes // Add child markup children = node.children; if(children && (isRootNode || deep || node.expanded)){ for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded; this.nodeRender(subCtx, force, deep, collapsed, true); } } // Make sure, that <tr> order matches node.children order. if(children && !_recursive){ // we only have to do it once, for the root branch prevTr = node.tr || null; firstTr = tree.tbody.firstChild; // Iterate over all descendants node.visit(function(n){ if(n.tr){ if(!n.parent.expanded && n.tr.style.display !== "none"){ // fix after a node was dropped over a collapsed n.tr.style.display = "none"; setChildRowVisibility(n, false); } if(n.tr.previousSibling !== prevTr){ node.debug("_fixOrder: mismatch at node: " + n); var nextTr = prevTr ? prevTr.nextSibling : firstTr; tree.tbody.insertBefore(n.tr, nextTr); } prevTr = n.tr; } }); } // Update element classes according to node state // if(!isRootNode){ // this.nodeRenderStatus(ctx); // } }, nodeRenderTitle: function(ctx, title) { var $cb, node = ctx.node, opts = ctx.options; this._superApply(arguments); // Move checkbox to custom column if(opts.checkbox && opts.table.checkboxColumnIdx != null ){ $cb = $("span.fancytree-checkbox", node.span).detach(); $(node.tr).find("td:first").html($cb); } // Let user code write column content // ctx.tree._triggerNodeEvent("renderColumns", node); // Update element classes according to node state if( ! node.isRoot() ){ this.nodeRenderStatus(ctx); } if( !opts.table.customStatus && node.isStatusNode() ) { // default rendering for status node: leave other cells empty } else if ( opts.renderColumns ) { opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx); } }, nodeRenderStatus: function(ctx) { var indent, node = ctx.node, opts = ctx.options; this._superApply(arguments); $(node.tr).removeClass("fancytree-node"); // indent indent = (node.getLevel() - 1) * opts.table.indentation; $(node.span).css({marginLeft: indent + "px"}); }, /* Expand node, return Deferred.promise. */ nodeSetExpanded: function(ctx, flag, opts) { var dfd = new $.Deferred(), subOpts = $.extend({}, opts, {noEvents: true, noAnimation: true}); opts = opts || {}; function _afterExpand(ok) { flag = (flag !== false); setChildRowVisibility(ctx.node, flag); if( ok ) { if( flag && ctx.options.autoScroll && !opts.noAnimation && ctx.node.hasChildren() ) { // Scroll down to last child, but keep current node visible ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){ if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); }); } else { if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); } } else { if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.rejectWith(ctx.node); } } // Call base-expand with disabled events and animation this._super(ctx, flag, subOpts).done(function () { _afterExpand(true); }).fail(function () { _afterExpand(false); }); return dfd.promise(); }, nodeSetStatus: function(ctx, status, message, details) { if(status === "ok"){ var node = ctx.node, firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $(firstChild.tr).remove(); } } return this._superApply(arguments); }, treeClear: function(ctx) { this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode)); return this._superApply(arguments); } /*, treeSetFocus: function(ctx, flag) { // alert("treeSetFocus" + ctx.tree.$container); ctx.tree.$container.focus(); $.ui.fancytree.focusTree = ctx.tree; }*/ }); }(jQuery, window, document)); /*! * jquery.fancytree.themeroller.js * * Enable jQuery UI ThemeRoller styles. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @see http://jqueryui.com/themeroller/ * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "themeroller", version: "0.0.1", // Default options for this extension. options: { activeClass: "ui-state-active", foccusClass: "ui-state-focus", hoverClass: "ui-state-hover", selectedClass: "ui-state-highlight" }, treeInit: function(ctx){ this._superApply(arguments); var $el = ctx.widget.element; if($el[0].nodeName === "TABLE"){ $el.addClass("ui-widget ui-corner-all"); $el.find(">thead tr").addClass("ui-widget-header"); $el.find(">tbody").addClass("ui-widget-conent"); }else{ $el.addClass("ui-widget ui-widget-content ui-corner-all"); } $el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){ var node = $.ui.fancytree.getNode(event.target), flag = (event.type === "mouseenter"); node.debug("hover: " + flag); $(node.span).toggleClass("ui-state-hover ui-corner-all", flag); }); }, treeDestroy: function(ctx){ this._superApply(arguments); ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all"); }, nodeRenderStatus: function(ctx){ var node = ctx.node, $el = $(node.span); this._superApply(arguments); /* .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons. */ $el.toggleClass("ui-state-active", node.isActive()); $el.toggleClass("ui-state-focus", node.hasFocus()); $el.toggleClass("ui-state-highlight", node.isSelected()); // node.debug("ext-themeroller.nodeRenderStatus: ", node.span.className); } }); }(jQuery, window, document)); /*! * jquery.fancytree.wide.js * Support for 100% wide selection bars. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.8.0 * @date 2015-02-08T17:56 */ ;(function($, window, document, undefined) { "use strict"; var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"] /******************************************************************************* * Private functions and variables */ // var _assert = $.ui.fancytree.assert; /* Calculate inner width without scrollbar */ // function realInnerWidth($el) { // // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/ // // inst.contWidth = parseFloat(this.$container.css("width"), 10); // // 'Client width without scrollbar' - 'padding' // return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10)); // } /* Create a global embedded CSS style for the tree. */ function defineHeadStyleElement(id, cssText) { id = "fancytree-style-" + id; var $headStyle = $("#" + id); if( !cssText ) { $headStyle.remove(); return null; } if( !$headStyle.length ) { $headStyle = $("<style />") .attr("id", id) .addClass("fancytree-style") .prop("type", "text/css") .appendTo("head"); } try { $headStyle.html(cssText); } catch ( e ) { // fix for IE 6-8 $headStyle[0].styleSheet.cssText = cssText; } return $headStyle; } /* Calculate the CSS rules that indent title spans. */ function renderLevelCss(containerId, depth, levelOfs, lineOfs, measureUnit) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for(i = 0; i < depth; i++) { rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }"); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push("#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title " + "{ padding-left: 3px; position: static; width: auto; }"); return rules.join("\n"); } // /** // * [ext-wide] Recalculate the width of the selection bar after the tree container // * was resized.<br> // * May be called explicitly on container resize, since there is no resize event // * for DIV tags. // * // * @alias Fancytree#wideUpdate // * @requires jquery.fancytree.wide.js // */ // $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){ // var inst = this.ext.wide, // prevCw = inst.contWidth, // prevLo = inst.lineOfs; // inst.contWidth = realInnerWidth(this.$container); // // Each title is precceeded by 2 or 3 icons (16px + 3 margin) // // + 1px title border and 3px title padding // // TODO: use code from treeInit() below // inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19; // if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) { // this.debug("wideUpdate: " + inst.contWidth); // this.visit(function(node){ // node.tree._callHook("nodeRenderTitle", node); // }); // } // }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "wide", version: "0.0.3", // Default options for this extension. options: { iconWidth: null, // Adjust this if @fancy-icon-width != "16px" iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px" levelOfs: null // Adjust this if ul padding != "16px" }, treeCreate: function(ctx){ this._superApply(arguments); this.$container.addClass("fancytree-ext-wide"); var containerId, cssText, iconSpacingUnit, iconWidthUnit, levelOfsUnit, instOpts = ctx.options.wide, // css sniffing $dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />") .appendTo(ctx.tree.$container), $dummyIcon = $dummyLI.find(".fancytree-icon"), $dummyUL = $dummyLI.find("ul"), // $dummyTitle = $dummyLI.find(".fancytree-title"), iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"), iconWidth = instOpts.iconWidth || $dummyIcon.css("width"), levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left"); $dummyLI.remove(); iconSpacingUnit = iconSpacing.match(reNumUnit)[2]; iconSpacing = parseFloat(iconSpacing, 10); iconWidthUnit = iconWidth.match(reNumUnit)[2]; iconWidth = parseFloat(iconWidth, 10); levelOfsUnit = levelOfs.match(reNumUnit)[2]; if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit ) { $.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit"); } this._local.measureUnit = iconWidthUnit; this._local.levelOfs = parseFloat(levelOfs); this._local.lineOfs = (ctx.options.checkbox ? 3 : 2) * (iconWidth + iconSpacing) + iconSpacing; this._local.maxDepth = 10; // Get/Set a unique Id on the container (if not already exists) containerId = this.$container.uniqueId().attr("id"); // Generated css rules for some levels (extended on demand) cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); }, treeDestroy: function(ctx){ // Remove generated css rules defineHeadStyleElement(this.$container.attr("id"), null); return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { var containerId, cssText, res, node = ctx.node, level = node.getLevel(); res = this._superApply(arguments); // Generate some more level-n rules if required if( level > this._local.maxDepth ) { containerId = this.$container.attr("id"); this._local.maxDepth *= 2; node.debug("Define global ext-wide css up to level " + this._local.maxDepth); cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); } // Add level-n class to apply indentation padding. // (Setting element style would not work, since it cannot easily be // overriden while animations run) $(node.span).addClass("fancytree-level-" + level); return res; } }); }(jQuery, window, document));
src/icons/IosArrowThinUp.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosArrowThinUp extends React.Component { render() { if(this.props.bare) { return <g> <path d="M349.7,189.8c-3.1,3.1-8,3-11.3,0L264,123.4V408c0,4.4-3.6,8-8,8c-4.4,0-8-3.6-8-8V123.4l-74.4,66.3 c-3.4,2.9-8.1,3.2-11.2,0.1c-3.1-3.1-3.3-8.5-0.1-11.4c0,0,87-79.2,88-80s2.8-2.4,5.7-2.4s4.9,1.6,5.7,2.4s88,80,88,80 c1.5,1.5,2.3,3.6,2.3,5.7C352,186.2,351.2,188.2,349.7,189.8z"></path> </g>; } return <IconBase> <path d="M349.7,189.8c-3.1,3.1-8,3-11.3,0L264,123.4V408c0,4.4-3.6,8-8,8c-4.4,0-8-3.6-8-8V123.4l-74.4,66.3 c-3.4,2.9-8.1,3.2-11.2,0.1c-3.1-3.1-3.3-8.5-0.1-11.4c0,0,87-79.2,88-80s2.8-2.4,5.7-2.4s4.9,1.6,5.7,2.4s88,80,88,80 c1.5,1.5,2.3,3.6,2.3,5.7C352,186.2,351.2,188.2,349.7,189.8z"></path> </IconBase>; } };IosArrowThinUp.defaultProps = {bare: false}
ajax/libs/angular.js/0.9.3/angular-scenario.js
athanclark/cdnjs
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function( window, undefined ) { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context ) { this.context = document; this[0] = document.body; this.selector = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); if ( elem ) { // 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: $("TAG") } else if ( !context && /^\w+$/.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // 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 jQuery( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.4.2", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || jQuery(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // 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 object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // 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 ) { window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 13 ); } // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); } // Reset the list of functions readyList = null; } // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { return jQuery.ready(); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { return toString.call(obj) === "[object Array]"; }, 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 || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwnProperty.call(obj, "constructor") && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { 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 || hasOwnProperty.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, trim: function( text ) { return (text || "").replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { if ( !inv !== !callback( elems[ i ], i ) ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function function access( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; } function now() { return (new Date).getTime(); } (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0]; // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText insted) style: /red/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: div.getElementsByTagName("input")[0].value === "on", // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected, parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null, // Will be defined later deleteExpando: true, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null }; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; document.body.removeChild( div ).style.display = 'none'; div = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var expando = "jQuery" + now(), uuid = 0, windowData = {}; jQuery.extend({ cache: {}, expando:expando, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, "object": true, "applet": true }, data: function( elem, name, data ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache; if ( !id && typeof name === "string" && data === undefined ) { return null; } // Compute a unique ID for the element if ( !id ) { id = ++uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { elem[ expando ] = id; thisCache = cache[ id ] = jQuery.extend(true, {}, name); } else if ( !cache[ id ] ) { elem[ expando ] = id; cache[ id ] = {}; } thisCache = cache[ id ]; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } // Completely remove the data cache delete cache[ id ]; } } }); jQuery.fn.extend({ data: function( key, value ) { if ( typeof key === "undefined" && this.length ) { return jQuery.data( this[0] ); } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { jQuery.data( this, key, value ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i, elem ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspace = /\s+/, rreturn = /\r/g, rspecialurl = /href|src|style/, rtype = /(button|input)/i, rfocusable = /(button|input|object|select|textarea)/i, rclickable = /^(a|area)$/i, rradiocheck = /radio|checkbox/; jQuery.fn.extend({ attr: function( name, value ) { return access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split(rspace); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery.data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( value === undefined ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { return (elem.attributes.value || {}).specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc 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; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Typecast each time if the value is a Function and the appended // value is therefore different each time. if ( typeof val === "number" ) { val += ""; } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // 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/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // Using attr for specific style information is now deprecated. Use style instead. return jQuery.style( elem, name, value ); } }); var rnamespaces = /\.(.*)$/, fcleanup = function( nm ) { return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { return "\\" + ch; }); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { elem = window; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery.data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events = elemData.events || {}, eventHandle = elemData.handle, eventHandle; if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; handleObj.guid = handler.guid; // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)") } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( var j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( var j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var target = event.target, old, isClick = jQuery.nodeName(target, "a") && type === "click", special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ type ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + type ]; if ( old ) { target[ "on" + type ] = null; } jQuery.event.triggered = true; target[ type ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( old ) { target[ "on" + type ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace, events; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); } var events = jQuery.data(this, "events"), handlers = events[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, arguments ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { event.which = event.charCode || event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) ); }, remove: function( handleObj ) { var remove = true, type = handleObj.origType.replace(rnamespaces, ""); jQuery.each( jQuery.data(this, "events").live || [], function() { if ( type === this.origType.replace(rnamespaces, "") ) { remove = false; return false; } }); if ( remove ) { jQuery.event.remove( this, handleObj.origType, liveHandler ); } } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( this.setInterval ) { this.onbeforeunload = eventHandle; } return false; }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; var removeEvent = document.removeEventListener ? function( elem, type, handle ) { elem.removeEventListener( type, handle, false ); } : function( elem, type, handle ) { elem.detachEvent( "on" + type, handle ); }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[ expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); } // otherwise set the returnValue property of the original event to false (IE) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { return trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var formElems = /textarea|input|select/i, changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information/focus[in] is not needed anymore beforeactivate: function( e ) { var elem = e.target; jQuery.data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return formElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return formElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { this.addEventListener( orig, handler, true ); }, teardown: function() { this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler context.each(function(){ jQuery.event.add( this, liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); }); } else { // unbind live handler context.unbind( liveConvert( type, selector ), fn ); } } return this; } }); function liveHandler( event ) { var stop, elems = [], selectors = [], args = arguments, related, match, handleObj, elem, j, i, l, data, events = jQuery.data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( match[i].selector === handleObj.selector ) { elem = match[i].elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) { stop = false; break; } } return stop; } function liveConvert( type, selector ) { return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { window.attachEvent("onunload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ return "\\" + (num - 0 + 1); })); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return a.compareDocumentPosition ? -1 : 1; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return a.ownerDocument ? -1 : 1; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Utility function for retreiving the text value of an array of DOM nodes function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date).getTime(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); root = form = null; // release memory in IE })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); } (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = getText; jQuery.isXMLDoc = isXML; jQuery.contains = contains; return; window.Sizzle = Sizzle; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, slice = Array.prototype.slice; // Implement the identical functionality for filter and not var winnow = function( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); }; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { if ( jQuery.isArray( selectors ) ) { var ret = [], cur = this[0], match, matches = {}, selector; if ( cur && selectors.length ) { for ( var i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur }); delete matches[selector]; } } cur = cur.parentNode; } } return ret; } var pos = jQuery.expr.match.POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; return this.map(function( i, cur ) { while ( cur && cur.ownerDocument && cur !== context ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { return cur; } cur = cur.parentNode; } return null; }); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // 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 || this.context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[dir]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<script|<object|<embed|<option|<style/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) fcloseTag = function( all, front, tag ) { return rselfClosing.test( tag ) ? all : front + "></" + tag + ">"; }, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery(this); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(/=([^="'>\s]+\/)>/g, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, fcloseTag); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery(this), old = self.html(); self.empty().append(function(){ return value.call( this, i, old ); }); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery(value).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery(this).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, value = args[0], scripts = [], fragment, parent; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(true) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }); function cloneCopyEvent(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } function buildFragment( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; } jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, fcloseTag); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); } else { removeEvent( elem, type, data.handle ); } } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); // exclude the following css properties to add px var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); }; jQuery.extend({ style: function( elem, name, value ) { // don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // ignore negative width and height values #1599 if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { value = undefined; } var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } name = name.replace(rdashAlpha, fcamelCase); if ( set ) { style[ name ] = value; } return style[ name ]; }, css: function( elem, name, force, extra ) { if ( name === "width" || name === "height" ) { var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; function getWH() { val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; } else { val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; } }); } if ( elem.offsetWidth !== 0 ) { getWH(); } else { jQuery.swap( elem, props, getWH ); } return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { var ret, style = elem.style, filter; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { ret = ropacity.test(elem.currentStyle.filter || "") ? (parseFloat(RegExp.$1) / 100) + "" : ""; return ret === "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } if ( !force && style && style[ name ] ) { ret = style[ name ]; } else if ( getComputedStyle ) { // Only "float" is needed here if ( rfloat.test( name ) ) { name = "float"; } name = name.replace( rupper, "-$1" ).toLowerCase(); var defaultView = elem.ownerDocument.defaultView; if ( !defaultView ) { return null; } var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) { ret = computedStyle.getPropertyValue( name ); } // We should always get a number back from opacity if ( name === "opacity" && ret === "" ) { ret = "1"; } } else if ( elem.currentStyle ) { var camelCase = name.replace(rdashAlpha, fcamelCase); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = camelCase === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) { elem.style[ name ] = old[ name ]; } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = now(), rscript = /<script(.|\s)*?\/script>/gi, rselectTextarea = /select|textarea/i, rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, jsre = /=\?(&|$)/, rquery = /\?/, rts = /(\?|&)_=.*?(&|$)/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, // Keep a copy of the old load method _load = jQuery.fn.load; jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" ) { return _load.call( this, url ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div />") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; }, serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function() { return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function( i, elem ) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function( val, i ) { return { name: elem.name, value: val }; }) : { name: elem.name, value: val }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { jQuery.fn[o] = function( f ) { return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7 (can't request local files), // so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); var jsonp, status, data, callbackContext = origSettings && origSettings.context || s, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data || origSettings && origSettings.contentType ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { trigger("ajaxSend", [xhr, s]); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { complete(); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(err) { status = "parsererror"; errMsg = err; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { success(); } } else { jQuery.handleError(s, xhr, status, errMsg); } // Fire the complete handlers complete(); if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { oldAbort.call( xhr ); } onreadystatechange( "abort" ); }; } catch(e) { } // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, data, status, xhr ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [xhr, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, xhr, status); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || // Opera returns 0 when status is 304 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } // Opera returns 0 when status is 304 return xhr.status === 304 || xhr.status === 0; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = []; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray(a) || a.jquery ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[prefix] ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); function buildParams( prefix, obj ) { if ( jQuery.isArray(obj) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || /\[\]$/.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v ); }); } else { // Serialize scalar item. add( prefix, obj ); } } function add( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : value; s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); } } }); var elemdisplay = {}, rfxtypes = /toggle|show|hide/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, callback ) { if ( speed || speed === 0) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var nodeName = this[i].nodeName, display; if ( elemdisplay[ nodeName ] ) { display = elemdisplay[ nodeName ]; } else { var elem = jQuery("<" + nodeName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) { display = "block"; } elem.remove(); elemdisplay[ nodeName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; } return this; } }, hide: function( speed, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) { jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2); } return this; }, fadeTo: function( speed, to, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { var opt = jQuery.extend({}, optall), p, hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = p.replace(rdashAlpha, fcamelCase); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( ( p === "height" || p === "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, callback ) { return this.animate( props, speed, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? 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 : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { this.elem.style.display = "block"; } }, // Get the current size cur: function( force ) { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(jQuery.fx.tick, 13); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display var old = jQuery.data(this.elem, "olddisplay"); this.elem.style.display = old ? old : this.options.display; if ( jQuery.css(this.elem, "display") === "none" ) { this.elem.style.display = "block"; } } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style(this.elem, p, this.options.orig[p]); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style(fx.elem, "opacity", fx.now); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } var props = { top: (options.top - curOffset.top) + curTop, left: (options.left - curOffset.left) + curLeft }; if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return ("scrollTo" in elem && elem.document) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window); /** * The MIT License * * Copyright (c) 2010 Adam Abrons and Misko Hevery http://getangular.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function(window, document, previousOnLoad){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// if (typeof document.getAttribute == $undefined) document.getAttribute = function() {}; /** * @ngdoc * @name angular.lowercase * @function * * @description Converts string to lowercase * @param {string} value * @returns {string} Lowercased string. */ var lowercase = function (value){ return isString(value) ? value.toLowerCase() : value; }; /** * @ngdoc * @name angular.uppercase * @function * * @description Converts string to uppercase. * @param {string} value * @returns {string} Uppercased string. */ var uppercase = function (value){ return isString(value) ? value.toUpperCase() : value; }; var manualLowercase = function (s) { return isString(s) ? s.replace(/[A-Z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) | 32); }) : s; }; var manualUppercase = function (s) { return isString(s) ? s.replace(/[a-z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) & ~32); }) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods with // correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } function fromCharCode(code) { return String.fromCharCode(code); } var _undefined = undefined, _null = null, $$element = '$element', $angular = 'angular', $array = 'array', $boolean = 'boolean', $console = 'console', $date = 'date', $display = 'display', $element = 'element', $function = 'function', $length = 'length', $name = 'name', $none = 'none', $noop = 'noop', $null = 'null', $number = 'number', $object = 'object', $string = 'string', $undefined = 'undefined', NG_EXCEPTION = 'ng-exception', NG_VALIDATION_ERROR = 'ng-validation-error', NOOP = 'noop', PRIORITY_FIRST = -99999, PRIORITY_WATCH = -1000, PRIORITY_LAST = 99999, PRIORITY = {'FIRST': PRIORITY_FIRST, 'LAST': PRIORITY_LAST, 'WATCH':PRIORITY_WATCH}, jQuery = window['jQuery'] || window['$'], // weirdness to make IE happy _ = window['_'], /** holds major version number for IE or NaN for real browsers */ msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), jqLite = jQuery || jqLiteWrap, slice = Array.prototype.slice, push = Array.prototype.push, error = window[$console] ? bind(window[$console], window[$console]['error'] || noop) : noop, /** * @name angular * @namespace The exported angular namespace. */ angular = window[$angular] || (window[$angular] = {}), angularTextMarkup = extensionMap(angular, 'markup'), angularAttrMarkup = extensionMap(angular, 'attrMarkup'), angularDirective = extensionMap(angular, 'directive'), /** * @ngdoc overview * @name angular.widget * @namespace Namespace for all widgets. * @description * # Overview * Widgets allow you to create DOM elements that the browser doesn't * already understand. You create the widget in your namespace and * assign it behavior. You can only bind one widget per DOM element * (unlike directives, in which you can use any number per DOM * element). Widgets are expected to manipulate the DOM tree by * adding new elements whereas directives are expected to only modify * element properties. * * Widgets come in two flavors: element and attribute. * * # Element Widget * Let's say we would like to create a new element type in the * namespace `my` that can watch an expression and alert() the user * with each new value. * * <pre> * &lt;my:watch exp="name"/&gt; * </pre> * * You can implement `my:watch` like this: * <pre> * angular.widget('my:watch', function(compileElement) { * var compiler = this; * var exp = compileElement.attr('exp'); * return function(linkElement) { * var currentScope = this; * currentScope.$watch(exp, function(value){ * alert(value); * }}; * }; * }); * </pre> * * # Attribute Widget * Let's implement the same widget, but this time as an attribute * that can be added to any existing DOM element. * <pre> * &lt;div my-watch="name"&gt;text&lt;/div&gt; * </pre> * You can implement `my:watch` attribute like this: * <pre> * angular.widget('@my:watch', function(expression, compileElement) { * var compiler = this; * return function(linkElement) { * var currentScope = this; * currentScope.$watch(expression, function(value){ * alert(value); * }); * }; * }); * </pre> * * @example * <script> * angular.widget('my:time', function(compileElement){ * compileElement.css('display', 'block'); * return function(linkElement){ * function update(){ * linkElement.text('Current time is: ' + new Date()); * setTimeout(update, 1000); * } * update(); * }; * }); * </script> * <my:time></my:time> */ angularWidget = extensionMap(angular, 'widget', lowercase), /** * @ngdoc overview * @name angular.validator * @namespace Namespace for all filters. * @description * # Overview * Validators are a standard way to check the user input against a specific criteria. For * example, you might need to check that an input field contains a well-formed phone number. * * # Syntax * Attach a validator on user input widgets using the `ng:validate` attribute. * * <doc:example> * <doc:source> * Change me: &lt;input type="text" name="number" ng:validate="integer" value="123"&gt; * </doc:source> * <doc:scenario> * it('should validate the default number string', function() { * expect(element('input[name=number]').attr('class')). * not().toMatch(/ng-validation-error/); * }); * it('should not validate "foo"', function() { * input('number').enter('foo'); * expect(element('input[name=number]').attr('class')). * toMatch(/ng-validation-error/); * }); * </doc:scenario> * </doc:example> * * * # Writing your own Validators * Writing your own validator is easy. To make a function available as a * validator, just define the JavaScript function on the `angular.validator` * object. <angular/> passes in the input to validate as the first argument * to your function. Any additional validator arguments are passed in as * additional arguments to your function. * * You can use these variables in the function: * * * `this` — The current scope. * * `this.$element` — The DOM element containing the binding. This allows the filter to manipulate * the DOM in addition to transforming the input. * * In this example we have written a upsTrackingNo validator. * It marks the input text "valid" only when the user enters a well-formed * UPS tracking number. * * @css ng-validation-error * When validation fails, this css class is applied to the binding, making its borders red by * default. * * @example * <script> * angular.validator('upsTrackingNo', function(input, format) { * var regexp = new RegExp("^" + format.replace(/9/g, '\\d') + "$"); * return input.match(regexp)?"":"The format must match " + format; * }); * </script> * <input type="text" name="trackNo" size="40" * ng:validate="upsTrackingNo:'1Z 999 999 99 9999 999 9'" * value="1Z 123 456 78 9012 345 6"/> * * @scenario * it('should validate correct UPS tracking number', function() { * expect(element('input[name=trackNo]').attr('class')). * not().toMatch(/ng-validation-error/); * }); * * it('should not validate in correct UPS tracking number', function() { * input('trackNo').enter('foo'); * expect(element('input[name=trackNo]').attr('class')). * toMatch(/ng-validation-error/); * }); * */ angularValidator = extensionMap(angular, 'validator'), /** * @ngdoc overview * @name angular.filter * @namespace Namespace for all filters. * @description * # Overview * Filters are a standard way to format your data for display to the user. For example, you * might have the number 1234.5678 and would like to display it as US currency: $1,234.57. * Filters allow you to do just that. In addition to transforming the data, filters also modify * the DOM. This allows the filters to for example apply css styles to the filtered output if * certain conditions were met. * * * # Standard Filters * * The Angular framework provides a standard set of filters for common operations, including: * {@link angular.filter.currency}, {@link angular.filter.json}, {@link angular.filter.number}, * and {@link angular.filter.html}. You can also add your own filters. * * * # Syntax * * Filters can be part of any {@link angular.scope} evaluation but are typically used with * {{bindings}}. Filters typically transform the data to a new data type, formating the data in * the process. Filters can be chained and take optional arguments. Here are few examples: * * * No filter: {{1234.5678}} => 1234.5678 * * Number filter: {{1234.5678|number}} => 1,234.57. Notice the “,” and rounding to two * significant digits. * * Filter with arguments: {{1234.5678|number:5}} => 1,234.56780. Filters can take optional * arguments, separated by colons in a binding. To number, the argument “5” requests 5 digits * to the right of the decimal point. * * * # Writing your own Filters * * Writing your own filter is very easy: just define a JavaScript function on `angular.filter`. * The framework passes in the input value as the first argument to your function. Any filter * arguments are passed in as additional function arguments. * * You can use these variables in the function: * * * `this` — The current scope. * * `this.$element` — The DOM element containing the binding. This allows the filter to manipulate * the DOM in addition to transforming the input. * * * @exampleDescription * The following example filter reverses a text string. In addition, it conditionally makes the * text upper-case (to demonstrate optional arguments) and assigns color (to demonstrate DOM * modification). * * @example <script type="text/javascript"> angular.filter('reverse', function(input, uppercase, color) { var out = ""; for (var i = 0; i < input.length; i++) { out = input.charAt(i) + out; } if (uppercase) { out = out.toUpperCase(); } if (color) { this.$element.css('color', color); } return out; }); </script> <input name="text" type="text" value="hello" /><br> No filter: {{text}}<br> Reverse: {{text|reverse}}<br> Reverse + uppercase: {{text|reverse:true}}<br> Reverse + uppercase + blue: {{text|reverse:true:"blue"}} */ angularFilter = extensionMap(angular, 'filter'), /** * @ngdoc overview * @name angular.formatter * @namespace Namespace for all formats. * @description * # Overview * The formatters are responsible for translating user readable text in an input widget to a * data model stored in an application. * * # Writting your own Fromatter * Writing your own formatter is easy. Just register a pair of JavaScript functions with * `angular.formatter`. One function for parsing user input text to the stored form, * and one for formatting the stored data to user-visible text. * * Here is an example of a "reverse" formatter: The data is stored in uppercase and in * reverse, while it is displayed in lower case and non-reversed. User edits are * automatically parsed into the internal form and data changes are automatically * formatted to the viewed form. * * <pre> * function reverse(text) { * var reversed = []; * for (var i = 0; i < text.length; i++) { * reversed.unshift(text.charAt(i)); * } * return reversed.join(''); * } * * angular.formatter('reverse', { * parse: function(value){ * return reverse(value||'').toUpperCase(); * }, * format: function(value){ * return reverse(value||'').toLowerCase(); * } * }); * </pre> * * @example * <script type="text/javascript"> * function reverse(text) { * var reversed = []; * for (var i = 0; i < text.length; i++) { * reversed.unshift(text.charAt(i)); * } * return reversed.join(''); * } * * angular.formatter('reverse', { * parse: function(value){ * return reverse(value||'').toUpperCase(); * }, * format: function(value){ * return reverse(value||'').toLowerCase(); * } * }); * </script> * * Formatted: * <input type="text" name="data" value="angular" ng:format="reverse"/> * <br/> * * Stored: * <input type="text" name="data"/><br/> * <pre>{{data}}</pre> * * * @scenario * it('should store reverse', function(){ * expect(element('.doc-example input:first').val()).toEqual('angular'); * expect(element('.doc-example input:last').val()).toEqual('RALUGNA'); * * this.addFutureAction('change to XYZ', function($window, $document, done){ * $document.elements('.doc-example input:last').val('XYZ').trigger('change'); * done(); * }); * expect(element('input:first').val()).toEqual('zyx'); * }); */ angularFormatter = extensionMap(angular, 'formatter'), angularService = extensionMap(angular, 'service'), angularCallbacks = extensionMap(angular, 'callbacks'), nodeName, rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/; function foreach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach) { obj.forEach(iterator, context); } else if (isObject(obj) && isNumber(obj.length)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) iterator.call(context, obj[key], key); } } return obj; } function foreachSorted(obj, iterator, context) { var keys = []; for (var key in obj) keys.push(key); keys.sort(); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } function extend(dst) { foreach(arguments, function(obj){ if (obj !== dst) { foreach(obj, function(value, key){ dst[key] = value; }); } }); return dst; } function inherit(parent, extra) { return extend(new (extend(function(){}, {prototype:parent}))(), extra); } function noop() {} function identity($) {return $;} function valueFn(value) {return function(){ return value; };} function extensionMap(angular, name, transform) { var extPoint; return angular[name] || (extPoint = angular[name] = function (name, fn, prop){ name = (transform || identity)(name); if (isDefined(fn)) { if (isDefined(extPoint[name])) { foreach(extPoint[name], function(property, key) { if (key.charAt(0) == '$' && isUndefined(fn[key])) fn[key] = property; }); } extPoint[name] = extend(fn, prop || {}); } return extPoint[name]; }); } function jqLiteWrap(element) { // for some reasons the parentNode of an orphan looks like _null but its typeof is object. if (element) { if (isString(element)) { var div = document.createElement('div'); div.innerHTML = element; element = new JQLite(div.childNodes); } else if (!(element instanceof JQLite) && isElement(element)) { element = new JQLite(element); } } return element; } function isUndefined(value){ return typeof value == $undefined; } function isDefined(value){ return typeof value != $undefined; } function isObject(value){ return value!=_null && typeof value == $object;} function isString(value){ return typeof value == $string;} function isNumber(value){ return typeof value == $number;} function isDate(value){ return value instanceof Date; } function isArray(value) { return value instanceof Array; } function isFunction(value){ return typeof value == $function;} function isBoolean(value) { return typeof value == $boolean;} function isTextNode(node) { return nodeName(node) == '#text'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } function isElement(node) { return node && (node.nodeName || node instanceof JQLite || (jQuery && node instanceof jQuery)); } /** * HTML class which is the only class which can be used in ng:bind to inline HTML for security reasons. * @constructor * @param html raw (unsafe) html * @param {string=} option if set to 'usafe' then get method will return raw (unsafe/unsanitized) html */ function HTML(html, option) { this.html = html; this.get = lowercase(option) == 'unsafe' ? valueFn(html) : function htmlSanitize() { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; } if (msie) { nodeName = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML' ) ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function quickClone(element) { return jqLite(element[0].cloneNode(true)); } function isVisible(element) { var rect = element[0].getBoundingClientRect(), width = (rect.width || (rect.right||0 - rect.left||0)), height = (rect.height || (rect.bottom||0 - rect.top||0)); return width>0 && height>0; } function map(obj, iterator, context) { var results = []; foreach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } function size(obj) { var size = 0; if (obj) { if (isNumber(obj.length)) { return obj.length; } else if (isObject(obj)){ for (key in obj) size++; } } return size; } function includes(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return true; } return false; } function indexOf(array, obj) { for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * Copies stuff. * * If destination is not provided and source is an object or an array, a copy is created & returned, * otherwise the source is returned. * * If destination is provided, all of its properties will be deleted and if source is an object or * an array, all of its members will be copied into the destination object. Finally the destination * is returned just for kicks. * * @param {*} source The source to be used during copy. * Can be any type including primitives, null and undefined. * @param {(Object|Array)=} destination Optional destination into which the source is copied * @returns {*} */ function copy(source, destination){ if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (isArray(source)) { while(destination.length) { destination.pop(); } for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { foreach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } } } return destination; } function equals(o1, o2) { if (o1 == o2) return true; var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2 && t1 == 'object') { if (o1 instanceof Array) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else { keySet = {}; for(key in o1) { if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false; } return true; } } return false; } function setHtml(node, html) { if (isLeafNode(node)) { if (msie) { node.innerText = html; } else { node.textContent = html; } } else { node.innerHTML = html; } } function isRenderableElement(element) { var name = element && element[0] && element[0].nodeName; return name && name.charAt(0) != '#' && !includes(['TR', 'COL', 'COLGROUP', 'TBODY', 'THEAD', 'TFOOT'], name); } function elementError(element, type, error) { while (!isRenderableElement(element)) { element = element.parent() || jqLite(document.body); } if (element[0]['$NG_ERROR'] !== error) { element[0]['$NG_ERROR'] = error; if (error) { element.addClass(type); element.attr(type, error); } else { element.removeClass(type); element.removeAttr(type); } } } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index, array2.length)); } function bind(self, fn) { var curryArgs = arguments.length > 2 ? slice.call(arguments, 2, arguments.length) : []; if (typeof fn == $function) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0, arguments.length))) : fn.apply(self, curryArgs); }: function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods ore not functions and so they can not be bound (but they don't need to be) return fn; } } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } function merge(src, dst) { for ( var key in src) { var value = dst[key]; var type = typeof value; if (type == $undefined) { dst[key] = fromJson(toJson(src[key])); } else if (type == 'object' && value.constructor != array && key.substring(0, 1) != "$") { merge(src[key], value); } } } function compile(element, existingScope) { var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget), $element = jqLite(element); return compiler.compile($element)($element, existingScope); } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; foreach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = unescape(key_value[0]); obj[key] = isDefined(key_value[1]) ? unescape(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; foreach(obj, function(value, key) { parts.push(escape(key) + (value === true ? '' : '=' + escape(value))); }); return parts.length ? parts.join('&') : ''; } function angularInit(config){ if (config.autobind) { // TODO default to the source of angular.js var scope = compile(window.document, _null, {'$config':config}), $browser = scope.$inject('$browser'); if (config.css) $browser.addCss(config.base_url + config.css); else if(msie<8) $browser.addJs(config.base_url + config.ie_compat, config.ie_compat_id); scope.$init(); } } function angularJsConfig(document, config) { var scripts = document.getElementsByTagName("script"), match; config = extend({ ie_compat_id: 'ng-ie-compat' }, config); for(var j = 0; j < scripts.length; j++) { match = (scripts[j].src || "").match(rngScript); if (match) { config.base_url = match[1]; config.ie_compat = match[1] + 'angular-ie-compat' + (match[2] || '') + '.js'; extend(config, parseKeyValue(match[6])); eachAttribute(jqLite(scripts[j]), function(value, name){ if (/^ng:/.exec(name)) { name = name.substring(3).replace(/-/g, '_'); if (name == 'autobind') value = true; config[name] = value; } }); } } return config; } var array = [].constructor; function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : _null, []); return buf.join(''); } function fromJson(json) { if (!json) return json; try { var p = parser(json, true); var expression = p.primary(); p.assertAllConsumed(); return expression(); } catch (e) { error("fromJson error: ", json, e); throw e; } } angular['toJson'] = toJson; angular['fromJson'] = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === _null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angular['String']['quoteUnicode'](obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angular['String']['quoteUnicode'](obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isDate(obj)) { buf.push(angular['String']['quoteUnicode'](angular['Date']['toString'](obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (obj[k] === _undefined) continue; keys.push(k); } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (typeof value != $function) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angular['String']['quote'](key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } } /** * Template provides directions an how to bind to a given element. * It contains a list of init functions which need to be called to * bind to a new instance of elements. It also provides a list * of child paths which contain child templates */ function Template(priority) { this.paths = []; this.children = []; this.inits = []; this.priority = priority; this.newScope = false; } Template.prototype = { init: function(element, scope) { var inits = {}; this.collectInits(element, inits, scope); foreachSorted(inits, function(queue){ foreach(queue, function(fn) {fn();}); }); }, collectInits: function(element, inits, scope) { var queue = inits[this.priority], childScope = scope; if (!queue) { inits[this.priority] = queue = []; } element = jqLite(element); if (this.newScope) { childScope = createScope(scope); scope.$onEval(childScope.$eval); } foreach(this.inits, function(fn) { queue.push(function() { childScope.$tryEval(function(){ return childScope.$inject(fn, childScope, element); }, element); }); }); var i, childNodes = element[0].childNodes, children = this.children, paths = this.paths, length = paths.length; for (i = 0; i < length; i++) { children[i].collectInits(childNodes[paths[i]], inits, childScope); } }, addInit:function(init) { if (init) { this.inits.push(init); } }, addChild: function(index, template) { if (template) { this.paths.push(index); this.children.push(template); } }, empty: function() { return this.inits.length === 0 && this.paths.length === 0; } }; /////////////////////////////////// //Compiler ////////////////////////////////// function Compiler(markup, attrMarkup, directives, widgets){ this.markup = markup; this.attrMarkup = attrMarkup; this.directives = directives; this.widgets = widgets; } Compiler.prototype = { compile: function(rawElement) { rawElement = jqLite(rawElement); var index = 0, template, parent = rawElement.parent(); if (parent && parent[0]) { parent = parent[0]; for(var i = 0; i < parent.childNodes.length; i++) { if (parent.childNodes[i] == rawElement[0]) { index = i; } } } template = this.templatize(rawElement, index, 0) || new Template(); return function(element, parentScope){ element = jqLite(element); var scope = parentScope && parentScope.$eval ? parentScope : createScope(parentScope); return extend(scope, { $element:element, $init: function() { template.init(element, scope); scope.$eval(); delete scope.$init; return scope; } }); }; }, templatize: function(element, elementIndex, priority){ var self = this, widget, fn, directiveFns = self.directives, descend = true, directives = true, elementName = nodeName(element), template, selfApi = { compile: bind(self, self.compile), comment:function(text) {return jqLite(document.createComment(text));}, element:function(type) {return jqLite(document.createElement(type));}, text:function(text) {return jqLite(document.createTextNode(text));}, descend: function(value){ if(isDefined(value)) descend = value; return descend;}, directives: function(value){ if(isDefined(value)) directives = value; return directives;}, scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;} }; try { priority = element.attr('ng:eval-order') || priority || 0; } catch (e) { // for some reason IE throws error under some weird circumstances. so just assume nothing priority = priority || 0; } if (isString(priority)) { priority = PRIORITY[uppercase(priority)] || parseInt(priority, 10); } template = new Template(priority); eachAttribute(element, function(value, name){ if (!widget) { if (widget = self.widgets('@' + name)) { element.addClass('ng-attr-widget'); widget = bind(selfApi, widget, value, element); } } }); if (!widget) { if (widget = self.widgets(elementName)) { if (elementName.indexOf(':') > 0) element.addClass('ng-widget'); widget = bind(selfApi, widget, element); } } if (widget) { descend = false; directives = false; var parent = element.parent(); template.addInit(widget.call(selfApi, element)); if (parent && parent[0]) { element = jqLite(parent[0].childNodes[elementIndex]); } } if (descend){ // process markup for text nodes only for(var i=0, child=element[0].childNodes; i<child.length; i++) { if (isTextNode(child[i])) { foreach(self.markup, function(markup){ if (i<child.length) { var textNode = jqLite(child[i]); markup.call(selfApi, textNode.text(), textNode, element); } }); } } } if (directives) { // Process attributes/directives eachAttribute(element, function(value, name){ foreach(self.attrMarkup, function(markup){ markup.call(selfApi, value, name, element); }); }); eachAttribute(element, function(value, name){ fn = directiveFns[name]; if (fn) { element.addClass('ng-directive'); template.addInit((directiveFns[name]).call(selfApi, value, element)); } }); } // Process non text child nodes if (descend) { eachNode(element, function(child, i){ template.addChild(i, self.templatize(child, i, priority)); }); } return template.empty() ? _null : template; } }; function eachNode(element, fn){ var i, chldNodes = element[0].childNodes || [], chld; for (i = 0; i < chldNodes.length; i++) { if(!isTextNode(chld = chldNodes[i])) { fn(jqLite(chld), i); } } } function eachAttribute(element, fn){ var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {}; for (i = 0; i < attrs.length; i++) { attr = attrs[i]; name = attr.name; value = attr.value; if (msie && name == 'href') { value = decodeURIComponent(element[0].getAttribute(name, 2)); } attrValue[name] = value; } foreachSorted(attrValue, fn); } function getter(instance, path, unboundFn) { if (!path) return instance; var element = path.split('.'); var key; var lastInstance = instance; var len = element.length; for ( var i = 0; i < len; i++) { key = element[i]; if (!key.match(/^[\$\w][\$\w\d]*$/)) throw "Expression '" + path + "' is not a valid expression for accesing variables."; if (instance) { lastInstance = instance; instance = instance[key]; } if (isUndefined(instance) && key.charAt(0) == '$') { var type = angular['Global']['typeOf'](lastInstance); type = angular[type.charAt(0).toUpperCase()+type.substring(1)]; var fn = type ? type[[key.substring(1)]] : _undefined; if (fn) { instance = bind(lastInstance, fn, lastInstance); return instance; } } } if (!unboundFn && isFunction(instance)) { return bind(lastInstance, instance); } return instance; } function setter(instance, path, value){ var element = path.split('.'); for ( var i = 0; element.length > 1; i++) { var key = element.shift(); var newInstance = instance[key]; if (!newInstance) { newInstance = {}; instance[key] = newInstance; } instance = newInstance; } instance[element.shift()] = value; return value; } /////////////////////////////////// var scopeId = 0, getterFnCache = {}, compileCache = {}, JS_KEYWORDS = {}; foreach( ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," + "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," + "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," + "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," + "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/), function(key){ JS_KEYWORDS[key] = true;} ); function getterFn(path){ var fn = getterFnCache[path]; if (fn) return fn; var code = 'var l, fn, t;\n'; foreach(path.split('.'), function(key) { key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key; code += 'if(!s) return s;\n' + 'l=s;\n' + 's=s' + key + ';\n' + 'if(typeof s=="function") s = function(){ return l'+key+'.apply(l, arguments); };\n'; if (key.charAt(1) == '$') { // special code for super-imposed functions var name = key.substr(2); code += 'if(!s) {\n' + ' t = angular.Global.typeOf(l);\n' + ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' + ' if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n' + '}\n'; } }); code += 'return s;'; fn = Function('s', code); fn["toString"] = function(){ return code; }; return getterFnCache[path] = fn; } /////////////////////////////////// function expressionCompile(exp){ if (typeof exp === $function) return exp; var fn = compileCache[exp]; if (!fn) { var p = parser(exp); var fnSelf = p.statements(); p.assertAllConsumed(); fn = compileCache[exp] = extend( function(){ return fnSelf(this);}, {fnSelf: fnSelf}); } return fn; } function errorHandlerFor(element, error) { elementError(element, NG_EXCEPTION, isDefined(error) ? toJson(error) : error); } function createScope(parent, providers, instanceCache) { function Parent(){} parent = Parent.prototype = (parent || {}); var instance = new Parent(); var evalLists = {sorted:[]}; var postList = [], postHash = {}, postId = 0; extend(instance, { 'this': instance, $id: (scopeId++), $parent: parent, $bind: bind(instance, bind, instance), $get: bind(instance, getter, instance), $set: bind(instance, setter, instance), $eval: function $eval(exp) { var type = typeof exp; var i, iSize; var j, jSize; var queue; var fn; if (type == $undefined) { for ( i = 0, iSize = evalLists.sorted.length; i < iSize; i++) { for ( queue = evalLists.sorted[i], jSize = queue.length, j= 0; j < jSize; j++) { instance.$tryEval(queue[j].fn, queue[j].handler); } } while(postList.length) { fn = postList.shift(); delete postHash[fn.$postEvalId]; instance.$tryEval(fn); } } else if (type === $function) { return exp.call(instance); } else if (type === 'string') { return expressionCompile(exp).call(instance); } }, $tryEval: function (expression, exceptionHandler) { var type = typeof expression; try { if (type == $function) { return expression.call(instance); } else if (type == 'string'){ return expressionCompile(expression).call(instance); } } catch (e) { (instance.$log || {error:error}).error(e); if (isFunction(exceptionHandler)) { exceptionHandler(e); } else if (exceptionHandler) { errorHandlerFor(exceptionHandler, e); } else if (isFunction(instance.$exceptionHandler)) { instance.$exceptionHandler(e); } } }, $watch: function(watchExp, listener, exceptionHandler) { var watch = expressionCompile(watchExp), last = {}; listener = expressionCompile(listener); function watcher(){ var value = watch.call(instance), lastValue = last; if (last !== value) { last = value; instance.$tryEval(function(){ return listener.call(instance, value, lastValue); }, exceptionHandler); } } instance.$onEval(PRIORITY_WATCH, watcher); watcher(); }, $onEval: function(priority, expr, exceptionHandler){ if (!isNumber(priority)) { exceptionHandler = expr; expr = priority; priority = 0; } var evalList = evalLists[priority]; if (!evalList) { evalList = evalLists[priority] = []; evalList.priority = priority; evalLists.sorted.push(evalList); evalLists.sorted.sort(function(a,b){return a.priority-b.priority;}); } evalList.push({ fn: expressionCompile(expr), handler: exceptionHandler }); }, $postEval: function(expr) { if (expr) { var fn = expressionCompile(expr); var id = fn.$postEvalId; if (!id) { id = '$' + instance.$id + "_" + (postId++); fn.$postEvalId = id; } if (!postHash[id]) { postList.push(postHash[id] = fn); } } }, $become: function(Class) { if (isFunction(Class)) { instance.constructor = Class; foreach(Class.prototype, function(fn, name){ instance[name] = bind(instance, fn); }); instance.$inject.apply(instance, concat([Class, instance], arguments, 1)); //TODO: backwards compatibility hack, remove when we don't depend on init methods if (isFunction(Class.prototype.init)) { instance.init(); } } }, $new: function(Class) { var child = createScope(instance); child.$become.apply(instance, concat([Class], arguments, 1)); instance.$onEval(child.$eval); return child; } }); if (!parent.$root) { instance.$root = instance; instance.$parent = instance; (instance.$inject = createInjector(instance, providers, instanceCache))(); } return instance; } /** * Create an inject method * @param providerScope provider's "this" * @param providers a function(name) which returns provider function * @param cache place where instances are saved for reuse * @returns {Function} */ function createInjector(providerScope, providers, cache) { providers = providers || angularService; cache = cache || {}; providerScope = providerScope || {}; /** * injection function * @param value: string, array, object or function. * @param scope: optional function "this" * @param args: optional arguments to pass to function after injection * parameters * @returns depends on value: * string: return an instance for the injection key. * array of keys: returns an array of instances. * function: look at $inject property of function to determine instances * and then call the function with instances and scope. Any * additional arguments are passed on to function. * object: initialize eager providers and publish them the ones with publish here. * none: same as object but use providerScope as place to publish. */ return function inject(value, scope, args){ var returnValue, provider, creation; if (isString(value)) { if (!cache.hasOwnProperty(value)) { provider = providers[value]; if (!provider) throw "Unknown provider for '"+value+"'."; cache[value] = inject(provider, providerScope); } returnValue = cache[value]; } else if (isArray(value)) { returnValue = []; foreach(value, function(name) { returnValue.push(inject(name)); }); } else if (isFunction(value)) { returnValue = inject(value.$inject || []); returnValue = value.apply(scope, concat(returnValue, arguments, 2)); } else if (isObject(value)) { foreach(providers, function(provider, name){ creation = provider.$creation; if (creation == 'eager') { inject(name); } if (creation == 'eager-published') { setter(value, name, inject(name)); } }); } else { returnValue = inject(providerScope); } return returnValue; }; }var OPERATORS = { 'null':function(self){return _null;}, 'true':function(self){return true;}, 'false':function(self){return false;}, $undefined:noop, '+':function(self, a,b){return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, '-':function(self, a,b){return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, a,b){return a*b;}, '/':function(self, a,b){return a/b;}, '%':function(self, a,b){return a%b;}, '^':function(self, a,b){return a^b;}, '=':function(self, a,b){return setter(self, a, b);}, '==':function(self, a,b){return a==b;}, '!=':function(self, a,b){return a!=b;}, '<':function(self, a,b){return a<b;}, '>':function(self, a,b){return a>b;}, '<=':function(self, a,b){return a<=b;}, '>=':function(self, a,b){return a>=b;}, '&&':function(self, a,b){return a&&b;}, '||':function(self, a,b){return a||b;}, '&':function(self, a,b){return a&b;}, // '|':function(self, a,b){return a|b;}, '|':function(self, a,b){return b(self, a);}, '!':function(self, a){return !a;} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, parseStringsForObjects){ var dateParseLength = parseStringsForObjects ? 24 : -1, tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if ( was('({[:,;') && is('/') ) { readRegexp(); } else if (isIdent(ch)) { readIdent(); if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:')) { tokens.push({index:index, text:ch, json:is('{}[]:,')}); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), fn = OPERATORS[ch], fn2 = OPERATORS[ch2]; if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throw "Lexer Error: Unexpected next character [" + text.substring(index) + "] in expression '" + text + "' at column '" + (index+1) + "'."; } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek() { return index + 1 < text.length ? text.charAt(index + 1) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throw 'Lexer found invalid exponential value "' + text + '"'; } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function(){return number;}}); } function readIdent() { var ident = ""; var start = index; while (index < text.length) { var ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { ident += ch; } else { break; } index++; } var fn = OPERATORS[ident]; if (!fn) { fn = getterFn(ident); fn.isAssignable = ident; } tokens.push({index:start, text:ident, fn:fn, json: OPERATORS[ident]}); } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throw "Lexer Error: Invalid unicode escape [\\u" + hex + "] starting at column '" + start + "' in expression '" + text + "'."; index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({index:start, text:rawString, string:string, json:true, fn:function(){ return (string.length == dateParseLength) ? angular['String']['toDate'](string) : string; }}); return; } else { string += ch; } index++; } throw "Lexer Error: Unterminated quote [" + text.substring(start) + "] starting at column '" + (start+1) + "' in expression '" + text + "'."; } function readRegexp(quote) { var start = index; index++; var regexp = ""; var escape = false; while (index < text.length) { var ch = text.charAt(index); if (escape) { regexp += ch; escape = false; } else if (ch === '\\') { regexp += ch; escape = true; } else if (ch === '/') { index++; var flags = ""; if (isIdent(text.charAt(index))) { readIdent(); flags = tokens.pop().text; } var compiledRegexp = new RegExp(regexp, flags); tokens.push({index:start, text:regexp, flags:flags, fn:function(){return compiledRegexp;}}); return; } else { regexp += ch; } index++; } throw "Lexer Error: Unterminated RegExp [" + text.substring(start) + "] starting at column '" + (start+1) + "' in expression '" + text + "'."; } } ///////////////////////////////////////// function parser(text, json){ var ZERO = valueFn(0), tokens = lex(text, json); return { assertAllConsumed: assertAllConsumed, primary: primary, statements: statements, validator: validator, filter: filter, watch: watch }; /////////////////////////////////// function error(msg, token) { throw "Token '" + token.text + "' is " + msg + " at column='" + (token.index + 1) + "' of expression '" + text + "' starting at '" + text.substring(token.index) + "'."; } function peekToken() { if (tokens.length === 0) throw "Unexpected end of expression: " + text; return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { index = token.index; throw "Expression at column='" + token.index + "' of expression '" + text + "' starting at '" + text.substring(token.index) + "' is not valid json."; } tokens.shift(); this.currentToken = token; return token; } return false; } function consume(e1){ if (!expect(e1)) { var token = peek(); throw "Expecting '" + e1 + "' at column '" + (token.index+1) + "' in '" + text + "' got '" + text.substring(token.index) + "'."; } } function unaryFn(fn, right) { return function(self) { return fn(self, right(self)); }; } function binaryFn(left, fn, right) { return function(self) { return fn(self, left(self), right(self)); }; } function hasTokens () { return tokens.length > 0; } function assertAllConsumed(){ if (tokens.length !== 0) { throw "Did not understand '" + text.substring(tokens[0].index) + "' while evaluating '" + text + "'."; } } function statements(){ var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { return function (self){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self); } return value; }; } } } function filterChain(){ var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter(){ return pipeFunction(angularFilter); } function validator(){ return pipeFunction(angularValidator); } function pipeFunction(fnScope){ var fn = functionIdent(fnScope); var argsFn = []; var token; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } return fn.apply(self, args); }; return function(){ return fnInvoke; }; } } } function expression(){ return throwStmt(); } function throwStmt(){ if (expect('throw')) { var throwExp = assignment(); return function (self) { throw throwExp(self); }; } else { return assignment(); } } function assignment(){ var left = logicalOR(); var token; if (token = expect('=')) { if (!left.isAssignable) { throw "Left hand side '" + text.substring(0, token.index) + "' of assignment '" + text.substring(token.index) + "' is not assignable."; } var ident = function(){return left.isAssignable;}; return binaryFn(ident, token.fn, logicalOR()); } else { return left; } } function logicalOR(){ var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND(){ var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality(){ var left = relational(); var token; if ((token = expect('==','!='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational(){ var left = additive(); var token; if (token = expect('<', '>', '<=', '>=')) { left = binaryFn(left, token.fn, relational()); } return left; } function additive(){ var left = multiplicative(); var token; while(token = expect('+','-')) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative(){ var left = unary(); var token; while(token = expect('*','/','%')) { left = binaryFn(left, token.fn, unary()); } return left; } function unary(){ var token; if (expect('+')) { return primary(); } else if (token = expect('-')) { return binaryFn(ZERO, token.fn, unary()); } else if (token = expect('!')) { return unaryFn(token.fn, unary()); } else { return primary(); } } function functionIdent(fnScope) { var token = expect(); var element = token.text.split('.'); var instance = fnScope; var key; for ( var i = 0; i < element.length; i++) { key = element[i]; if (instance) instance = instance[key]; } if (typeof instance != $function) { throw "Function '" + token.text + "' at column '" + (token.index+1) + "' in '" + text + "' is not defined."; } return instance; } function primary() { var primary; if (expect('(')) { var expression = filterChain(); consume(')'); primary = expression; } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { error("not a primary expression", token); } } var next; while (next = expect('(', '[', '.')) { if (next.text === '(') { primary = functionCall(primary); } else if (next.text === '[') { primary = objectIndex(primary); } else if (next.text === '.') { primary = fieldAccess(primary); } else { throw "IMPOSSIBLE"; } } return primary; } function fieldAccess(object) { var field = expect().text; var getter = getterFn(field); var fn = function (self){ return getter(object(self)); }; fn.isAssignable = field; return fn; } function objectIndex(obj) { var indexFn = expression(); consume(']'); if (expect('=')) { var rhs = expression(); return function (self){ return obj(self)[indexFn(self)] = rhs(self); }; } else { return function (self){ var o = obj(self); var i = indexFn(self); return (o) ? o[i] : _undefined; }; } } function functionCall(fn) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function (self){ var args = []; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self)); } var fnPtr = fn(self) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(self, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; if (peekToken().text != ']') { do { elementFns.push(expression()); } while (expect(',')); } consume(']'); return function (self){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self)); } return array; }; } function object () { var keyValues = []; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); } while (expect(',')); } consume('}'); return function (self){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; var value = keyValue.value(self); object[keyValue.key] = value; } return object; }; } function watch () { var decl = []; while(hasTokens()) { decl.push(watchDecl()); if (!expect(';')) { assertAllConsumed(); } } assertAllConsumed(); return function (self){ for ( var i = 0; i < decl.length; i++) { var d = decl[i](self); self.addListener(d.name, d.fn); } }; } function watchDecl () { var anchorName = expect().text; consume(":"); var expressionFn; if (peekToken().text == '{') { consume("{"); expressionFn = statements(); consume("}"); } else { expressionFn = expression(); } return function(self) { return {name:anchorName, fn:expressionFn}; }; } } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; foreach(template.split(/\W/), function(param){ if (param && template.match(new RegExp(":" + param + "\\W"))) { urlParams[param] = true; } }); } Route.prototype = { url: function(params) { var path = []; var self = this; var url = this.template; params = params || {}; foreach(this.urlParams, function(_, urlParam){ var value = params[urlParam] || self.defaults[urlParam] || ""; url = url.replace(new RegExp(":" + urlParam + "(\\W)"), value + "$1"); }); url = url.replace(/\/?#$/, ''); var query = []; foreachSorted(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeURI(key) + '=' + encodeURI(value)); } }); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(xhr) { this.xhr = xhr; } ResourceFactory.DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; ResourceFactory.prototype = { route: function(url, paramDefaults, actions){ var self = this; var route = new Route(url); actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions); function extractParams(data){ var ids = {}; foreach(paramDefaults || {}, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } foreach(actions, function(action, name){ var isPostOrPut = action.method == 'POST' || action.method == 'PUT'; Resource[name] = function (a1, a2, a3) { var params = {}; var data; var callback = noop; switch(arguments.length) { case 3: callback = a3; case 2: if (isFunction(a2)) { callback = a2; } else { params = a1; data = a2; break; } case 1: if (isFunction(a1)) callback = a1; else if (isPostOrPut) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-3 arguments [params, data, callback], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); self.xhr( action.method, route.url(extend({}, action.params || {}, extractParams(data), params)), data, function(status, response, clear) { if (status == 200) { if (action.isArray) { value.length = 0; foreach(response, function(item){ value.push(new Resource(item)); }); } else { copy(response, value); } (callback||noop)(value); } else { throw {status: status, response:response, message: status + ": " + response}; } }, action.verifyCache); return value; }; Resource.bind = function(additionalParamDefaults){ return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; Resource.prototype['$' + name] = function(a1, a2){ var params = extractParams(this); var callback = noop; switch(arguments.length) { case 2: params = a1; callback = a2; case 1: if (typeof a1 == $function) callback = a1; else params = a1; case 0: break; default: throw "Expected between 1-2 arguments [params, callback], got " + arguments.length + " arguments."; } var data = isPostOrPut ? this : _undefined; Resource[name].call(this, params, data, callback); }; }); return Resource; } }; ////////////////////////////// // Browser ////////////////////////////// var XHR = window.XMLHttpRequest || function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; function Browser(location, document, head, XHR, $log) { var self = this; self.isMock = false; ////////////////////////////////////////////////////////////// // XHR API ////////////////////////////////////////////////////////////// var idCounter = 0; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; self.xhr = function(method, url, post, callback){ if (isFunction(post)) { callback = post; post = _null; } if (lowercase(method) == 'json') { var callbackId = "angular_" + Math.random() + '_' + (idCounter++); callbackId = callbackId.replace(/\d\./, ''); var script = document[0].createElement('script'); script.type = 'text/javascript'; script.src = url.replace('JSON_CALLBACK', callbackId); window[callbackId] = function(data){ window[callbackId] = _undefined; callback(200, data); }; head.append(script); } else { var xhr = new XHR(); xhr.open(method, url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Accept", "application/json, text/plain, */*"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); outstandingRequestCount ++; xhr.onreadystatechange = function() { if (xhr.readyState == 4) { try { callback(xhr.status || 200, xhr.responseText); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { } } } } } }; xhr.send(post || ''); } }; self.notifyWhenNoOutstandingRequests = function(callback){ if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = []; function poll(){ foreach(pollFns, function(pollFn){ pollFn(); }); } self.poll = poll; /** * Adds a function to the list of functions that poller periodically executes * @return {Function} the added function */ self.addPollFn = function(/**Function*/fn){ pollFns.push(fn); return fn; }; /** * Configures the poller to run in the specified intervals, using the specified setTimeout fn and * kicks it off. */ self.startPoller = function(/**number*/interval, /**Function*/setTimeout){ (function check(){ poll(); setTimeout(check, interval); })(); }; ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// self.setUrl = function(url) { var existingURL = location.href; if (!existingURL.match(/#/)) existingURL += '#'; if (!url.match(/#/)) url += '#'; location.href = url; }; self.getUrl = function() { return location.href; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var rawDocument = document[0]; var lastCookies = {}; var lastCookieString = ''; /** * The cookies method provides a 'private' low level access to browser cookies. It is not meant to * be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul><li> * cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it * </li><li> * cookies(name, value) -> set name to value, if value is undefined delete the cookie * </li><li> * cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way) * </li></ul> */ self.cookies = function (/**string*/name, /**string*/value){ var cookieLength, cookieArray, i, keyValue; if (name) { if (value === _undefined) { rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { rawDocument.cookie = escape(name) + '=' + escape(value); cookieLength = name.length + value.length + 1; if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } if (lastCookies.length > 20) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " + "were already set (" + lastCookies.length + " > 20 )"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { keyValue = cookieArray[i].split("="); if (keyValue.length === 2) { //ignore nameless cookies lastCookies[unescape(keyValue[0])] = unescape(keyValue[1]); } } } return lastCookies; } }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// var hoverListener = noop; self.hover = function(listener) { hoverListener = listener; }; self.bind = function() { document.bind("mouseover", function(event){ hoverListener(jqLite(msie ? event.srcElement : event.target), true); return true; }); document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){ hoverListener(jqLite(event.target), false); return true; }); }; /** * Adds a stylesheet tag to the head. */ self.addCss = function(/**string*/url) { var link = jqLite(rawDocument.createElement('link')); link.attr('rel', 'stylesheet'); link.attr('type', 'text/css'); link.attr('href', url); head.append(link); }; /** * Adds a script tag to the head. */ self.addJs = function(/**string*/url, /**string*/dom_id) { var script = jqLite(rawDocument.createElement('script')); script.attr('type', 'text/javascript'); script.attr('src', url); if (dom_id) script.attr('id', dom_id); head.append(script); }; } /* * HTML Parser By Misko Hevery ([email protected]) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:]+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:]+)[^>]*>/, ATTR_REGEXP = /(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g; // Empty Elements - HTML 4.01 var emptyElements = makeMap("area,base,basefont,br,col,hr,img,input,isindex,link,param"); // Block Elements - HTML 4.01 var blockElements = makeMap("address,blockquote,button,center,dd,del,dir,div,dl,dt,fieldset,"+ "form,hr,ins,isindex,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul"); // Inline Elements - HTML 4.01 var inlineElements = makeMap("a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,"+ "input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"); // Elements that you can, intentionally, leave open // (and which close themselves) var closeSelfElements = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"); // Attributes that have their values filled in disabled="disabled" var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements); var validAttrs = extend({}, fillAttrs, makeMap( 'abbr,align,alink,alt,archive,axis,background,bgcolor,border,cellpadding,cellspacing,cite,class,classid,clear,code,codebase,'+ 'codetype,color,cols,colspan,content,coords,data,dir,face,for,headers,height,href,hreflang,hspace,id,label,lang,language,'+ 'link,longdesc,marginheight,marginwidth,maxlength,media,method,name,nowrap,profile,prompt,rel,rev,rows,rowspan,rules,scheme,'+ 'scope,scrolling,shape,size,span,src,standby,start,summary,tabindex,target,text,title,type,usemap,valign,value,valuetype,'+ 'vlink,vspace,width')); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ var htmlParser = function( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function(){ return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if ( handler.comment ) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if ( handler.chars ) handler.chars( text ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if ( handler.chars ) handler.chars( text ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( closeSelfElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = emptyElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); if ( handler.start ) { var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name) { var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : ""; attrs[name] = value; //value.replace(/(^|[^\\])"/g, '$1\\\"') //" }); if ( handler.start ) handler.start( tagName, attrs, unary ); } } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if ( handler.end ) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } }; /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } /* * For attack vectors see: http://ha.ckers.org/xss.html */ var JAVASCRIPT_URL = /^javascript:/i, NBSP_REGEXP = /&nbsp;/gim, HEX_ENTITY_REGEXP = /&#x([\da-f]*);?/igm, DEC_ENTITY_REGEXP = /&#(\d+);?/igm, CHAR_REGEXP = /[\w:]/gm, HEX_DECODE = function(match, code){return fromCharCode(parseInt(code,16));}, DEC_DECODE = function(match, code){return fromCharCode(code);}; /** * @param {string} url * @returns true if url decodes to something which starts with 'javascript:' hence unsafe */ function isJavaScriptUrl(url) { var chars = []; url.replace(NBSP_REGEXP, ''). replace(HEX_ENTITY_REGEXP, HEX_DECODE). replace(DEC_ENTITY_REGEXP, DEC_DECODE). // Remove all non \w: characters, unfurtunetly value.replace(/[\w:]/,'') can be defeated using \u0000 replace(CHAR_REGEXP, function(ch){chars.push(ch);}); return JAVASCRIPT_URL.test(lowercase(chars.join(''))); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag]) { out('<'); out(tag); foreach(attrs, function(value, key){ if (validAttrs[lowercase(key)] && !isJavaScriptUrl(value)) { out(' '); out(key); out('="'); out(value. replace(/</g, '&lt;'). replace(/>/g, '&gt;'). replace(/\"/g,'&quot;')); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = lowercase(tag); if (!ignore && validElements[tag]) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(chars. replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&amp;';}). replace(/</g, '&lt;'). replace(/>/g, '&gt;')); } } }; } ////////////////////////////////// //JQLite ////////////////////////////////// var jqCache = {}, jqName = 'ng-' + new Date().getTime(), jqId = 1, addEventListener = (window.document.attachEvent ? function(element, type, fn) {element.attachEvent('on' + type, fn);} : function(element, type, fn) {element.addEventListener(type, fn, false);}), removeEventListener = (window.document.detachEvent ? function(element, type, fn) {element.detachEvent('on' + type, fn); } : function(element, type, fn) { element.removeEventListener(type, fn, false); }); function jqNextId() { return (jqId++); } function jqClearData(element) { var cacheId = element[jqName], cache = jqCache[cacheId]; if (cache) { foreach(cache.bind || {}, function(fn, type){ removeEventListener(element, type, fn); }); delete jqCache[cacheId]; if (msie) element[jqName] = ''; // ie does not allow deletion of attributes on elements. else delete element[jqName]; } } function getStyle(element) { var current = {}, style = element[0].style, value, name, i; if (typeof style.length == 'number') { for(i = 0; i < style.length; i++) { name = style[i]; current[name] = style[name]; } } else { for (name in style) { value = style[name]; if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false') current[name] = value; } } return current; } function JQLite(element) { if (isElement(element)) { this[0] = element; this.length = 1; } else if (isDefined(element.length) && element.item) { for(var i=0; i < element.length; i++) { this[i] = element[i]; } this.length = element.length; } } JQLite.prototype = { data: function(key, value) { var element = this[0], cacheId = element[jqName], cache = jqCache[cacheId || -1]; if (isDefined(value)) { if (!cache) { element[jqName] = cacheId = jqNextId(); cache = jqCache[cacheId] = {}; } cache[key] = value; } else { return cache ? cache[key] : _null; } }, removeData: function(){ jqClearData(this[0]); }, dealoc: function(){ (function dealoc(element){ jqClearData(element); for ( var i = 0, children = element.childNodes; i < children.length; i++) { dealoc(children[i]); } })(this[0]); }, bind: function(type, fn){ var self = this, element = self[0], bind = self.data('bind'), eventHandler; if (!bind) this.data('bind', bind = {}); foreach(type.split(' '), function(type){ eventHandler = bind[type]; if (!eventHandler) { bind[type] = eventHandler = function(event) { if (!event.preventDefault) { event.preventDefault = function(){ event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } foreach(eventHandler.fns, function(fn){ fn.call(self, event); }); }; eventHandler.fns = []; addEventListener(element, type, eventHandler); } eventHandler.fns.push(fn); }); }, replaceWith: function(replaceNode) { this[0].parentNode.replaceChild(jqLite(replaceNode)[0], this[0]); }, children: function() { return new JQLite(this[0].childNodes); }, append: function(node) { var self = this[0]; node = jqLite(node); foreach(node, function(child){ self.appendChild(child); }); }, remove: function() { this.dealoc(); var parentNode = this[0].parentNode; if (parentNode) parentNode.removeChild(this[0]); }, removeAttr: function(name) { this[0].removeAttribute(name); }, after: function(element) { this[0].parentNode.insertBefore(jqLite(element)[0], this[0].nextSibling); }, hasClass: function(selector) { var className = " " + selector + " "; if ( (" " + this[0].className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1 ) { return true; } return false; }, removeClass: function(selector) { this[0].className = trim((" " + this[0].className + " ").replace(/[\n\t]/g, " ").replace(" " + selector + " ", "")); }, toggleClass: function(selector, condition) { var self = this; (condition ? self.addClass : self.removeClass).call(self, selector); }, addClass: function( selector ) { if (!this.hasClass(selector)) { this[0].className = trim(this[0].className + ' ' + selector); } }, css: function(name, value) { var style = this[0].style; if (isString(name)) { if (isDefined(value)) { style[name] = value; } else { return style[name]; } } else { extend(style, name); } }, attr: function(name, value){ var e = this[0]; if (isObject(name)) { foreach(name, function(value, name){ e.setAttribute(name, value); }); } else if (isDefined(value)) { e.setAttribute(name, value); } else { // the extra argument is to get the right thing for a.href in IE, see jQuery code return e.getAttribute(name, 2); } }, text: function(value) { if (isDefined(value)) { this[0].textContent = value; } return this[0].textContent; }, val: function(value) { if (isDefined(value)) { this[0].value = value; } return this[0].value; }, html: function(value) { if (isDefined(value)) { var i = 0, childNodes = this[0].childNodes; for ( ; i < childNodes.length; i++) { jqLite(childNodes[i]).dealoc(); } this[0].innerHTML = value; } return this[0].innerHTML; }, parent: function() { return jqLite(this[0].parentNode); }, clone: function() { return jqLite(this[0].cloneNode(true)); } }; if (msie) { extend(JQLite.prototype, { text: function(value) { var e = this[0]; // NodeType == 3 is text node if (e.nodeType == 3) { if (isDefined(value)) e.nodeValue = value; return e.nodeValue; } else { if (isDefined(value)) e.innerText = value; return e.innerText; } } }); } var angularGlobal = { 'typeOf':function(obj){ if (obj === _null) return $null; var type = typeof obj; if (type == $object) { if (obj instanceof Array) return $array; if (isDate(obj)) return $date; if (obj.nodeType == 1) return $element; } return type; } }; var angularCollection = { 'copy': copy, 'size': size, 'equals': equals }; var angularObject = { 'extend': extend }; var angularArray = { 'indexOf': indexOf, 'sum':function(array, expression) { var fn = angular['Function']['compile'](expression); var sum = 0; for (var i = 0; i < array.length; i++) { var value = 1 * fn(array[i]); if (!isNaN(value)){ sum += value; } } return sum; }, 'remove':function(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; }, 'filter':function(array, expression) { var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; var search = function(obj, text){ if (text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return ('' + obj).toLowerCase().indexOf(text) > -1; case "object": for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function(){ var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(value, text); }); })(); } else { (function(){ var path = key; var text = (''+expression[key]).toLowerCase(); if (!text) return; predicates.push(function(value) { return search(getter(value, path), text); }); })(); } } break; case $function: predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; }, 'add':function(array, value) { array.push(isUndefined(value)? {} : value); return array; }, 'count':function(array, condition) { if (!condition) return array.length; var fn = angular['Function']['compile'](condition), count = 0; foreach(array, function(value){ if (fn(value)) { count ++; } }); return count; }, 'orderBy':function(array, expression, descend) { expression = isArray(expression) ? expression: [expression]; expression = map(expression, function($){ var descending = false, get = $ || identity; if (isString($)) { if (($.charAt(0) == '+' || $.charAt(0) == '-')) { descending = $.charAt(0) == '-'; $ = $.substring(1); } get = expressionCompile($).fnSelf; } return reverse(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverse(comparator, descend)); function comparator(o1, o2){ for ( var i = 0; i < expression.length; i++) { var comp = expression[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverse(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } }; var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/ var angularString = { 'quote':function(string) { return '"' + string.replace(/\\/g, '\\\\'). replace(/"/g, '\\"'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/\t/g, '\\t'). replace(/\v/g, '\\v') + '"'; }, 'quoteUnicode':function(string) { var str = angular['String']['quote'](string); var chars = []; for ( var i = 0; i < str.length; i++) { var ch = str.charCodeAt(i); if (ch < 128) { chars.push(str.charAt(i)); } else { var encode = "000" + ch.toString(16); chars.push("\\u" + encode.substring(encode.length - 4)); } } return chars.join(''); }, /** * Tries to convert input to date and if successful returns the date, otherwise returns the input. * @param {string} string * @return {(Date|string)} */ 'toDate':function(string){ var match; if (isString(string) && (match = string.match(R_ISO8061_STR))){ var date = new Date(0); date.setUTCFullYear(match[1], match[2] - 1, match[3]); date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0); return date; } return string; } }; var angularDate = { 'toString':function(date){ return !date ? date : date.toISOString ? date.toISOString() : padNumber(date.getUTCFullYear(), 4) + '-' + padNumber(date.getUTCMonth() + 1, 2) + '-' + padNumber(date.getUTCDate(), 2) + 'T' + padNumber(date.getUTCHours(), 2) + ':' + padNumber(date.getUTCMinutes(), 2) + ':' + padNumber(date.getUTCSeconds(), 2) + '.' + padNumber(date.getUTCMilliseconds(), 3) + 'Z'; } }; var angularFunction = { 'compile':function(expression) { if (isFunction(expression)){ return expression; } else if (expression){ return expressionCompile(expression).fnSelf; } else { return identity; } } }; function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; foreach(chain, function(parent){ extend(angular[dst], parent); }); } defineApi('Global', [angularGlobal]); defineApi('Collection', [angularGlobal, angularCollection]); defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); //IE bug angular['Date']['toString'] = angularDate['toString']; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); /** * @ngdoc filter * @name angular.filter.currency * @function * * @description * Formats a number as a currency (ie $1,234.56). * * @param {number} amount Input to filter. * @returns {string} Formated number. * * @css ng-format-negative * When the value is negative, this css class is applied to the binding making it by default red. * * @example <input type="text" name="amount" value="1234.56"/> <br/> {{amount | currency}} * * @scenario it('should init with 1234.56', function(){ expect(binding('amount | currency')).toBe('$1,234.56'); }); it('should update', function(){ input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('$-1,234.00'); expect(element('.doc-example-live .ng-binding').attr('className')). toMatch(/ng-format-negative/); }); */ angularFilter.currency = function(amount){ this.$element.toggleClass('ng-format-negative', amount < 0); return '$' + angularFilter['number'].apply(this, [amount, 2]); }; /** * @ngdoc filter * @name angular.filter.number * @function * * @description * Formats a number as text. * * If the input is not a number empty string is returned. * * @param {(number|string)} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. Default 2. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example Enter number: <input name='val' value='1234.56789' /><br/> Default formatting: {{val | number}}<br/> No fractions: {{val | number:0}}<br/> Negative number: {{-val | number:4}} * @scenario it('should format numbers', function(){ expect(binding('val | number')).toBe('1,234.57'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function(){ input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.33'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); */ angularFilter.number = function(number, fractionSize){ if (isNaN(number) || !isFinite(number)) { return ''; } fractionSize = typeof fractionSize == $undefined ? 2 : fractionSize; var isNegative = number < 0; number = Math.abs(number); var pow = Math.pow(10, fractionSize); var text = "" + Math.round(number * pow); var whole = text.substring(0, text.length - fractionSize); whole = whole || '0'; var frc = text.substring(text.length - fractionSize); text = isNegative ? '-' : ''; for (var i = 0; i < whole.length; i++) { if ((whole.length - i)%3 === 0 && i !== 0) { text += ','; } text += whole.charAt(i); } if (fractionSize > 0) { for (var j = frc.length; j < fractionSize; j++) { frc += '0'; } text += '.' + frc.substring(0, fractionSize); } return text; }; function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), a: function(date){return date.getHours() < 12 ? 'am' : 'pm';}, Z: function(date){ var offset = date.getTimezoneOffset(); return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2); } }; var DATE_FORMATS_SPLIT = /([^yMdHhmsaZ]*)(y+|M+|d+|H+|h+|m+|s+|a|Z)(.*)/; var NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name angular.filter.date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year e.g. 2010 * * `'yy'`: 2 digit representation of year, padded (00-99) * * `'MM'`: Month in year, padded (01‒12) * * `'M'`: Month in year (1‒12) * * `'dd'`: Day in month, padded (01‒31) * * `'d'`: Day in month (1-31) * * `'HH'`: Hour in day, padded (00‒23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01‒12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00‒59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00‒59) * * `'s'`: Second in minute (0‒59) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200‒1200) * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ). * @param {string=} format Formatting rules. If not specified, Date#toLocaleDateString is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/> <span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/> * * @scenario it('should format date', function(){ expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(am|pm)/); }); * */ angularFilter.date = function(date, format) { if (isString(date)) { if (NUMBER_STRING.test(date)) { date = parseInt(date, 10); } else { date = angularString.toDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } var text = date.toLocaleDateString(), fn; if (format && isString(format)) { text = ''; var parts = []; while(format) { parts = concat(parts, DATE_FORMATS_SPLIT.exec(format), 1); format = parts.pop(); } foreach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date) : value; }); } return text; }; /** * @ngdoc filter * @name angular.filter.json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * @css ng-monospace Always applied to the encapsulating element. * * @example: <input type="text" name="objTxt" value="{a:1, b:[]}" ng:eval="obj = $eval(objTxt)"/> <pre>{{ obj | json }}</pre> * * @scenario it('should jsonify filtered objects', function() { expect(binding('obj | json')).toBe('{\n "a":1,\n "b":[]}'); }); it('should update', function() { input('objTxt').enter('[1, 2, 3]'); expect(binding('obj | json')).toBe('[1,2,3]'); }); * */ angularFilter.json = function(object) { this.$element.addClass("ng-monospace"); return toJson(object, true); }; /** * @ngdoc filter * @name angular.filter.lowercase * @function * * @see angular.lowercase */ angularFilter.lowercase = lowercase; /** * @ngdoc filter * @name angular.filter.uppercase * @function * * @see angular.uppercase */ angularFilter.uppercase = uppercase; /** * @ngdoc filter * @name angular.filter.html * @function * * @description * Prevents the input from getting escaped by angular. By default the input is sanitized and * inserted into the DOM as is. * * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses * the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this * option is strongly discouraged and should be used only if you absolutely trust the input being * filtered and you can't get the content through the sanitizer. * * @param {string} html Html input. * @param {string=} option If 'unsafe' then do not sanitize the HTML input. * @returns {string} Sanitized or raw html. * * @example Snippet: <textarea name="snippet" cols="60" rows="3"> &lt;p style="color:blue"&gt;an html &lt;em onmouseover="this.textContent='PWN3D!'"&gt;click here&lt;/em&gt; snippet&lt;/p&gt;</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng:bind="snippet | html"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | html"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng:bind="snippet | html:'unsafe'"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet | html:'unsafe'"></div></td> </tr> </table> * * @scenario it('should sanitize the html snippet ', function(){ expect(using('#html-filter').binding('snippet | html')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it ('should escape snippet without any filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it ('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function(){ input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>'); expect(using('#escaped-html').binding('snippet')).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>'); }); */ angularFilter.html = function(html, option){ return new HTML(html, option); }; /** * @ngdoc filter * @name angular.filter.linky * @function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plane email address links. * * @param {string} text Input text. * @returns {string} Html-linkified text. * * @example Snippet: <textarea name="snippet" cols="60" rows="3"> Pretty text with some links: http://angularjs.org/, mailto:[email protected], [email protected], and one more: ftp://127.0.0.1/.</textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng:bind="snippet | linky"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng:bind="snippet | linky"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng:bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng:bind="snippet"></div></td> </tr> </table> @scenario it('should linkify the snippet with urls', function(){ expect(using('#linky-filter').binding('snippet | linky')). toBe('Pretty text with some links:\n' + '<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' + '<a href="mailto:[email protected]">[email protected]</a>,\n' + '<a href="mailto:[email protected]">[email protected]</a>,\n' + 'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.'); }); it ('should not linkify snippet without the linky filter', function() { expect(using('#escaped-html').binding('snippet')). toBe("Pretty text with some links:\n" + "http://angularjs.org/,\n" + "mailto:[email protected],\n" + "[email protected],\n" + "and one more: ftp://127.0.0.1/."); }); it('should update', function(){ input('snippet').enter('new http://link.'); expect(using('#linky-filter').binding('snippet | linky')). toBe('new <a href="http://link">http://link</a>.'); expect(using('#escaped-html').binding('snippet')).toBe('new http://link.'); }); */ //TODO: externalize all regexps angularFilter.linky = function(text){ if (!text) return text; var URL = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/; var match; var raw = text; var html = []; var writer = htmlSanitizeWriter(html); var url; var i; while (match=raw.match(URL)) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/mailto then assume mailto if (match[2]==match[3]) url = 'mailto:' + url; i = match.index; writer.chars(raw.substr(0, i)); writer.start('a', {href:url}); writer.chars(match[0].replace(/^mailto:/, '')); writer.end('a'); raw = raw.substring(i + match[0].length); } writer.chars(raw); return new HTML(html.join('')); }; function formatter(format, parse) {return {'format':format, 'parse':parse || format};} function toString(obj) { return (isDefined(obj) && obj !== _null) ? "" + obj : obj; } var NUMBER = /^\s*[-+]?\d*(\.\d*)?\s*$/; angularFormatter.noop = formatter(identity, identity); /** * @ngdoc formatter * @name angular.formatter.json * * @description * Formats the user input as JSON text. * * @returns {string} A JSON string representation of the model. * * @example * <div ng:init="data={name:'misko', project:'angular'}"> * <input type="text" size='50' name="data" ng:format="json"/> * <pre>data={{data}}</pre> * </div> * * @scenario * it('should format json', function(){ * expect(binding('data')).toEqual('data={\n \"name\":\"misko\",\n \"project\":\"angular\"}'); * input('data').enter('{}'); * expect(binding('data')).toEqual('data={\n }'); * }); */ angularFormatter.json = formatter(toJson, fromJson); /** * @ngdoc formatter * @name angular.formatter.boolean * * @description * Use boolean formatter if you wish to store the data as boolean. * * @returns Convert to `true` unless user enters (blank), `f`, `false`, `0`, `no`, `[]`. * * @example * Enter truthy text: * <input type="text" name="value" ng:format="boolean" value="no"/> * <input type="checkbox" name="value"/> * <pre>value={{value}}</pre> * * @scenario * it('should format boolean', function(){ * expect(binding('value')).toEqual('value=false'); * input('value').enter('truthy'); * expect(binding('value')).toEqual('value=true'); * }); */ angularFormatter['boolean'] = formatter(toString, toBoolean); /** * @ngdoc formatter * @name angular.formatter.number * * @description * Use number formatter if you wish to convert the user entered string to a number. * * @returns parse string to number. * * @example * Enter valid number: * <input type="text" name="value" ng:format="number" value="1234"/> * <pre>value={{value}}</pre> * * @scenario * it('should format numbers', function(){ * expect(binding('value')).toEqual('value=1234'); * input('value').enter('5678'); * expect(binding('value')).toEqual('value=5678'); * }); */ angularFormatter.number = formatter(toString, function(obj){ if (obj == _null || NUMBER.exec(obj)) { return obj===_null || obj === '' ? _null : 1*obj; } else { throw "Not a number"; } }); /** * @ngdoc formatter * @name angular.formatter.list * * @description * Use number formatter if you wish to convert the user entered string to a number. * * @returns parse string to number. * * @example * Enter a list of items: * <input type="text" name="value" ng:format="list" value=" chair ,, table"/> * <input type="text" name="value" ng:format="list"/> * <pre>value={{value}}</pre> * * @scenario * it('should format lists', function(){ * expect(binding('value')).toEqual('value=["chair","table"]'); * this.addFutureAction('change to XYZ', function($window, $document, done){ * $document.elements('.doc-example :input:last').val(',,a,b,').trigger('change'); * done(); * }); * expect(binding('value')).toEqual('value=["a","b"]'); * }); */ angularFormatter.list = formatter( function(obj) { return obj ? obj.join(", ") : obj; }, function(value) { var list = []; foreach((value || '').split(','), function(item){ item = trim(item); if (item) list.push(item); }); return list; } ); /** * @ngdoc formatter * @name angular.formatter.trim * * @description * Use trim formatter if you wish to trim extra spaces in user text. * * @returns {String} Trim excess leading and trailing space. * * @example * Enter text with leading/trailing spaces: * <input type="text" name="value" ng:format="trim" value=" book "/> * <input type="text" name="value" ng:format="trim"/> * <pre>value={{value|json}}</pre> * * @scenario * it('should format trim', function(){ * expect(binding('value')).toEqual('value="book"'); * this.addFutureAction('change to XYZ', function($window, $document, done){ * $document.elements('.doc-example :input:last').val(' text ').trigger('change'); * done(); * }); * expect(binding('value')).toEqual('value="text"'); * }); */ angularFormatter.trim = formatter( function(obj) { return obj ? trim("" + obj) : ""; } ); extend(angularValidator, { 'noop': function() { return _null; }, /** * @ngdoc validator * @name angular.validator.regexp * @description * Use regexp validator to restrict the input to any Regular Expression. * * @param {string} value value to validate * @param {regexp} expression regular expression. * @css ng-validation-error * * @example * Enter valid SSN: * <input name="ssn" value="123-45-6789" ng:validate="regexp:/^\d\d\d-\d\d-\d\d\d\d$/" > * * @scenario * it('should invalidate non ssn', function(){ * var textBox = element('.doc-example :input'); * expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); * expect(textBox.val()).toEqual('123-45-6789'); * * input('ssn').enter('123-45-67890'); * expect(textBox.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'regexp': function(value, regexp, msg) { if (!value.match(regexp)) { return msg || "Value does not match expected format " + regexp + "."; } else { return _null; } }, /** * @ngdoc validator * @name angular.validator.number * @description * Use number validator to restrict the input to numbers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example * Enter number: <input name="n1" ng:validate="number" > <br> * Enter number greater than 10: <input name="n2" ng:validate="number:10" > <br> * Enter number between 100 and 200: <input name="n3" ng:validate="number:100:200" > <br> * * @scenario * it('should invalidate number', function(){ * var n1 = element('.doc-example :input[name=n1]'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('n1').enter('1.x'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * * var n2 = element('.doc-example :input[name=n2]'); * expect(n2.attr('className')).not().toMatch(/ng-validation-error/); * input('n2').enter('9'); * expect(n2.attr('className')).toMatch(/ng-validation-error/); * * var n3 = element('.doc-example :input[name=n3]'); * expect(n3.attr('className')).not().toMatch(/ng-validation-error/); * input('n3').enter('201'); * expect(n3.attr('className')).toMatch(/ng-validation-error/); * * }); * */ 'number': function(value, min, max) { var num = 1 * value; if (num == value) { if (typeof min != $undefined && num < min) { return "Value can not be less than " + min + "."; } if (typeof min != $undefined && num > max) { return "Value can not be greater than " + max + "."; } return _null; } else { return "Not a number"; } }, /** * @ngdoc validator * @name angular.validator.integer * @description * Use number validator to restrict the input to integers with an * optional range. (See integer for whole numbers validator). * * @param {string} value value to validate * @param {int=} [min=MIN_INT] minimum value. * @param {int=} [max=MAX_INT] maximum value. * @css ng-validation-error * * @example * Enter integer: <input name="n1" ng:validate="integer" > <br> * Enter integer equal or greater than 10: <input name="n2" ng:validate="integer:10" > <br> * Enter integer between 100 and 200 (inclusive): <input name="n3" ng:validate="integer:100:200" > <br> * * @scenario * it('should invalidate integer', function(){ * var n1 = element('.doc-example :input[name=n1]'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('n1').enter('1.1'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * * var n2 = element('.doc-example :input[name=n2]'); * expect(n2.attr('className')).not().toMatch(/ng-validation-error/); * input('n2').enter('10.1'); * expect(n2.attr('className')).toMatch(/ng-validation-error/); * * var n3 = element('.doc-example :input[name=n3]'); * expect(n3.attr('className')).not().toMatch(/ng-validation-error/); * input('n3').enter('100.1'); * expect(n3.attr('className')).toMatch(/ng-validation-error/); * * }); */ 'integer': function(value, min, max) { var numberError = angularValidator['number'](value, min, max); if (numberError) return numberError; if (!("" + value).match(/^\s*[\d+]*\s*$/) || value != Math.round(value)) { return "Not a whole number"; } return _null; }, /** * @ngdoc validator * @name angular.validator.date * @description * Use date validator to restrict the user input to a valid date * in format in format MM/DD/YYYY. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid date: * <input name="text" value="1/1/2009" ng:validate="date" > * * @scenario * it('should invalidate date', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('123/123/123'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'date': function(value) { var fields = /^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(value); var date = fields ? new Date(fields[3], fields[1]-1, fields[2]) : 0; return (date && date.getFullYear() == fields[3] && date.getMonth() == fields[1]-1 && date.getDate() == fields[2]) ? _null : "Value is not a date. (Expecting format: 12/31/2009)."; }, /** * @ngdoc validator * @name angular.validator.email * @description * Use email validator if you wist to restrict the user input to a valid email. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid email: * <input name="text" ng:validate="email" value="[email protected]"> * * @scenario * it('should invalidate email', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('[email protected]'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'email': function(value) { if (value.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) { return _null; } return "Email needs to be in [email protected] format."; }, /** * @ngdoc validator * @name angular.validator.phone * @description * Use phone validator to restrict the input phone numbers. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid phone number: * <input name="text" value="1(234)567-8901" ng:validate="phone" > * * @scenario * it('should invalidate phone', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('+12345678'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'phone': function(value) { if (value.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)) { return _null; } if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) { return _null; } return "Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly."; }, /** * @ngdoc validator * @name angular.validator.url * @description * Use phone validator to restrict the input URLs. * * @param {string} value value to validate * @css ng-validation-error * * @example * Enter valid phone number: * <input name="text" value="http://example.com/abc.html" size="40" ng:validate="url" > * * @scenario * it('should invalidate url', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('text').enter('abc://server/path'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'url': function(value) { if (value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) { return _null; } return "URL needs to be in http://server[:port]/path format."; }, /** * @ngdoc validator * @name angular.validator.json * @description * Use json validator if you wish to restrict the user input to a valid JSON. * * @param {string} value value to validate * @css ng-validation-error * * @example * <textarea name="json" cols="60" rows="5" ng:validate="json"> * {name:'abc'} * </textarea> * * @scenario * it('should invalidate json', function(){ * var n1 = element('.doc-example :input'); * expect(n1.attr('className')).not().toMatch(/ng-validation-error/); * input('json').enter('{name}'); * expect(n1.attr('className')).toMatch(/ng-validation-error/); * }); * */ 'json': function(value) { try { fromJson(value); return _null; } catch (e) { return e.toString(); } }, /** * @ngdoc validator * @name angular.validator.asynchronous * @description * Use asynchronous validator if the validation can not be computed * immediately, but is provided through a callback. The widget * automatically shows a spinning indicator while the validity of * the widget is computed. This validator caches the result. * * @param {string} value value to validate * @param {function(inputToValidate,validationDone)} validate function to call to validate the state * of the input. * @param {function(data)=} [update=noop] function to call when state of the * validator changes * * @paramDescription * The `validate` function (specified by you) is called as * `validate(inputToValidate, validationDone)`: * * * `inputToValidate`: value of the input box. * * `validationDone`: `function(error, data){...}` * * `error`: error text to display if validation fails * * `data`: data object to pass to update function * * The `update` function is optionally specified by you and is * called by <angular/> on input change. Since the * asynchronous validator caches the results, the update * function can be called without a call to `validate` * function. The function is called as `update(data)`: * * * `data`: data object as passed from validate function * * @css ng-input-indicator-wait, ng-validation-error * * @example * <script> * function myValidator(inputToValidate, validationDone) { * setTimeout(function(){ * validationDone(inputToValidate.length % 2); * }, 500); * } * </script> * This input is validated asynchronously: * <input name="text" ng:validate="asynchronous:$window.myValidator"> * * @scenario * it('should change color in delayed way', function(){ * var textBox = element('.doc-example :input'); * expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); * expect(textBox.attr('className')).not().toMatch(/ng-validation-error/); * * input('text').enter('X'); * expect(textBox.attr('className')).toMatch(/ng-input-indicator-wait/); * * pause(.6); * * expect(textBox.attr('className')).not().toMatch(/ng-input-indicator-wait/); * expect(textBox.attr('className')).toMatch(/ng-validation-error/); * * }); * */ /* * cache is attached to the element * cache: { * inputs : { * 'user input': { * response: server response, * error: validation error * }, * current: 'current input' * } * */ 'asynchronous': function(input, asynchronousFn, updateFn) { if (!input) return; var scope = this; var element = scope.$element; var cache = element.data('$asyncValidator'); if (!cache) { element.data('$asyncValidator', cache = {inputs:{}}); } cache.current = input; var inputState = cache.inputs[input]; if (!inputState) { cache.inputs[input] = inputState = { inFlight: true }; scope.$invalidWidgets.markInvalid(scope.$element); element.addClass('ng-input-indicator-wait'); asynchronousFn(input, function(error, data) { inputState.response = data; inputState.error = error; inputState.inFlight = false; if (cache.current == input) { element.removeClass('ng-input-indicator-wait'); scope.$invalidWidgets.markValid(element); } element.data('$validate')(); scope.$root.$eval(); }); } else if (inputState.inFlight) { // request in flight, mark widget invalid, but don't show it to user scope.$invalidWidgets.markInvalid(scope.$element); } else { (updateFn||noop)(inputState.response); } return inputState.error; } }); var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, HASH_MATCH = /^([^\?]*)?(\?([^\?]*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp':21}, EAGER = 'eager', EAGER_PUBLISHED = EAGER + '-published'; function angularServiceInject(name, fn, inject, eager) { angularService(name, fn, {$inject:inject, $creation:eager}); } angularServiceInject("$window", bind(window, identity, window), [], EAGER_PUBLISHED); angularServiceInject("$document", function(window){ return jqLite(window.document); }, ['$window'], EAGER_PUBLISHED); angularServiceInject("$location", function(browser) { var scope = this, location = {toString:toString, update:update, updateHash: updateHash}, lastBrowserUrl = browser.getUrl(), lastLocationHref, lastLocationHash; browser.addPollFn(function() { if (lastBrowserUrl != browser.getUrl()) { update(lastBrowserUrl = browser.getUrl()); updateLastLocation(); scope.$eval(); } }); this.$onEval(PRIORITY_FIRST, updateBrowser); this.$onEval(PRIORITY_LAST, updateBrowser); update(lastBrowserUrl); updateLastLocation(); return location; // PUBLIC METHODS /** * Update location object * Does not immediately update the browser * Browser is updated at the end of $eval() * * @example * scope.$location.update('http://www.angularjs.org/path#hash?search=x'); * scope.$location.update({host: 'www.google.com', protocol: 'https'}); * scope.$location.update({hashPath: '/path', hashSearch: {a: 'b', x: true}}); * * @param {(string|Object)} href Full href as a string or hash object with properties */ function update(href) { if (isString(href)) { extend(location, parseHref(href)); } else { if (isDefined(href.hash)) { extend(href, parseHash(href.hash)); } extend(location, href); if (isDefined(href.hashPath || href.hashSearch)) { location.hash = composeHash(location); } location.href = composeHref(location); } } /** * Update location hash * @see update() * * @example * scope.$location.updateHash('/hp') * ==> update({hashPath: '/hp'}) * * scope.$location.updateHash({a: true, b: 'val'}) * ==> update({hashSearch: {a: true, b: 'val'}}) * * scope.$location.updateHash('/hp', {a: true}) * ==> update({hashPath: '/hp', hashSearch: {a: true}}) * * @param {(string|Object)} path A hashPath or hashSearch object * @param {Object=} search A hashSearch object */ function updateHash(path, search) { var hash = {}; if (isString(path)) { hash.hashPath = path; if (isDefined(search)) hash.hashSearch = search; } else hash.hashSearch = path; update(hash); } /** * Returns string representation - href * * @return {string} Location's href property */ function toString() { updateLocation(); return location.href; } // INNER METHODS /** * Update location object * * User is allowed to change properties, so after property change, * location object is not in consistent state. * * @example * scope.$location.href = 'http://www.angularjs.org/path#a/b' * immediately after this call, other properties are still the old ones... * * This method checks the changes and update location to the consistent state */ function updateLocation() { if (location.href == lastLocationHref) { if (location.hash == lastLocationHash) { location.hash = composeHash(location); } location.href = composeHref(location); } update(location.href); } /** * Update information about last location */ function updateLastLocation() { lastLocationHref = location.href; lastLocationHash = location.hash; } /** * If location has changed, update the browser * This method is called at the end of $eval() phase */ function updateBrowser() { updateLocation(); if (location.href != lastLocationHref) { browser.setUrl(lastBrowserUrl = location.href); updateLastLocation(); } } /** * Compose href string from a location object * * @param {Object} loc The location object with all properties * @return {string} Composed href */ function composeHref(loc) { var url = toKeyValue(loc.search); var port = (loc.port == DEFAULT_PORTS[loc.protocol] ? _null : loc.port); return loc.protocol + '://' + loc.host + (port ? ':' + port : '') + loc.path + (url ? '?' + url : '') + (loc.hash ? '#' + loc.hash : ''); } /** * Compose hash string from location object * * @param {Object} loc Object with hashPath and hashSearch properties * @return {string} Hash string */ function composeHash(loc) { var hashSearch = toKeyValue(loc.hashSearch); return escape(loc.hashPath) + (hashSearch ? '?' + hashSearch : ''); } /** * Parse href string into location object * * @param {string} href * @return {Object} The location object */ function parseHref(href) { var loc = {}; var match = URL_MATCH.exec(href); if (match) { loc.href = href.replace(/#$/, ''); loc.protocol = match[1]; loc.host = match[3] || ''; loc.port = match[5] || DEFAULT_PORTS[loc.protocol] || _null; loc.path = match[6] || ''; loc.search = parseKeyValue(match[8]); loc.hash = match[10] || ''; extend(loc, parseHash(loc.hash)); } return loc; } /** * Parse hash string into object * * @param {string} hash */ function parseHash(hash) { var h = {}; var match = HASH_MATCH.exec(hash); if (match) { h.hash = hash; h.hashPath = unescape(match[1] || ''); h.hashSearch = parseKeyValue(match[3]); } return h; } }, ['$browser'], EAGER_PUBLISHED); angularServiceInject("$log", function($window){ var console = $window.console || {log: noop, warn: noop, info: noop, error: noop}, log = console.log || noop; return { log: bind(console, log), warn: bind(console, console.warn || log), info: bind(console, console.info || log), error: bind(console, console.error || log) }; }, ['$window'], EAGER_PUBLISHED); angularServiceInject('$exceptionHandler', function($log){ return function(e) { $log.error(e); }; }, ['$log'], EAGER_PUBLISHED); angularServiceInject("$hover", function(browser, document) { var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body); browser.hover(function(element, show){ if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) { if (!tooltip) { tooltip = { callout: jqLite('<div id="ng-callout"></div>'), arrow: jqLite('<div></div>'), title: jqLite('<div class="ng-title"></div>'), content: jqLite('<div class="ng-content"></div>') }; tooltip.callout.append(tooltip.arrow); tooltip.callout.append(tooltip.title); tooltip.callout.append(tooltip.content); body.append(tooltip.callout); } var docRect = body[0].getBoundingClientRect(), elementRect = element[0].getBoundingClientRect(), leftSpace = docRect.right - elementRect.right - arrowWidth; tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error..."); tooltip.content.text(error); if (leftSpace < width) { tooltip.arrow.addClass('ng-arrow-right'); tooltip.arrow.css({left: (width + 1)+'px'}); tooltip.callout.css({ position: 'fixed', left: (elementRect.left - arrowWidth - width - 4) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } else { tooltip.arrow.addClass('ng-arrow-left'); tooltip.callout.css({ position: 'fixed', left: (elementRect.right + arrowWidth) + "px", top: (elementRect.top - 3) + "px", width: width + "px" }); } } else if (tooltip) { tooltip.callout.remove(); tooltip = _null; } }); }, ['$browser', '$document'], EAGER); /* Keeps references to all invalid widgets found during validation. Can be queried to find if there * are invalid widgets currently displayed */ angularServiceInject("$invalidWidgets", function(){ var invalidWidgets = []; /** Remove an element from the array of invalid widgets */ invalidWidgets.markValid = function(element){ var index = indexOf(invalidWidgets, element); if (index != -1) invalidWidgets.splice(index, 1); }; /** Add an element to the array of invalid widgets */ invalidWidgets.markInvalid = function(element){ var index = indexOf(invalidWidgets, element); if (index === -1) invalidWidgets.push(element); }; /** Return count of all invalid widgets that are currently visible */ invalidWidgets.visible = function() { var count = 0; foreach(invalidWidgets, function(widget){ count = count + (isVisible(widget) ? 1 : 0); }); return count; }; /* At the end of each eval removes all invalid widgets that are not part of the current DOM. */ this.$onEval(PRIORITY_LAST, function() { for(var i = 0; i < invalidWidgets.length;) { var widget = invalidWidgets[i]; if (isOrphan(widget[0])) { invalidWidgets.splice(i, 1); if (widget.dealoc) widget.dealoc(); } else { i++; } } }); /** * Traverses DOM element's (widget's) parents and considers the element to be an orphant if one of * it's parents isn't the current window.document. */ function isOrphan(widget) { if (widget == window.document) return false; var parent = widget.parentNode; return !parent || isOrphan(parent); } return invalidWidgets; }, [], EAGER_PUBLISHED); function switchRouteMatcher(on, when, dstName) { var regex = '^' + when.replace(/[\.\\\(\)\^\$]/g, "\$1") + '$', params = [], dst = {}; foreach(when.split(/\W/), function(param){ if (param) { var paramRegExp = new RegExp(":" + param + "([\\W])"); if (regex.match(paramRegExp)) { regex = regex.replace(paramRegExp, "([^\/]*)$1"); params.push(param); } } }); var match = on.match(new RegExp(regex)); if (match) { foreach(params, function(name, index){ dst[name] = match[index + 1]; }); if (dstName) this.$set(dstName, dst); } return match ? dst : _null; } angularServiceInject('$route', function(location){ var routes = {}, onChange = [], matcher = switchRouteMatcher, parentScope = this, dirty = 0, $route = { routes: routes, onChange: bind(onChange, onChange.push), when:function (path, params){ if (angular.isUndefined(path)) return routes; var route = routes[path]; if (!route) route = routes[path] = {}; if (params) angular.extend(route, params); dirty++; return route; } }; function updateRoute(){ var childScope; $route.current = _null; angular.foreach(routes, function(routeParams, route) { if (!childScope) { var pathParams = matcher(location.hashPath, route); if (pathParams) { childScope = angular.scope(parentScope); $route.current = angular.extend({}, routeParams, { scope: childScope, params: angular.extend({}, location.hashSearch, pathParams) }); } } }); angular.foreach(onChange, parentScope.$tryEval); if (childScope) { childScope.$become($route.current.controller); } } this.$watch(function(){return dirty + location.hash;}, updateRoute); return $route; }, ['$location'], EAGER_PUBLISHED); angularServiceInject('$xhr', function($browser, $error, $log){ var self = this; return function(method, url, post, callback){ if (isFunction(post)) { callback = post; post = _null; } if (post && isObject(post)) { post = toJson(post); } $browser.xhr(method, url, post, function(code, response){ try { if (isString(response) && /^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { response = fromJson(response); } if (code == 200) { callback(code, response); } else { $error( {method: method, url:url, data:post, callback:callback}, {status: code, body:response}); } } catch (e) { $log.error(e); } finally { self.$eval(); } }); }; }, ['$browser', '$xhr.error', '$log']); angularServiceInject('$xhr.error', function($log){ return function(request, response){ $log.error('ERROR: XHR: ' + request.url, request, response); }; }, ['$log']); angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, callback) { if (isFunction(post)) { callback = post; post = _null; } var currentQueue; foreach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; currentQueue.requests.push({method: method, url: url, data:post, callback:callback}); } else { $xhr(method, url, post, callback); } } bulkXHR.urls = {}; bulkXHR.flush = function(callback){ foreach(bulkXHR.urls, function(queue, url){ var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests:currentRequests}, function(code, response){ foreach(response, function(response, i){ try { if (response.status == 200) { (currentRequests[i].callback || noop)(response.status, response.response); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); (callback || noop)(); }); scope.$eval(); } }); }; this.$onEval(PRIORITY_LAST, bulkXHR.flush); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']); angularServiceInject('$xhr.cache', function($xhr){ var inflight = {}, self = this; function cache(method, url, post, callback, verifyCache){ if (isFunction(post)) { callback = post; post = _null; } if (method == 'GET') { var data; if (data = cache.data[url]) { callback(200, copy(data.value)); if (!verifyCache) return; } if (data = inflight[url]) { data.callbacks.push(callback); } else { inflight[url] = {callbacks: [callback]}; cache.delegate(method, url, post, function(status, response){ if (status == 200) cache.data[url] = { value: response }; var callbacks = inflight[url].callbacks; delete inflight[url]; foreach(callbacks, function(callback){ try { (callback||noop)(status, copy(response)); } catch(e) { self.$log.error(e); } }); }); } } else { cache.data = {}; cache.delegate(method, url, post, callback); } } cache.data = {}; cache.delegate = $xhr; return cache; }, ['$xhr.bulk']); angularServiceInject('$resource', function($xhr){ var resource = new ResourceFactory($xhr); return bind(resource, resource.route); }, ['$xhr.cache']); /** * $cookies service provides read/write access to the browser cookies. Currently only session * cookies are supported. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created or deleted from the browser at the end of the current eval. */ angularServiceInject('$cookies', function($browser) { var rootScope = this, cookies = {}, lastCookies = {}, lastBrowserCookies; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); rootScope.$eval(); } })(); //at the end of each eval, push cookies this.$onEval(PRIORITY_LAST, push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were stored. */ function push(){ var name, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, _undefined); } } //update all cookies updated in $cookies for(name in cookies) { if (cookies[name] !== lastCookies[name]) { $browser.cookies(name, cookies[name]); updated = true; } } //verify what was actually stored if (updated){ updated = !updated; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } if (updated) { rootScope.$eval(); } } } }, ['$browser'], EAGER_PUBLISHED); /** * $cookieStore provides a key-value (string-object) storage that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or deserialized. */ angularServiceInject('$cookieStore', function($store) { return { get: function(/**string*/key) { return fromJson($store[key]); }, put: function(/**string*/key, /**Object*/value) { $store[key] = toJson(value); }, remove: function(/**string*/key) { delete $store[key]; } }; }, ['$cookies']); /** * @ngdoc directive * @name angular.directive.ng:init * * @description * `ng:init` attribute allows the for initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} expression to eval. * * @example <div ng:init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> * * @scenario it('should check greeting', function(){ expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); */ angularDirective("ng:init", function(expression){ return function(element){ this.$tryEval(expression, element); }; }); /** * @ngdoc directive * @name angular.directive.ng:controller * * @description * To support the Model-View-Controller design pattern, it is possible * to assign behavior to a scope through `ng:controller`. The scope is * the MVC model. The HTML (with data bindings) is the MVC view. * The `ng:controller` directive specifies the MVC controller class * * @element ANY * @param {expression} expression to eval. * * @example <script type="text/javascript"> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'[email protected]'} ]; } SettingsController.prototype = { greet: function(){ alert(this.name); }, addContact: function(){ this.contacts.push({type:'email', value:'[email protected]'}); }, removeContact: function(contactToRemove) { angular.Array.remove(this.contacts, contactToRemove); }, clearContact: function(contact) { contact.type = 'phone'; contact.value = ''; } }; </script> <div ng:controller="SettingsController"> Name: <input type="text" name="name"/> [ <a href="" ng:click="greet()">greet</a> ]<br/> Contact: <ul> <li ng:repeat="contact in contacts"> <select name="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" name="contact.value"/> [ <a href="" ng:click="clearContact(contact)">clear</a> | <a href="" ng:click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng:click="addContact()">add</a> ]</li> </ul> </div> * * @scenario it('should check controller', function(){ expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li[ng\\:repeat-index="0"] input').val()).toBe('408 555 1212'); expect(element('.doc-example-live li[ng\\:repeat-index="1"] input').val()).toBe('[email protected]'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li[ng\\:repeat-index="2"] input').val()).toBe('[email protected]'); }); */ angularDirective("ng:controller", function(expression){ this.scope(true); return function(element){ var controller = getter(window, expression, true) || getter(this, expression, true); if (!controller) throw "Can not find '"+expression+"' controller."; if (!isFunction(controller)) throw "Reference '"+expression+"' is not a class."; this.$become(controller); }; }); /** * @ngdoc directive * @name angular.directive.ng:eval * * @description * The `ng:eval` allows you to execute a binding which has side effects * without displaying the result to the user. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * Notice that `{{` `obj.multiplied = obj.a * obj.b` `}}` has a side effect of assigning * a value to `obj.multiplied` and displaying the result to the user. Sometimes, * however, it is desirable to execute a side effect without showing the value to * the user. In such a case `ng:eval` allows you to execute code without updating * the display. * * @example * <input name="obj.a" value="6" > * * <input name="obj.b" value="2"> * = {{obj.multiplied = obj.a * obj.b}} <br> * <span ng:eval="obj.divide = obj.a / obj.b"></span> * <span ng:eval="obj.updateCount = 1 + (obj.updateCount||0)"></span> * <tt>obj.divide = {{obj.divide}}</tt><br/> * <tt>obj.updateCount = {{obj.updateCount}}</tt> * * @scenario it('should check eval', function(){ expect(binding('obj.divide')).toBe('3'); expect(binding('obj.updateCount')).toBe('2'); input('obj.a').enter('12'); expect(binding('obj.divide')).toBe('6'); expect(binding('obj.updateCount')).toBe('3'); }); */ angularDirective("ng:eval", function(expression){ return function(element){ this.$onEval(expression, element); }; }); /** * @ngdoc directive * @name angular.directive.ng:bind * * @description * The `ng:bind` attribute asks <angular/> to replace the text content of this * HTML element with the value of the given expression and kept it up to * date when the expression's value changes. Usually you just write * {{expression}} and let <angular/> compile it into * <span ng:bind="expression"></span> at bootstrap time. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * Try it here: enter text in text box and watch the greeting change. * @example * Enter name: <input type="text" name="name" value="Whirled">. <br> * Hello <span ng:bind="name" />! * * @scenario it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); */ angularDirective("ng:bind", function(expression, element){ element.addClass('ng-binding'); return function(element) { var lastValue = noop, lastError = noop; this.$onEval(function() { var error, value, html, isHtml, isDomElement, oldElement = this.hasOwnProperty($$element) ? this.$element : _undefined; this.$element = element; value = this.$tryEval(expression, function(e){ error = toJson(e); }); this.$element = oldElement; // If we are HTML than save the raw HTML data so that we don't // recompute sanitization since it is expensive. // TODO: turn this into a more generic way to compute this if (isHtml = (value instanceof HTML)) value = (html = value).html; if (lastValue === value && lastError == error) return; isDomElement = isElement(value); if (!isHtml && !isDomElement && isObject(value)) { value = toJson(value); } if (value != lastValue || error != lastError) { lastValue = value; lastError = error; elementError(element, NG_EXCEPTION, error); if (error) value = error; if (isHtml) { element.html(html.get()); } else if (isDomElement) { element.html(''); element.append(value); } else { element.text(value === _undefined ? '' : value); } } }, element); }; }); var bindTemplateCache = {}; function compileBindTemplate(template){ var fn = bindTemplateCache[template]; if (!fn) { var bindings = []; foreach(parseBindings(template), function(text){ var exp = binding(text); bindings.push(exp ? function(element){ var error, value = this.$tryEval(exp, function(e){ error = toJson(e); }); elementError(element, NG_EXCEPTION, error); return error ? error : value; } : function() { return text; }); }); bindTemplateCache[template] = fn = function(element){ var parts = [], self = this, oldElement = this.hasOwnProperty($$element) ? self.$element : _undefined; self.$element = element; for ( var i = 0; i < bindings.length; i++) { var value = bindings[i].call(self, element); if (isElement(value)) value = ''; else if (isObject(value)) value = toJson(value, true); parts.push(value); } self.$element = oldElement; return parts.join(''); }; } return fn; } /** * @ngdoc directive * @name angular.directive.ng:bind-template * * @description * The `ng:bind-template` attribute specifies that the element * text should be replaced with the template in ng:bind-template. * Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few. * * @element ANY * @param {string} template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @exampleDescription * Try it here: enter text in text box and watch the greeting change. * @example Salutation: <input type="text" name="salutation" value="Hello"><br/> Name: <input type="text" name="name" value="World"><br/> <pre ng:bind-template="{{salutation}} {{name}}!"></pre> * * @scenario it('should check ng:bind', function(){ expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Hello World!'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('{{salutation}} {{name}}')). toBe('Greetings user!'); }); */ angularDirective("ng:bind-template", function(expression, element){ element.addClass('ng-binding'); var templateFn = compileBindTemplate(expression); return function(element) { var lastValue; this.$onEval(function() { var value = templateFn.call(this, element); if (value != lastValue) { element.text(value); lastValue = value; } }, element); }; }); var REMOVE_ATTRIBUTES = { 'disabled':'disabled', 'readonly':'readOnly', 'checked':'checked' }; /** * @ngdoc directive * @name angular.directive.ng:bind-attr * * @description * The `ng:bind-attr` attribute specifies that the element attributes * which should be replaced by the expression in it. Unlike `ng:bind` * the `ng:bind-attr` contains a JSON key value pairs representing * which attributes need to be changed. You don’t usually write the * `ng:bind-attr` in the HTML since embedding * <tt ng:non-bindable>{{expression}}</tt> into the * attribute directly is the preferred way. The attributes get * translated into <span ng:bind-attr="{attr:expression}"/> at * bootstrap time. * * This HTML snippet is preferred way of working with `ng:bind-attr` * <pre> * <a href="http://www.google.com/search?q={{query}}">Google</a> * </pre> * * The above gets translated to bellow during bootstrap time. * <pre> * <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a> * </pre> * * @element ANY * @param {string} attribute_json a JSON key-value pairs representing * the attributes to replace. Each key matches the attribute * which needs to be replaced. Each value is a text template of * the attribute with embedded * <tt ng:non-bindable>{{expression}}</tt>s. Any number of * key-value pairs can be specified. * * @exampleDescription * Try it here: enter text in text box and click Google. * @example Google for: <input type="text" name="query" value="AngularJS"/> <a href="http://www.google.com/search?q={{query}}">Google</a> * * @scenario it('should check ng:bind-attr', function(){ expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=AngularJS'); using('.doc-example-live').input('query').enter('google'); expect(using('.doc-example-live').element('a').attr('href')). toBe('http://www.google.com/search?q=google'); }); */ angularDirective("ng:bind-attr", function(expression){ return function(element){ var lastValue = {}; var updateFn = element.parent().data('$update'); this.$onEval(function(){ var values = this.$eval(expression); for(var key in values) { var value = compileBindTemplate(values[key]).call(this, element), specialName = REMOVE_ATTRIBUTES[lowercase(key)]; if (lastValue[key] !== value) { lastValue[key] = value; if (specialName) { if (element[specialName] = toBoolean(value)) { element.attr(specialName, value); } else { element.removeAttr(key); } (element.data('$validate')||noop)(); } else { element.attr(key, value); } this.$postEval(updateFn); } } }, element); }; }); /** * @ngdoc directive * @name angular.directive.ng:non-bindable * * @description * Sometimes it is necessary to write code which looks like * bindings but which should be left alone by <angular/>. * Use `ng:non-bindable` to ignore a chunk of HTML. * * @element ANY * @param {string} ignore * * @exampleDescription * In this example there are two location where * <tt ng:non-bindable>{{1 + 2}}</tt> is present, but the one * wrapped in `ng:non-bindable` is left alone * @example <div>Normal: {{1 + 2}}</div> <div ng:non-bindable>Ignored: {{1 + 2}}</div> * * @scenario it('should check ng:non-bindable', function(){ expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); */ angularWidget("@ng:non-bindable", noop); /** * @ngdoc directive * @name angular.directive.ng:repeat * * @description * `ng:repeat` instantiates a template once per item from a * collection. The collection is enumerated with * `ng:repeat-index` attribute starting from 0. Each template * instance gets its own scope where the given loop variable * is set to the current collection item and `$index` is set * to the item index or key. * * NOTE: `ng:repeat` looks like a directive, but is actually a * attribute widget. * * @element ANY * @param {repeat} repeat_expression to itterate over. * * * `variable in expression`, where variable is the user * defined loop variable and expression is a scope expression * giving the collection to enumerate. For example: * `track in cd.tracks`. * * `(key, value) in expression`, where key and value can * be any user defined identifiers, and expression is the * scope expression giving the collection to enumerate. * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * Special properties set on the local scope: * * {number} $index - iterator offset of the repeated element (0..length-1) * * {string} $position - position of the repeated element in the iterator ('first', 'middle', 'last') * * @exampleDescription * This example initializes the scope to a list of names and * than uses `ng:repeat` to display every person. * @example <div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> I have {{friends.length}} friends. They are: <ul> <li ng:repeat="friend in friends"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> * @scenario it('should check ng:repeat', function(){ var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Mary","28"]); }); */ angularWidget("@ng:repeat", function(expression, element){ element.removeAttr('ng:repeat'); element.replaceWith(this.comment("ng:repeat: " + expression)); var template = this.compile(element); return function(reference){ var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), lhs, rhs, valueIdent, keyIdent; if (! match) { throw "Expected ng:repeat in form of 'item in collection' but got '" + expression + "'."; } lhs = match[1]; rhs = match[2]; match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); if (!match) { throw "'item' in 'item in collection' should be identifier or (key, value) but got '" + keyValue + "'."; } valueIdent = match[3] || match[1]; keyIdent = match[2]; var children = [], currentScope = this; this.$onEval(function(){ var index = 0, childCount = children.length, lastElement = reference, collection = this.$tryEval(rhs, reference), is_array = isArray(collection), collectionLength = 0, childScope, key; if (is_array) { collectionLength = collection.length; } else { for (key in collection) if (collection.hasOwnProperty(key)) collectionLength++; } for (key in collection) { if (!is_array || collection.hasOwnProperty(key)) { if (index < childCount) { // reuse existing child childScope = children[index]; childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; } else { // grow children childScope = template(quickClone(element), createScope(currentScope)); childScope[valueIdent] = collection[key]; if (keyIdent) childScope[keyIdent] = key; lastElement.after(childScope.$element); childScope.$index = index; childScope.$position = index == 0 ? 'first' : (index == collectionLength - 1 ? 'last' : 'middle'); childScope.$element.attr('ng:repeat-index', index); childScope.$init(); children.push(childScope); } childScope.$eval(); lastElement = childScope.$element; index ++; } } // shrink children while(children.length > index) { children.pop().$element.remove(); } }, reference); }; }); /** * @ngdoc directive * @name angular.directive.ng:click * * @description * The ng:click allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} expression to eval upon click. * * @example <button ng:click="count = count + 1" ng:init="count=0"> Increment </button> count: {{count}} * @scenario it('should check ng:click', function(){ expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. * * TODO: maybe we should consider allowing users to control event propagation in the future. */ angularDirective("ng:click", function(expression, element){ return function(element){ var self = this; element.bind('click', function(event){ self.$tryEval(expression, element); self.$root.$eval(); event.stopPropagation(); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:submit * * @description * * @element form * @param {expression} expression to eval. * * @exampleDescription * @example * <form ng:submit="list.push(text);text='';" ng:init="list=[]"> * Enter text and hit enter: * <input type="text" name="text" value="hello"/> * </form> * <pre>list={{list}}</pre> * @scenario it('should check ng:submit', function(){ expect(binding('list')).toBe('list=[]'); element('.doc-example-live form input').click(); this.addFutureAction('submit from', function($window, $document, done) { $window.angular.element( $document.elements('.doc-example-live form')). trigger('submit'); done(); }); expect(binding('list')).toBe('list=["hello"]'); }); */ /** * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). */ angularDirective("ng:submit", function(expression, element) { return function(element) { var self = this; element.bind('submit', function(event) { self.$tryEval(expression, element); self.$root.$eval(); event.preventDefault(); }); }; }); /** * @ngdoc directive * @name angular.directive.ng:watch * * @description * The `ng:watch` allows you watch a variable and then execute * an evaluation on variable change. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * Notice that the counter is incremented * every time you change the text. * @example <div ng:init="counter=0" ng:watch="name: counter = counter+1"> <input type="text" name="name" value="hello"><br/> Change counter: {{counter}} Name: {{name}} </div> * @scenario it('should check ng:watch', function(){ expect(using('.doc-example-live').binding('counter')).toBe('2'); using('.doc-example-live').input('name').enter('abc'); expect(using('.doc-example-live').binding('counter')).toBe('3'); }); */ angularDirective("ng:watch", function(expression, element){ return function(element){ var self = this; parser(expression).watch()({ addListener:function(watch, exp){ self.$watch(watch, function(){ return exp(self); }, element); } }); }; }); function ngClass(selector) { return function(expression, element){ var existing = element[0].className + ' '; return function(element){ this.$onEval(function(){ if (selector(this.$index)) { var value = this.$eval(expression); if (isArray(value)) value = value.join(' '); element[0].className = trim(existing + value); } }, element); }; }; } /** * @ngdoc directive * @name angular.directive.ng:class * * @description * The `ng:class` allows you to set CSS class on HTML element * conditionally. * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * @example <input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'"> <input type="button" value="clear" ng:click="myVar=''"> <br> <span ng:class="myVar">Sample Text &nbsp;&nbsp;&nbsp;&nbsp;</span> * * @scenario it('should check ng:class', function(){ expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').attr('className')). toMatch(/ng-input-indicator-wait/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').attr('className')).not(). toMatch(/ng-input-indicator-wait/); }); */ angularDirective("ng:class", ngClass(function(){return true;})); /** * @ngdoc directive * @name angular.directive.ng:class-odd * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression to eval. Must be inside * `ng:repeat`. * * @exampleDescription * @example <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> * * @scenario it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); */ angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;})); /** * @ngdoc directive * @name angular.directive.ng:class-even * * @description * The `ng:class-odd` and `ng:class-even` works exactly as * `ng:class`, except it works in conjunction with `ng:repeat` * and takes affect only on odd (even) rows. * * @element ANY * @param {expression} expression to eval. Must be inside * `ng:repeat`. * * @exampleDescription * @example <ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng:repeat="name in names"> <span ng:class-odd="'ng-format-negative'" ng:class-even="'ng-input-indicator-wait'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> * * @scenario it('should check ng:class-odd and ng:class-even', function(){ expect(element('.doc-example-live li:first span').attr('className')). toMatch(/ng-format-negative/); expect(element('.doc-example-live li:last span').attr('className')). toMatch(/ng-input-indicator-wait/); }); */ angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;})); /** * @ngdoc directive * @name angular.directive.ng:show * * @description * The `ng:show` and `ng:hide` allows you to show or hide a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression if truthy then the element is * shown or hidden respectively. * * @exampleDescription * @example Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> * * @scenario it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); */ angularDirective("ng:show", function(expression, element){ return function(element){ this.$onEval(function(){ element.css($display, toBoolean(this.$eval(expression)) ? '' : $none); }, element); }; }); /** * @ngdoc directive * @name angular.directive.ng:hide * * @description * The `ng:show` and `ng:hide` allows you to show or hide a portion * of the HTML conditionally. * * @element ANY * @param {expression} expression if truthy then the element is * shown or hidden respectively. * * @exampleDescription * @example Click me: <input type="checkbox" name="checked"><br/> Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/> Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span> * * @scenario it('should check ng:show / ng:hide', function(){ expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); */ angularDirective("ng:hide", function(expression, element){ return function(element){ this.$onEval(function(){ element.css($display, toBoolean(this.$eval(expression)) ? $none : ''); }, element); }; }); /** * @ngdoc directive * @name angular.directive.ng:style * * @description * * @element ANY * @param {expression} expression to eval. * * @exampleDescription * @example * * @scenario it('should check ng:style', function(){ }); */ angularDirective("ng:style", function(expression, element){ return function(element){ var resetStyle = getStyle(element); this.$onEval(function(){ var style = this.$eval(expression) || {}, key, mergedStyle = {}; for(key in style) { if (resetStyle[key] === _undefined) resetStyle[key] = ''; mergedStyle[key] = style[key]; } for(key in resetStyle) { mergedStyle[key] = mergedStyle[key] || resetStyle[key]; } element.css(mergedStyle); }, element); }; }); function parseBindings(string) { var results = []; var lastIndex = 0; var index; while((index = string.indexOf('{{', lastIndex)) > -1) { if (lastIndex < index) results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; index = string.indexOf('}}', index); index = index < 0 ? string.length : index + 2; results.push(string.substr(lastIndex, index - lastIndex)); lastIndex = index; } if (lastIndex != string.length) results.push(string.substr(lastIndex, string.length - lastIndex)); return results.length === 0 ? [ string ] : results; } function binding(string) { var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/); return binding ? binding[1] : _null; } function hasBindings(bindings) { return bindings.length > 1 || binding(bindings[0]) !== _null; } angularTextMarkup('{{}}', function(text, textNode, parentElement) { var bindings = parseBindings(text), self = this; if (hasBindings(bindings)) { if (isLeafNode(parentElement[0])) { parentElement.attr('ng:bind-template', text); } else { var cursor = textNode, newElement; foreach(parseBindings(text), function(text){ var exp = binding(text); if (exp) { newElement = self.element('span'); newElement.attr('ng:bind', exp); } else { newElement = self.text(text); } if (msie && text.charAt(0) == ' ') { newElement = jqLite('<span>&nbsp;</span>'); var nbsp = newElement.html(); newElement.text(text.substr(1)); newElement.html(nbsp + newElement.html()); } cursor.after(newElement); cursor = newElement; }); textNode.remove(); } } }); // TODO: this should be widget not a markup angularTextMarkup('OPTION', function(text, textNode, parentElement){ if (nodeName(parentElement) == "OPTION") { var select = document.createElement('select'); select.insertBefore(parentElement[0].cloneNode(true), _null); if (!select.innerHTML.match(/<option(\s.*\s|\s)value\s*=\s*.*>.*<\/\s*option\s*>/gi)) { parentElement.attr('value', text); } } }); var NG_BIND_ATTR = 'ng:bind-attr'; var SPECIAL_ATTRS = {'ng:src': 'src', 'ng:href': 'href'}; angularAttrMarkup('{{}}', function(value, name, element){ // don't process existing attribute markup if (angularDirective(name) || angularDirective("@" + name)) return; if (msie && name == 'src') value = decodeURI(value); var bindings = parseBindings(value), bindAttr; if (hasBindings(bindings)) { element.removeAttr(name); bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}"); bindAttr[SPECIAL_ATTRS[name] || name] = value; element.attr(NG_BIND_ATTR, toJson(bindAttr)); } }); /** * @ngdoc widget * @name angular.widget.HTML * * @description * The most common widgets you will use will be in the from of the * standard HTML set. These widgets are bound using the name attribute * to an expression. In addition they can have `ng:validate`, `ng:required`, * `ng:format`, `ng:change` attribute to further control their behavior. * * @usageContent * see example below for usage * * <input type="text|checkbox|..." ... /> * <textarea ... /> * <select ...> * <option>...</option> * </select> * * @example <table style="font-size:.9em;"> <tr> <th>Name</th> <th>Format</th> <th>HTML</th> <th>UI</th> <th ng:non-bindable>{{input#}}</th> </tr> <tr> <th>text</th> <td>String</td> <td><tt>&lt;input type="text" name="input1"&gt;</tt></td> <td><input type="text" name="input1" size="4"></td> <td><tt>{{input1|json}}</tt></td> </tr> <tr> <th>textarea</th> <td>String</td> <td><tt>&lt;textarea name="input2"&gt;&lt;/textarea&gt;</tt></td> <td><textarea name="input2" cols='6'></textarea></td> <td><tt>{{input2|json}}</tt></td> </tr> <tr> <th>radio</th> <td>String</td> <td><tt> &lt;input type="radio" name="input3" value="A"&gt;<br> &lt;input type="radio" name="input3" value="B"&gt; </tt></td> <td> <input type="radio" name="input3" value="A"> <input type="radio" name="input3" value="B"> </td> <td><tt>{{input3|json}}</tt></td> </tr> <tr> <th>checkbox</th> <td>Boolean</td> <td><tt>&lt;input type="checkbox" name="input4" value="checked"&gt;</tt></td> <td><input type="checkbox" name="input4" value="checked"></td> <td><tt>{{input4|json}}</tt></td> </tr> <tr> <th>pulldown</th> <td>String</td> <td><tt> &lt;select name="input5"&gt;<br> &nbsp;&nbsp;&lt;option value="c"&gt;C&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="d"&gt;D&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input5"> <option value="c">C</option> <option value="d">D</option> </select> </td> <td><tt>{{input5|json}}</tt></td> </tr> <tr> <th>multiselect</th> <td>Array</td> <td><tt> &lt;select name="input6" multiple size="4"&gt;<br> &nbsp;&nbsp;&lt;option value="e"&gt;E&lt;/option&gt;<br> &nbsp;&nbsp;&lt;option value="f"&gt;F&lt;/option&gt;<br> &lt;/select&gt;<br> </tt></td> <td> <select name="input6" multiple size="4"> <option value="e">E</option> <option value="f">F</option> </select> </td> <td><tt>{{input6|json}}</tt></td> </tr> </table> * @scenario * it('should exercise text', function(){ * input('input1').enter('Carlos'); * expect(binding('input1')).toEqual('"Carlos"'); * }); * it('should exercise textarea', function(){ * input('input2').enter('Carlos'); * expect(binding('input2')).toEqual('"Carlos"'); * }); * it('should exercise radio', function(){ * expect(binding('input3')).toEqual('null'); * input('input3').select('A'); * expect(binding('input3')).toEqual('"A"'); * input('input3').select('B'); * expect(binding('input3')).toEqual('"B"'); * }); * it('should exercise checkbox', function(){ * expect(binding('input4')).toEqual('false'); * input('input4').check(); * expect(binding('input4')).toEqual('true'); * }); * it('should exercise pulldown', function(){ * expect(binding('input5')).toEqual('"c"'); * select('input5').option('d'); * expect(binding('input5')).toEqual('"d"'); * }); * it('should exercise multiselect', function(){ * expect(binding('input6')).toEqual('[]'); * select('input6').options('e'); * expect(binding('input6')).toEqual('["e"]'); * select('input6').options('e', 'f'); * expect(binding('input6')).toEqual('["e","f"]'); * }); */ function modelAccessor(scope, element) { var expr = element.attr('name'); if (!expr) throw "Required field 'name' not found."; return { get: function() { return scope.$eval(expr); }, set: function(value) { if (value !== _undefined) { return scope.$tryEval(expr + '=' + toJson(value), element); } } }; } function modelFormattedAccessor(scope, element) { var accessor = modelAccessor(scope, element), formatterName = element.attr('ng:format') || NOOP, formatter = angularFormatter(formatterName); if (!formatter) throw "Formatter named '" + formatterName + "' not found."; return { get: function() { return formatter.format(accessor.get()); }, set: function(value) { return accessor.set(formatter.parse(value)); } }; } function compileValidator(expr) { return parser(expr).validator()(); } function valueAccessor(scope, element) { var validatorName = element.attr('ng:validate') || NOOP, validator = compileValidator(validatorName), requiredExpr = element.attr('ng:required'), formatterName = element.attr('ng:format') || NOOP, formatter = angularFormatter(formatterName), format, parse, lastError, required, invalidWidgets = scope.$invalidWidgets || {markValid:noop, markInvalid:noop}; if (!validator) throw "Validator named '" + validatorName + "' not found."; if (!formatter) throw "Formatter named '" + formatterName + "' not found."; format = formatter.format; parse = formatter.parse; if (requiredExpr) { scope.$watch(requiredExpr, function(newValue) { required = newValue; validate(); }); } else { required = requiredExpr === ''; } element.data('$validate', validate); return { get: function(){ if (lastError) elementError(element, NG_VALIDATION_ERROR, _null); try { var value = parse(element.val()); validate(); return value; } catch (e) { lastError = e; elementError(element, NG_VALIDATION_ERROR, e); } }, set: function(value) { var oldValue = element.val(), newValue = format(value); if (oldValue != newValue) { element.val(newValue || ''); // needed for ie } validate(); } }; function validate() { var value = trim(element.val()); if (element[0].disabled || element[0].readOnly) { elementError(element, NG_VALIDATION_ERROR, _null); invalidWidgets.markValid(element); } else { var error, validateScope = inherit(scope, {$element:element}); error = required && !value ? 'Required' : (value ? validator(validateScope, value) : _null); elementError(element, NG_VALIDATION_ERROR, error); lastError = error; if (error) { invalidWidgets.markInvalid(element); } else { invalidWidgets.markValid(element); } } } } function checkedAccessor(scope, element) { var domElement = element[0], elementValue = domElement.value; return { get: function(){ return !!domElement.checked; }, set: function(value){ domElement.checked = toBoolean(value); } }; } function radioAccessor(scope, element) { var domElement = element[0]; return { get: function(){ return domElement.checked ? domElement.value : _null; }, set: function(value){ domElement.checked = value == domElement.value; } }; } function optionsAccessor(scope, element) { var options = element[0].options; return { get: function(){ var values = []; foreach(options, function(option){ if (option.selected) values.push(option.value); }); return values; }, set: function(values){ var keys = {}; foreach(values, function(value){ keys[value] = true; }); foreach(options, function(option){ option.selected = keys[option.value]; }); } }; } function noopAccessor() { return { get: noop, set: noop }; } var textWidget = inputWidget('keyup change', modelAccessor, valueAccessor, initWidgetValue()), buttonWidget = inputWidget('click', noopAccessor, noopAccessor, noop), INPUT_TYPE = { 'text': textWidget, 'textarea': textWidget, 'hidden': textWidget, 'password': textWidget, 'button': buttonWidget, 'submit': buttonWidget, 'reset': buttonWidget, 'image': buttonWidget, 'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)), 'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit), 'select-one': inputWidget('change', modelFormattedAccessor, valueAccessor, initWidgetValue(_null)), 'select-multiple': inputWidget('change', modelFormattedAccessor, optionsAccessor, initWidgetValue([])) // 'file': fileWidget??? }; function initWidgetValue(initValue) { return function (model, view) { var value = view.get(); if (!value && isDefined(initValue)) { value = copy(initValue); } if (isUndefined(model.get()) && isDefined(value)) { model.set(value); } }; } function radioInit(model, view, element) { var modelValue = model.get(), viewValue = view.get(), input = element[0]; input.checked = false; input.name = this.$id + '@' + input.name; if (isUndefined(modelValue)) { model.set(modelValue = _null); } if (modelValue == _null && viewValue !== _null) { model.set(viewValue); } view.set(modelValue); } function inputWidget(events, modelAccessor, viewAccessor, initFn) { return function(element) { var scope = this, model = modelAccessor(scope, element), view = viewAccessor(scope, element), action = element.attr('ng:change') || '', lastValue; initFn.call(scope, model, view, element); this.$eval(element.attr('ng:init')||''); // Don't register a handler if we are a button (noopAccessor) and there is no action if (action || modelAccessor !== noopAccessor) { element.bind(events, function(event){ model.set(view.get()); lastValue = model.get(); scope.$tryEval(action, element); scope.$root.$eval(); }); } function updateView(){ view.set(lastValue = model.get()); } updateView(); element.data('$update', updateView); scope.$watch(model.get, function(value){ if (lastValue !== value) { view.set(lastValue = value); } }); }; } function inputWidgetSelector(element){ this.directives(true); return INPUT_TYPE[lowercase(element[0].type)] || noop; } angularWidget('input', inputWidgetSelector); angularWidget('textarea', inputWidgetSelector); angularWidget('button', inputWidgetSelector); angularWidget('select', function(element){ this.descend(true); return inputWidgetSelector.call(this, element); }); angularWidget('option', function(){ this.descend(true); this.directives(true); return function(element) { this.$postEval(element.parent().data('$update')); }; }); /** * @ngdoc widget * @name angular.widget.ng:include * * @description * Include external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ng:include won't work for file:// access). * * @param {string} src expression evaluating to URL. * @param {Scope=} [scope=new_child_scope] expression evaluating to angular.scope * * @example * <select name="url"> * <option value="angular.filter.date.html">date filter</option> * <option value="angular.filter.html.html">html filter</option> * <option value="">(blank)</option> * </select> * <tt>url = <a href="{{url}}">{{url}}</a></tt> * <hr/> * <ng:include src="url"></ng:include> * * @scenario * it('should load date filter', function(){ * expect(element('.doc-example ng\\:include').text()).toMatch(/angular\.filter\.date/); * }); * it('should change to hmtl filter', function(){ * select('url').option('angular.filter.html.html'); * expect(element('.doc-example ng\\:include').text()).toMatch(/angular\.filter\.html/); * }); * it('should change to blank', function(){ * select('url').option('(blank)'); * expect(element('.doc-example ng\\:include').text()).toEqual(''); * }); */ angularWidget('ng:include', function(element){ var compiler = this, srcExp = element.attr("src"), scopeExp = element.attr("scope") || ''; if (element[0]['ng:compiled']) { this.descend(true); this.directives(true); } else { element[0]['ng:compiled'] = true; return extend(function(xhr, element){ var scope = this, childScope; var changeCounter = 0; var preventRecursion = false; function incrementChange(){ changeCounter++;} this.$watch(srcExp, incrementChange); this.$watch(scopeExp, incrementChange); scope.$onEval(function(){ if (childScope && !preventRecursion) { preventRecursion = true; try { childScope.$eval(); } finally { preventRecursion = false; } } }); this.$watch(function(){return changeCounter;}, function(){ var src = this.$eval(srcExp), useScope = this.$eval(scopeExp); if (src) { xhr('GET', src, function(code, response){ element.html(response); childScope = useScope || createScope(scope); compiler.compile(element)(element, childScope); childScope.$init(); }); } else { childScope = null; element.html(''); } }); }, {$inject:['$xhr.cache']}); } }); /** * @ngdoc widget * @name angular.widget.ng:switch * * @description * Conditionally change the DOM structure. * * @usageContent * <any ng:switch-when="matchValue1">...</any> * <any ng:switch-when="matchValue2">...</any> * ... * <any ng:switch-default>...</any> * * @param {*} on expression to match against <tt>ng:switch-when</tt>. * @paramDescription * On child elments add: * * * `ng:switch-when`: the case statement to match against. If match then this * case will be displayed. * * `ng:switch-default`: the default case when no other casses match. * * @example <select name="switch"> <option>settings</option> <option>home</option> <option>other</option> </select> <tt>switch={{switch}}</tt> </hr> <ng:switch on="switch" > <div ng:switch-when="settings">Settings Div</div> <span ng:switch-when="home">Home Span</span> <span ng:switch-default>default</span> </ng:switch> </code> * * @scenario * it('should start in settings', function(){ * expect(element('.doc-example ng\\:switch').text()).toEqual('Settings Div'); * }); * it('should change to home', function(){ * select('switch').option('home'); * expect(element('.doc-example ng\\:switch').text()).toEqual('Home Span'); * }); * it('should select deafault', function(){ * select('switch').option('other'); * expect(element('.doc-example ng\\:switch').text()).toEqual('default'); * }); */ var ngSwitch = angularWidget('ng:switch', function (element){ var compiler = this, watchExpr = element.attr("on"), usingExpr = (element.attr("using") || 'equals'), usingExprParams = usingExpr.split(":"), usingFn = ngSwitch[usingExprParams.shift()], changeExpr = element.attr('change') || '', cases = []; if (!usingFn) throw "Using expression '" + usingExpr + "' unknown."; if (!watchExpr) throw "Missing 'on' attribute."; eachNode(element, function(caseElement){ var when = caseElement.attr('ng:switch-when'); var switchCase = { change: changeExpr, element: caseElement, template: compiler.compile(caseElement) }; if (isString(when)) { switchCase.when = function(scope, value){ var args = [value, when]; foreach(usingExprParams, function(arg){ args.push(arg); }); return usingFn.apply(scope, args); }; cases.unshift(switchCase); } else if (isString(caseElement.attr('ng:switch-default'))) { switchCase.when = valueFn(true); cases.push(switchCase); } }); // this needs to be here for IE foreach(cases, function(_case){ _case.element.remove(); }); element.html(''); return function(element){ var scope = this, childScope; this.$watch(watchExpr, function(value){ var found = false; element.html(''); childScope = createScope(scope); foreach(cases, function(switchCase){ if (!found && switchCase.when(childScope, value)) { found = true; var caseElement = quickClone(switchCase.element); element.append(caseElement); childScope.$tryEval(switchCase.change, element); switchCase.template(caseElement, childScope); childScope.$init(); } }); }); scope.$onEval(function(){ if (childScope) childScope.$eval(); }); }; }, { equals: function(on, when) { return ''+on == when; }, route: switchRouteMatcher }); /* * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with ng:click without * changing the location or causing page reloads, e.g.: * <a href="" ng:click="model.$save()">Save</a> */ angular.widget('a', function() { this.descend(true); this.directives(true); return function(element) { if (element.attr('href') === '') { element.bind('click', function(event){ event.preventDefault(); }); } }; });var browserSingleton; angularService('$browser', function($log){ if (!browserSingleton) { browserSingleton = new Browser( window.location, jqLite(window.document), jqLite(window.document.getElementsByTagName('head')[0]), XHR, $log); browserSingleton.startPoller(50, function(delay, fn){setTimeout(delay,fn);}); browserSingleton.bind(); } return browserSingleton; }, {inject:['$log']}); extend(angular, { 'element': jqLite, 'compile': compile, 'scope': createScope, 'copy': copy, 'extend': extend, 'equals': equals, 'foreach': foreach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isArray': isArray }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {Function} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {Function} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.foreach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {Function} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialization function for the scenario runner. * * @param {angular.scenario.Runner} $scenario The runner to setup * @param {Object} config Config options */ function angularScenarioInit($scenario, config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; if (config.scenario_output) { output = config.scenario_output.split(','); } angular.foreach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $scenario); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $scenario.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $scenario.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $scenario.run(application); } /** * Iterates through list with iterator function that must call the * continueFunction to continute iterating. * * @param {Array} list list to iterate over * @param {Function} iterator Callback function(value, continueFunction) * @param {Function} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number} maxStackLines Optional. max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} Optional event type. */ function browserTrigger(element, type) { if (element && !element.nodeName) element = element[0]; if (!element) return; if (!type) { type = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change' }[element.type] || 'click'; } if (lowercase(nodeName(element)) == 'option') { element.parentNode.value = element.value; element = element.parentNode; type = 'change'; } if (msie) { switch(element.type) { case 'radio': case 'checkbox': element.checked = !element.checked; break; } element.fireEvent('on' + type); if (lowercase(element.type) == 'submit') { while(element) { if (lowercase(element.nodeName) == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } } else { var evnt = document.createEvent('MouseEvents'); evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); element.dispatchEvent(evnt); } } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keyup)/.test(type)) { return this.each(function(index, node) { browserTrigger(node, type); }); } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} name The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(name) { function contains(text, value) { return value instanceof RegExp ? value.test(text) : text && text.indexOf(value) >= 0; } var result = []; this.find('.ng-binding:visible').each(function() { var element = new _jQuery(this); if (!angular.isDefined(name) || contains(element.attr('ng:bind'), name) || contains(element.attr('ng:bind-template'), name)) { if (element.is('input, textarea')) { result.push(element.val()); } else { result.push(element.html()); } } }); return result; }; /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().attr('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Checks that a URL would return a 2xx success status code. Callback is called * with no arguments on success, or with an error on failure. * * Warning: This requires the server to be able to respond to HEAD requests * and not modify the state of your application. * * @param {string} url Url to check * @param {Function} callback function(error) that is called with result. */ angular.scenario.Application.prototype.checkUrlStatus_ = function(url, callback) { var self = this; _jQuery.ajax({ url: url, type: 'HEAD', complete: function(request) { if (request.status < 200 || request.status >= 300) { if (!request.status) { callback.call(self, 'Sandbox Error: Cannot access ' + url); } else { callback.call(self, request.status + ' ' + request.statusText); } } else { callback.call(self); } } }); }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {Function} loadFn function($window, $document) Called when frame loads. * @param {Function} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = this.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); this.executeAction(loadFn); } else { frame.css('display', 'none').attr('src', 'about:blank'); this.checkUrlStatus_(url, function(error) { if (error) { return errorFn(error); } self.context.find('#test-frames').append('<iframe>'); frame = this.getFrame_(); frame.load(function() { frame.unbind(); try { self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); }); } this.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {Function} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } var $browser = $window.angular.service.$browser(); $browser.poll(); $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, _jQuery($window.document)); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.foreach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.foreach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.foreach(this.children, function(child) { child.getSpecs(specs); }); angular.foreach(this.its, function(it) { specs.push(it); }); var only = []; angular.foreach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {Function} future callback(error, result) * @param {Function} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {Function} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {Function} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one glonal shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value; angular.foreach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; }); self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); it.steps.push(new angular.scenario.ObjectModel.Step(step.name)); }); runner.on('StepEnd', function(spec, step) { var it = self.getSpec(spec.id); if (it.getLastStep().name !== step.name) throw 'Events fired in the wrong order. Step names don\' match.'; complete(it.getLastStep()); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id); var item = it.getLastStep(); item.error = error; if (!it.status) { it.status = item.status = 'failure'; } }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id); var item = it.getLastStep(); it.status = 'error'; item.status = 'error'; item.error = error; }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec */ angular.scenario.ObjectModel.Spec = function(id, name) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.foreach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.foreach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; /** * Defines a block to execute before each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {Function} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {Function} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.foreach(this.children, function(child) { child.getSpecs(specs); }); angular.foreach(this.its, function(it) { specs.push(it); }); var only = []; angular.foreach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * Runner for scenarios. */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.foreach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.foreach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {Function} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {Function} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { return scope.$new(angular.scenario.SpecRunner); }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.scope(this); $root.application = application; this.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.foreach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.foreach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = angular.scope(runner); // Make the dsl accessible on the current chain scope.dsl = {}; angular.foreach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, specDone); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {Object} specDone An angular.scenario.Application instance * @param {Function} Callback function that is called when the spec finshes. */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {Function} behavior Behavior of the future * @param {Function} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.foreach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * wait() waits until you call resume() in the console */ angular.scenario.dsl('wait', function() { return function() { return this.addFuture('waiting for you to resume', function(done) { this.emit('InteractiveWait', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * pause(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('pause', function() { return function(time) { return this.addFuture('pause for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().location().href() the full URL of the page * browser().location().hash() the full hash in the url * browser().location().path() the full path in the url * browser().location().hashSearch() the hashSearch Object from angular * browser().location().hashPath() the hashPath string from angular */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.location = function() { var api = {}; api.href = function() { return this.addFutureAction('browser url', function($window, $document, done) { done(null, $window.location.href); }); }; api.hash = function() { return this.addFutureAction('browser url hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; api.path = function() { return this.addFutureAction('browser url path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('browser url search', function($window, $document, done) { done(null, $window.angular.scope().$location.search); }); }; api.hashSearch = function() { return this.addFutureAction('browser url hash search', function($window, $document, done) { done(null, $window.angular.scope().$location.hashSearch); }); }; api.hashPath = function() { return this.addFutureAction('browser url hash path', function($window, $document, done) { done(null, $window.angular.scope().$location.hashPath); }); }; return api; }; return function(time) { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings(name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the readio button with specified name/value */ angular.scenario.dsl('input', function() { var chain = {}; chain.enter = function(value) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements(':input[name="$1"]', this.name); input.val(value); input.trigger('change'); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements(':checkbox[name="$1"]', this.name); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements(':radio[name$="@$1"][value="$2"]', this.name, value); input.trigger('click'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings(binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var values = []; var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings()); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[name="$1"]', this.name); select.val(value); select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][name="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); elements.trigger('click'); if (href && elements[0].nodeName.toUpperCase() === 'A') { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.foreach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var futureName = "element '" + this.label + "' get " + methodName + " '" + name + "'"; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, name, value)); }); }; }); angular.foreach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var futureName = "element '" + this.label + "' " + methodName; if (angular.isDefined(value)) { futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; } return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].call(element, value)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner) { var model = new angular.scenario.ObjectModel(runner); context.append( '<div id="header">' + ' <h1><span class="angular">&lt;angular/&gt;</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractiveWait', function(spec, step) { var ui = model.getSpec(spec.id).getLastStep().ui; ui.find('.test-title'). html('waiting for you to <a href="javascript:resume()">resume</a>.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); model.getSpec(spec.id).ui = ui; }); runner.on('SpecError', function(spec, error) { var ui = model.getSpec(spec.id).ui; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { spec = model.getSpec(spec.id); spec.ui.removeClass('status-pending'); spec.ui.addClass('status-' + spec.status); spec.ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { spec.ui.find('> .test-info .test-name').addClass('closed'); spec.ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { spec = model.getSpec(spec.id); step = spec.getLastStep(); spec.ui.find('> .scrollpane .test-actions'). append('<li class="status-pending"></li>'); step.ui = spec.ui.find('> .scrollpane .test-actions li:last'); step.ui.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); step.ui.find('> .test-title').text(step.name); var scrollpane = step.ui.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = model.getSpec(spec.id).getLastStep().ui; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = model.getSpec(spec.id).getLastStep().ui; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { spec = model.getSpec(spec.id); step = spec.getLastStep(); step.ui.find('.timer-result').text(step.duration + 'ms'); step.ui.removeClass('status-pending'); step.ui.addClass('status-' + step.status); var scrollpane = spec.ui.find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.foreach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); }; /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {Function} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); }; }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner) { var model = new angular.scenario.ObjectModel(runner); runner.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner) { var model = new angular.scenario.ObjectModel(runner); var $ = function(args) {return new context.init(args);}; runner.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.foreach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.foreach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.foreach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error'); stepContext.append(error); error.text(formatException(stepContext.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner) { runner.$window.$result = new angular.scenario.ObjectModel(runner).value; }); var $scenario = new angular.scenario.Runner(window); window.onload = function() { try { if (previousOnLoad) previousOnLoad(); } catch(e) {} angularScenarioInit($scenario, angularJsConfig(document)); }; })(window, document, window.onload); document.write('<style type="text/css">@charset "UTF-8";\n\n.ng-format-negative {\n color: red;\n}\n\n.ng-exception {\n border: 2px solid #FF0000;\n font-family: "Courier New", Courier, monospace;\n font-size: smaller;\n}\n\n.ng-validation-error {\n border: 2px solid #FF0000;\n}\n\n\n/*****************\n * TIP\n *****************/\n#ng-callout {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 13px;\n font-weight: normal;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n vertical-align: baseline;\n background: transparent;\n text-decoration: none;\n}\n\n#ng-callout .ng-arrow-left{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n left:-12px;\n height:23px;\n width:10px;\n top:-3px;\n}\n\n#ng-callout .ng-arrow-right{\n background-image: url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");\n background-repeat: no-repeat;\n background-position: left top;\n position: absolute;\n z-index:101;\n height:23px;\n width:11px;\n top:-2px;\n}\n\n#ng-callout {\n position: absolute;\n z-index:100;\n border: 2px solid #CCCCCC;\n background-color: #fff;\n}\n\n#ng-callout .ng-content{\n padding:10px 10px 10px 10px;\n color:#333333;\n}\n\n#ng-callout .ng-title{\n background-color: #CCCCCC;\n text-align: left;\n padding-left: 8px;\n padding-bottom: 5px;\n padding-top: 2px;\n font-weight:bold;\n}\n\n\n/*****************\n * indicators\n *****************/\n.ng-input-indicator-wait {\n background-image: url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");\n background-position: right;\n background-repeat: no-repeat;\n}\n</style>'); document.write('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
ajax/libs/rxjs/2.3.10/rx.all.js
sinkcup/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, 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 = 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.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; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } 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; } // 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]; 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(); } } }; /** * 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 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, old; if (!shouldDispose) { 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 () { var old; if (!this.isDisposed) { this.isDisposed = true; 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) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { 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 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.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 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({ first: state, second: 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({ 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, 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({ first: state, second: 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 Error('Periodic scheduling not supported.'); } var s = state; var 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); } 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); 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; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; 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 Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (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 localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * 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 = 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); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * 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 notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { 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) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; 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() { __super__.apply(this, arguments); } 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(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { 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 TypeError('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); }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } 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; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * 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. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { 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) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * 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(); } }); }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @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 observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * 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) { isScheduler(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) { 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. * * @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 = Observable.just = function (value, scheduler) { isScheduler(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 'throwError' for browsers <IE9. * @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 = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @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 = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; 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; 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 for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), 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 (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable 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(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(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 (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.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @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.doAction = observableProto.tap = 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 (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * 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).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) { !hasValue && (hasValue = true); try { 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 () { !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); 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. * @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; } 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. * @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) { 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 () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * 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(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : 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 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 (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? 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; 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(); }); }).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; 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)); }); }; /** * 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; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, 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. * @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 (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? 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(); }); }).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 Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.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; } } 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 RangeError(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) { observer.onNext(x); 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. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * @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. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { count < len && (equal = comparer(value, second[count++])); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && 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.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; if (!!root.Set) { /** * 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 () { var source = this; return new AnonymousObservable(function (observer) { var s = new root.Set(); return source.subscribe( s.add.bind(s), observer.onError.bind(observer), function () { observer.onNext(s); observer.onCompleted(); }); }); }; } if (!!root.Map) { /** * 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) { var source = this; return new AnonymousObservable(function (observer) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { observer.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { observer.onError(e); return; } } m.set(key, element); }, observer.onError.bind(observer), function () { observer.onNext(m); observer.onCompleted(); }); }); }; } var fnString = 'function'; 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 observableToThink(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 && obj.prototype.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj.throw === fnString; } function isObject(val) { return val && val.constructor === Object; } /* * 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 = fan; if (isGenFun) { var args = slice.call(arguments), len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : error; gen = fn.apply(this, args); } else { done = done || error; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) res = slice.call(arguments, 1); if (err) { try { ret = gen.throw(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.')); } } }; /** * Takes a function with a callback and turns it into a thunk. * @param {Function} A function with a callback such as fs.readFile * @returns {Function} A function, when executed will continue the state machine. */ Rx.denodify = function (fn) { return function (){ var args = slice.call(arguments), results, called, callback; args.push(function(){ results = arguments; if (callback && !called) { called = true; cb.apply(this, results); } }); fn.apply(this, args); return function (fn){ callback = fn; if (results && !called) { called = true; fn.apply(this, results); } } } }; /** * 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. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, 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 args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } 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 args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { 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; } 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 if (Object.prototype.toString.call(el) === '[object NodeList]') { 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; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * 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) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.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); } 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 (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; 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) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); 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); } 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); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && 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. * * @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().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. * * @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 && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, 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, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(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) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(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) { return; } this.value = value; for (var i = 0, os = this.observers.slice(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 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.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; }, _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.call(this); if (this.isStopped) { return; } 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++) { var 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) { checkDisposed.call(this); if (this.isStopped) { return; } 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++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } 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++) { var 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)); 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, subject.subscribe.bind(subject)); } 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)); 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 obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } 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) { return 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; }); }; /** * 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; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { 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; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { 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); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * * @param other Observable sequence to match in addition to the current pattern. * @return Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.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 (exception) { observer.onError(exception); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ function JoinObserver(source, onError) { _super.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.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 plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(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); }); } 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. * * @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) { 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); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; if (timeShiftOrScheduler === undefined) { timeShift = timeSpan; } 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 () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { 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; }); }; /** * 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 createTimer, groupDisposable, n = 0, refCountDisposable, s, timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); createTimer = function (id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); }; s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; if (n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } if (newWindow) { createTimer(newId); } }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; 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.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) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(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); } 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) { 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 || (other = observableThrow(new Error('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); }); }; /** * 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, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { 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) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), 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. * @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); }); }; /** * 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; var subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(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); }); }; /** * 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 (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. * @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 (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(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * 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 (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; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), 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; 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))); }); }; /** * 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 (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @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 (observer) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /* * 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; }); }; /* * 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; 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 = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, 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 (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { 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 Error(argumentOutOfRange); } 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 Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { 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) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } 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)); 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.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 error. * @param {Mixed} error The Error 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 = []; } }, /** * 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) { 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 AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
ajax/libs/intl-tel-input/6.0.2/js/intlTelInput.js
CyrusSUEN/cdnjs
/* International Telephone Input v6.0.2 https://github.com/Bluefieldscom/intl-tel-input.git */ // wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPlugin.js (function(factory) { if (typeof define === "function" && define.amd) { define([ "jquery" ], function($) { factory($, window, document); }); } else { factory(jQuery, window, document); } })(function($, window, document, undefined) { "use strict"; // these vars persist through all instances of the plugin var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling defaults = { // typing digits after a valid number will be added to the extension part of the number allowExtensions: false, // automatically format the number according to the selected country autoFormat: true, // if there is just a dial code in the input: remove it on blur, and re-add it on focus autoHideDialCode: true, // add or remove input placeholder with an example number for the selected country autoPlaceholder: true, // default country defaultCountry: "", // geoIp lookup function geoIpLookup: null, // don't insert international dial codes nationalMode: true, // number type to use for placeholders numberType: "MOBILE", // display only these countries onlyCountries: [], // the countries at the top of the list. defaults to united states and united kingdom preferredCountries: [ "us", "gb" ], // specify the path to the libphonenumber script to enable validation/formatting utilsScript: "" }, keys = { UP: 38, DOWN: 40, ENTER: 13, ESC: 27, PLUS: 43, A: 65, Z: 90, ZERO: 48, NINE: 57, SPACE: 32, BSPACE: 8, TAB: 9, DEL: 46, CTRL: 17, CMD1: 91, // Chrome CMD2: 224 }, windowLoaded = false; // keep track of if the window.load event has fired as impossible to check after the fact $(window).load(function() { windowLoaded = true; }); function Plugin(element, options) { this.element = element; this.options = $.extend({}, defaults, options); this._defaults = defaults; // event namespace this.ns = "." + pluginName + id++; // Chrome, FF, Safari, IE9+ this.isGoodBrowser = Boolean(element.setSelectionRange); this.hadInitialPlaceholder = Boolean($(element).attr("placeholder")); this._name = pluginName; } Plugin.prototype = { _init: function() { // if in nationalMode, disable options relating to dial codes if (this.options.nationalMode) { this.options.autoHideDialCode = false; } // IE Mobile doesn't support the keypress event (see issue 68) which makes autoFormat impossible if (navigator.userAgent.match(/IEMobile/i)) { this.options.autoFormat = false; } // we cannot just test screen size as some smartphones/website meta tags will report desktop resolutions // Note: for some reason jasmine fucks up if you put this in the main Plugin function with the rest of these declarations // Note: to target Android Mobiles (and not Tablets), we must find "Android" and "Mobile" this.isMobile = /Android.+Mobile|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // we return these deferred objects from the _init() call so they can be watched, and then we resolve them when each specific request returns // Note: again, jasmine had a spazz when I put these in the Plugin function this.autoCountryDeferred = new $.Deferred(); this.utilsScriptDeferred = new $.Deferred(); // process all the data: onlyCountries, preferredCountries etc this._processCountryData(); // generate the markup this._generateMarkup(); // set the initial state of the input value and the selected flag this._setInitialState(); // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click this._initListeners(); // utils script, and auto country this._initRequests(); // return the deferreds return [ this.autoCountryDeferred, this.utilsScriptDeferred ]; }, /******************** * PRIVATE METHODS ********************/ // prepare all of the country data, including onlyCountries and preferredCountries options _processCountryData: function() { // set the instances country data objects this._setInstanceCountryData(); // set the preferredCountries property this._setPreferredCountries(); }, // add a country code to this.countryCodes _addCountryCode: function(iso2, dialCode, priority) { if (!(dialCode in this.countryCodes)) { this.countryCodes[dialCode] = []; } var index = priority || 0; this.countryCodes[dialCode][index] = iso2; }, // process onlyCountries array if present, and generate the countryCodes map _setInstanceCountryData: function() { var i; // process onlyCountries option if (this.options.onlyCountries.length) { // standardise case for (i = 0; i < this.options.onlyCountries.length; i++) { this.options.onlyCountries[i] = this.options.onlyCountries[i].toLowerCase(); } // build instance country array this.countries = []; for (i = 0; i < allCountries.length; i++) { if ($.inArray(allCountries[i].iso2, this.options.onlyCountries) != -1) { this.countries.push(allCountries[i]); } } } else { this.countries = allCountries; } // generate countryCodes map this.countryCodes = {}; for (i = 0; i < this.countries.length; i++) { var c = this.countries[i]; this._addCountryCode(c.iso2, c.dialCode, c.priority); // area codes if (c.areaCodes) { for (var j = 0; j < c.areaCodes.length; j++) { // full dial code is country code + dial code this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]); } } } }, // process preferred countries - iterate through the preferences, // fetching the country data for each one _setPreferredCountries: function() { this.preferredCountries = []; for (var i = 0; i < this.options.preferredCountries.length; i++) { var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true); if (countryData) { this.preferredCountries.push(countryData); } } }, // generate all of the markup for the plugin: the selected flag overlay, and the dropdown _generateMarkup: function() { // telephone input this.telInput = $(this.element); // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can easily put the plugin in an inconsistent state e.g. the wrong flag selected for the autocompleted number, which on submit could mean the wrong number is saved (esp in nationalMode) this.telInput.attr("autocomplete", "off"); // containers (mostly for positioning) this.telInput.wrap($("<div>", { "class": "intl-tel-input" })); this.flagsContainer = $("<div>", { "class": "flag-dropdown" }).insertBefore(this.telInput); // currently selected flag (displayed to left of input) var selectedFlag = $("<div>", { // make element focusable and tab naviagable tabindex: "0", "class": "selected-flag" }).appendTo(this.flagsContainer); this.selectedFlagInner = $("<div>", { "class": "iti-flag" }).appendTo(selectedFlag); // CSS triangle $("<div>", { "class": "arrow" }).appendTo(selectedFlag); // country list // mobile is just a native select element // desktop is a proper list containing: preferred countries, then divider, then all countries if (this.isMobile) { this.countryList = $("<select>", { "class": "iti-mobile-select" }).appendTo(this.flagsContainer); } else { this.countryList = $("<ul>", { "class": "country-list v-hide" }).appendTo(this.flagsContainer); if (this.preferredCountries.length && !this.isMobile) { this._appendListItems(this.preferredCountries, "preferred"); $("<li>", { "class": "divider" }).appendTo(this.countryList); } } this._appendListItems(this.countries, ""); if (!this.isMobile) { // now we can grab the dropdown height, and hide it properly this.dropdownHeight = this.countryList.outerHeight(); this.countryList.removeClass("v-hide").addClass("hide"); // this is useful in lots of places this.countryListItems = this.countryList.children(".country"); } }, // add a country <li> to the countryList <ul> container // UPDATE: if isMobile, add an <option> to the countryList <select> container _appendListItems: function(countries, className) { // we create so many DOM elements, it is faster to build a temp string // and then add everything to the DOM in one go at the end var tmp = ""; // for each country for (var i = 0; i < countries.length; i++) { var c = countries[i]; if (this.isMobile) { tmp += "<option data-dial-code='" + c.dialCode + "' value='" + c.iso2 + "'>"; tmp += c.name + " +" + c.dialCode; tmp += "</option>"; } else { // open the list item tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>"; // add the flag tmp += "<div class='flag'><div class='iti-flag " + c.iso2 + "'></div></div>"; // and the country name and dial code tmp += "<span class='country-name'>" + c.name + "</span>"; tmp += "<span class='dial-code'>+" + c.dialCode + "</span>"; // close the list item tmp += "</li>"; } } this.countryList.append(tmp); }, // set the initial state of the input value and the selected flag _setInitialState: function() { var val = this.telInput.val(); // if there is a number, and it's valid, we can go ahead and set the flag, else fall back to default if (this._getDialCode(val)) { this._updateFlagFromNumber(val, true); } else if (this.options.defaultCountry != "auto") { // check the defaultCountry option, else fall back to the first in the list if (this.options.defaultCountry) { this.options.defaultCountry = this._getCountryData(this.options.defaultCountry.toLowerCase(), false, false); } else { this.options.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0]; } this._selectFlag(this.options.defaultCountry.iso2); // if empty, insert the default dial code (this function will check !nationalMode and !autoHideDialCode) if (!val) { this._updateDialCode(this.options.defaultCountry.dialCode, false); } } // format if (val) { // this wont be run after _updateDialCode as that's only called if no val this._updateVal(val); } }, // initialise the main event listeners: input keyup, and click selected flag _initListeners: function() { var that = this; this._initKeyListeners(); // autoFormat prevents the change event from firing, so we need to check for changes between focus and blur in order to manually trigger it if (this.options.autoHideDialCode || this.options.autoFormat) { this._initFocusListeners(); } if (this.isMobile) { this.countryList.on("change" + this.ns, function(e) { that._selectListItem($(this).find("option:selected")); }); } else { // hack for input nested inside label: clicking the selected-flag to open the dropdown would then automatically trigger a 2nd click on the input which would close it again var label = this.telInput.closest("label"); if (label.length) { label.on("click" + this.ns, function(e) { // if the dropdown is closed, then focus the input, else ignore the click if (that.countryList.hasClass("hide")) { that.telInput.focus(); } else { e.preventDefault(); } }); } // toggle country dropdown on click var selectedFlag = this.selectedFlagInner.parent(); selectedFlag.on("click" + this.ns, function(e) { // only intercept this event if we're opening the dropdown // else let it bubble up to the top ("click-off-to-close" listener) // we cannot just stopPropagation as it may be needed to close another instance if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) { that._showDropdown(); } }); } // open dropdown list if currently focused this.flagsContainer.on("keydown" + that.ns, function(e) { var isDropdownHidden = that.countryList.hasClass("hide"); if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) { // prevent form from being submitted if "ENTER" was pressed e.preventDefault(); // prevent event from being handled again by document e.stopPropagation(); that._showDropdown(); } // allow navigation from dropdown to input on TAB if (e.which == keys.TAB) { that._closeDropdown(); } }); }, _initRequests: function() { var that = this; // if the user has specified the path to the utils script, fetch it on window.load if (this.options.utilsScript) { // if the plugin is being initialised after the window.load event has already been fired if (windowLoaded) { this.loadUtils(); } else { // wait until the load event so we don't block any other requests e.g. the flags image $(window).load(function() { that.loadUtils(); }); } } else { this.utilsScriptDeferred.resolve(); } if (this.options.defaultCountry == "auto") { this._loadAutoCountry(); } else { this.autoCountryDeferred.resolve(); } }, _loadAutoCountry: function() { var that = this; // check for cookie var cookieAutoCountry = $.cookie ? $.cookie("itiAutoCountry") : ""; if (cookieAutoCountry) { $.fn[pluginName].autoCountry = cookieAutoCountry; } // 3 options: // 1) already loaded (we're done) // 2) not already started loading (start) // 3) already started loading (do nothing - just wait for loading callback to fire) if ($.fn[pluginName].autoCountry) { this.autoCountryLoaded(); } else if (!$.fn[pluginName].startedLoadingAutoCountry) { // don't do this twice! $.fn[pluginName].startedLoadingAutoCountry = true; if (typeof this.options.geoIpLookup === "function") { this.options.geoIpLookup(function(countryCode) { $.fn[pluginName].autoCountry = countryCode.toLowerCase(); if ($.cookie) { $.cookie("itiAutoCountry", $.fn[pluginName].autoCountry, { path: "/" }); } // tell all instances the auto country is ready // TODO: this should just be the current instances $(".intl-tel-input input").intlTelInput("autoCountryLoaded"); }); } } }, _initKeyListeners: function() { var that = this; if (this.options.autoFormat) { // format number and update flag on keypress // use keypress event as we want to ignore all input except for a select few keys, // but we dont want to ignore the navigation keys like the arrows etc. // NOTE: no point in refactoring this to only bind these listeners on focus/blur because then you would need to have those 2 listeners running the whole time anyway... this.telInput.on("keypress" + this.ns, function(e) { // 32 is space, and after that it's all chars (not meta/nav keys) // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys // Update: also ignore if this is a metaKey e.g. FF and Safari trigger keypress on the v of Ctrl+v // Update: also ignore if ctrlKey (FF on Windows/Ubuntu) // Update: also check that we have utils before we do any autoFormat stuff if (e.which >= keys.SPACE && !e.ctrlKey && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) { e.preventDefault(); // allowed keys are just numeric keys and plus // we must allow plus for the case where the user does select-all and then hits plus to start typing a new number. we could refine this logic to first check that the selection contains a plus, but that wont work in old browsers, and I think it's overkill anyway var isAllowedKey = e.which >= keys.ZERO && e.which <= keys.NINE || e.which == keys.PLUS, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, max = that.telInput.attr("maxlength"), val = that.telInput.val(), // assumes that if max exists, it is >0 isBelowMax = max ? val.length < max : true; // first: ensure we dont go over maxlength. we must do this here to prevent adding digits in the middle of the number // still reformat even if not an allowed key as they could by typing a formatting char, but ignore if there's a selection as doesn't make sense to replace selection with illegal char and then immediately remove it if (isBelowMax && (isAllowedKey || noSelection)) { var newChar = isAllowedKey ? String.fromCharCode(e.which) : null; that._handleInputKey(newChar, true, isAllowedKey); // if something has changed, trigger the input event (which was otherwised squashed by the preventDefault) if (val != that.telInput.val()) { that.telInput.trigger("input"); } } if (!isAllowedKey) { that._handleInvalidKey(); } } }); } // handle cut/paste event (now supported in all major browsers) this.telInput.on("cut" + this.ns + " paste" + this.ns, function() { // hack because "paste" event is fired before input is updated setTimeout(function() { if (that.options.autoFormat && window.intlTelInputUtils) { var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length; that._handleInputKey(null, cursorAtEnd); that._ensurePlus(); } else { // if no autoFormat, just update flag that._updateFlagFromNumber(that.telInput.val()); } }); }); // handle keyup event // if autoFormat enabled: we use keyup to catch delete events (after the fact) // if no autoFormat, this is used to update the flag this.telInput.on("keyup" + this.ns, function(e) { // the "enter" key event from selecting a dropdown item is triggered here on the input, because the document.keydown handler that initially handles that event triggers a focus on the input, and so the keyup for that same key event gets triggered here. weird, but just make sure we dont bother doing any re-formatting in this case (we've already done preventDefault in the keydown handler, so it wont actually submit the form or anything). // ALSO: ignore keyup if readonly if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) { // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length; if (!that.telInput.val()) { // if they just cleared the input, update the flag to the default that._updateFlagFromNumber(""); } else if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE) { // if delete in the middle: reformat with no suffix (no need to reformat if delete at end) // if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature) // important to remember never to add suffix on any delete key as can fuck up in ie8 so you can never delete a formatting char at the end that._handleInputKey(); } that._ensurePlus(); } else { // if no autoFormat, just update flag that._updateFlagFromNumber(that.telInput.val()); } }); }, // prevent deleting the plus (if not in nationalMode) _ensurePlus: function() { if (!this.options.nationalMode) { var val = this.telInput.val(), input = this.telInput[0]; if (val.charAt(0) != "+") { // newCursorPos is current pos + 1 to account for the plus we are about to add var newCursorPos = this.isGoodBrowser ? input.selectionStart + 1 : 0; this.telInput.val("+" + val); if (this.isGoodBrowser) { input.setSelectionRange(newCursorPos, newCursorPos); } } } }, // alert the user to an invalid key event _handleInvalidKey: function() { var that = this; this.telInput.trigger("invalidkey").addClass("iti-invalid-key"); setTimeout(function() { that.telInput.removeClass("iti-invalid-key"); }, 100); }, // when autoFormat is enabled: handle various key events on the input: // 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position // 2) reformatting on backspace/delete // 3) cut/paste event _handleInputKey: function(newNumericChar, addSuffix, isAllowedKey) { var val = this.telInput.val(), cleanBefore = this._getClean(val), originalLeftChars, // raw DOM element input = this.telInput[0], digitsOnRight = 0; if (this.isGoodBrowser) { // cursor strategy: maintain the number of digits on the right. we use the right instead of the left so that A) we dont have to account for the new digit (or multiple digits if paste event), and B) we're always on the right side of formatting suffixes digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd); // if handling a new number character: insert it in the right place if (newNumericChar) { // replace any selection they may have made with the new char val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length); } else { // here we're not handling a new char, we're just doing a re-format (e.g. on delete/backspace/paste, after the fact), but we still need to maintain the cursor position. so make note of the char on the left, and then after the re-format, we'll count in the same number of digits from the right, and then keep going through any formatting chars until we hit the same left char that we had before. // UPDATE: now have to store 2 chars as extensions formatting contains 2 spaces so you need to be able to distinguish originalLeftChars = val.substr(input.selectionStart - 2, 2); } } else if (newNumericChar) { val += newNumericChar; } // update the number and flag this.setNumber(val, null, addSuffix, true, isAllowedKey); // update the cursor position if (this.isGoodBrowser) { var newCursor; val = this.telInput.val(); // if it was at the end, keep it there if (!digitsOnRight) { newCursor = val.length; } else { // else count in the same number of digits from the right newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight); // but if delete/paste etc, keep going left until hit the same left char as before if (!newNumericChar) { newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChars); } } // set the new cursor input.setSelectionRange(newCursor, newCursor); } }, // we start from the position in guessCursor, and work our way left until we hit the originalLeftChars or a number to make sure that after reformatting the cursor has the same char on the left in the case of a delete etc _getCursorFromLeftChar: function(val, guessCursor, originalLeftChars) { for (var i = guessCursor; i > 0; i--) { var leftChar = val.charAt(i - 1); if ($.isNumeric(leftChar) || val.substr(i - 2, 2) == originalLeftChars) { return i; } } return 0; }, // after a reformat we need to make sure there are still the same number of digits to the right of the cursor _getCursorFromDigitsOnRight: function(val, digitsOnRight) { for (var i = val.length - 1; i >= 0; i--) { if ($.isNumeric(val.charAt(i))) { if (--digitsOnRight === 0) { return i; } } } return 0; }, // get the number of numeric digits to the right of the cursor so we can reposition the cursor correctly after the reformat has happened _getDigitsOnRight: function(val, selectionEnd) { var digitsOnRight = 0; for (var i = selectionEnd; i < val.length; i++) { if ($.isNumeric(val.charAt(i))) { digitsOnRight++; } } return digitsOnRight; }, // listen for focus and blur _initFocusListeners: function() { var that = this; if (this.options.autoHideDialCode) { // mousedown decides where the cursor goes, so if we're focusing we must preventDefault as we'll be inserting the dial code, and we want the cursor to be at the end no matter where they click this.telInput.on("mousedown" + this.ns, function(e) { if (!that.telInput.is(":focus") && !that.telInput.val()) { e.preventDefault(); // but this also cancels the focus, so we must trigger that manually that.telInput.focus(); } }); } this.telInput.on("focus" + this.ns, function(e) { var value = that.telInput.val(); // save this to compare on blur that.telInput.data("focusVal", value); // on focus: if empty, insert the dial code for the currently selected flag if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) { that._updateVal("+" + that.selectedCountryData.dialCode, null, true); // after auto-inserting a dial code, if the first key they hit is '+' then assume they are entering a new number, so remove the dial code. use keypress instead of keydown because keydown gets triggered for the shift key (required to hit the + key), and instead of keyup because that shows the new '+' before removing the old one that.telInput.one("keypress.plus" + that.ns, function(e) { if (e.which == keys.PLUS) { // if autoFormat is enabled, this key event will have already have been handled by another keypress listener (hence we need to add the "+"). if disabled, it will be handled after this by a keyup listener (hence no need to add the "+"). var newVal = that.options.autoFormat && window.intlTelInputUtils ? "+" : ""; that.telInput.val(newVal); } }); // after tabbing in, make sure the cursor is at the end we must use setTimeout to get outside of the focus handler as it seems the selection happens after that setTimeout(function() { var input = that.telInput[0]; if (that.isGoodBrowser) { var len = that.telInput.val().length; input.setSelectionRange(len, len); } }); } }); this.telInput.on("blur" + this.ns, function() { if (that.options.autoHideDialCode) { // on blur: if just a dial code then remove it var value = that.telInput.val(), startsPlus = value.charAt(0) == "+"; if (startsPlus) { var numeric = that._getNumeric(value); // if just a plus, or if just a dial code if (!numeric || that.selectedCountryData.dialCode == numeric) { that.telInput.val(""); } } // remove the keypress listener we added on focus that.telInput.off("keypress.plus" + that.ns); } // if autoFormat, we must manually trigger change event if value has changed if (that.options.autoFormat && window.intlTelInputUtils && that.telInput.val() != that.telInput.data("focusVal")) { that.telInput.trigger("change"); } }); }, // extract the numeric digits from the given string _getNumeric: function(s) { return s.replace(/\D/g, ""); }, _getClean: function(s) { var prefix = s.charAt(0) == "+" ? "+" : ""; return prefix + this._getNumeric(s); }, // show the dropdown _showDropdown: function() { this._setDropdownPosition(); // update highlighting and scroll to active list item var activeListItem = this.countryList.children(".active"); if (activeListItem.length) { this._highlightListItem(activeListItem); } // show it this.countryList.removeClass("hide"); if (activeListItem.length) { this._scrollTo(activeListItem); } // bind all the dropdown-related listeners: mouseover, click, click-off, keydown this._bindDropdownListeners(); // update the arrow this.selectedFlagInner.children(".arrow").addClass("up"); }, // decide where to position dropdown (depends on position within viewport, and scroll) _setDropdownPosition: function() { var inputTop = this.telInput.offset().top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom) dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop; // dropdownHeight - 1 for border var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : ""; this.countryList.css("top", cssTop); }, // we only bind dropdown listeners when the dropdown is open _bindDropdownListeners: function() { var that = this; // when mouse over a list item, just highlight that one // we add the class "highlight", so if they hit "enter" we know which one to select this.countryList.on("mouseover" + this.ns, ".country", function(e) { that._highlightListItem($(this)); }); // listen for country selection this.countryList.on("click" + this.ns, ".country", function(e) { that._selectListItem($(this)); }); // click off to close // (except when this initial opening click is bubbling up) // we cannot just stopPropagation as it may be needed to close another instance var isOpening = true; $("html").on("click" + this.ns, function(e) { if (!isOpening) { that._closeDropdown(); } isOpening = false; }); // listen for up/down scrolling, enter to select, or letters to jump to country name. // use keydown as keypress doesn't fire for non-char keys and we want to catch if they // just hit down and hold it to scroll down (no keyup event). // listen on the document because that's where key events are triggered if no input has focus var query = "", queryTimer = null; $(document).on("keydown" + this.ns, function(e) { // prevent down key from scrolling the whole page, // and enter key from submitting a form etc e.preventDefault(); if (e.which == keys.UP || e.which == keys.DOWN) { // up and down to navigate that._handleUpDownKey(e.which); } else if (e.which == keys.ENTER) { // enter to select that._handleEnterKey(); } else if (e.which == keys.ESC) { // esc to close that._closeDropdown(); } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) { // upper case letters (note: keyup/keydown only return upper case letters) // jump to countries that start with the query string if (queryTimer) { clearTimeout(queryTimer); } query += String.fromCharCode(e.which); that._searchForCountry(query); // if the timer hits 1 second, reset the query queryTimer = setTimeout(function() { query = ""; }, 1e3); } }); }, // highlight the next/prev item in the list (and ensure it is visible) _handleUpDownKey: function(key) { var current = this.countryList.children(".highlight").first(); var next = key == keys.UP ? current.prev() : current.next(); if (next.length) { // skip the divider if (next.hasClass("divider")) { next = key == keys.UP ? next.prev() : next.next(); } this._highlightListItem(next); this._scrollTo(next); } }, // select the currently highlighted item _handleEnterKey: function() { var currentCountry = this.countryList.children(".highlight").first(); if (currentCountry.length) { this._selectListItem(currentCountry); } }, // find the first list item whose name starts with the query string _searchForCountry: function(query) { for (var i = 0; i < this.countries.length; i++) { if (this._startsWith(this.countries[i].name, query)) { var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred"); // update highlighting and scroll this._highlightListItem(listItem); this._scrollTo(listItem, true); break; } } }, // check if (uppercase) string a starts with string b _startsWith: function(a, b) { return a.substr(0, b.length).toUpperCase() == b; }, // update the input's value to the given val // if autoFormat=true, format it first according to the country-specific formatting rules // Note: preventConversion will be false (i.e. we allow conversion) on init and when dev calls public method setNumber _updateVal: function(val, format, addSuffix, preventConversion, isAllowedKey) { var formatted; if (this.options.autoFormat && window.intlTelInputUtils && this.selectedCountryData) { if (typeof format == "number" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) { // if user specified a format, and it's a valid number, then format it accordingly formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, format); } else if (!preventConversion && this.options.nationalMode && val.charAt(0) == "+" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) { // if nationalMode and we have a valid intl number, convert it to ntl formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, intlTelInputUtils.numberFormat.NATIONAL); } else { // else do the regular AsYouType formatting formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.allowExtensions, isAllowedKey); } // ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events var max = this.telInput.attr("maxlength"); if (max && formatted.length > max) { formatted = formatted.substr(0, max); } } else { // no autoFormat, so just insert the original value formatted = val; } this.telInput.val(formatted); }, // check if need to select a new flag based on the given number _updateFlagFromNumber: function(number, updateDefault) { // if we're in nationalMode and we're on US/Canada, make sure the number starts with a +1 so _getDialCode will be able to extract the area code // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag from the number), that means we're initialising the plugin with a number that already has a dial code, so fine to ignore this bit if (number && this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") { if (number.charAt(0) != "1") { number = "1" + number; } number = "+" + number; } // try and extract valid dial code from input var dialCode = this._getDialCode(number), countryCode = null; if (dialCode) { // check if one of the matching countries is already selected var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1; // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list if (!alreadySelected || this._isUnknownNanp(number, dialCode)) { // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index for (var j = 0; j < countryCodes.length; j++) { if (countryCodes[j]) { countryCode = countryCodes[j]; break; } } } } else if (number.charAt(0) == "+" && this._getNumeric(number).length) { // invalid dial code, so empty // Note: use getNumeric here because the number has not been formatted yet, so could contain bad shit countryCode = ""; } else if (!number || number == "+") { // empty, or just a plus, so default countryCode = this.options.defaultCountry.iso2; } if (countryCode !== null) { this._selectFlag(countryCode, updateDefault); } }, // check if the given number contains an unknown area code from the North American Numbering Plan i.e. the only dialCode that could be extracted was +1 but the actual number's length is >=4 _isUnknownNanp: function(number, dialCode) { return dialCode == "+1" && this._getNumeric(number).length >= 4; }, // remove highlighting from other list items and highlight the given item _highlightListItem: function(listItem) { this.countryListItems.removeClass("highlight"); listItem.addClass("highlight"); }, // find the country data for the given country code // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) { var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries; for (var i = 0; i < countryList.length; i++) { if (countryList[i].iso2 == countryCode) { return countryList[i]; } } if (allowFail) { return null; } else { throw new Error("No country data for '" + countryCode + "'"); } }, // select the given flag, update the placeholder and the active list item _selectFlag: function(countryCode, updateDefault) { // do this first as it will throw an error and stop if countryCode is invalid this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {}; // update the "defaultCountry" - we only need the iso2 from now on, so just store that if (updateDefault && this.selectedCountryData.iso2) { // can't just make this equal to selectedCountryData as would be a ref to that object this.options.defaultCountry = { iso2: this.selectedCountryData.iso2 }; } this.selectedFlagInner.attr("class", "iti-flag " + countryCode); // update the selected country's title attribute var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown"; this.selectedFlagInner.parent().attr("title", title); // and the input's placeholder this._updatePlaceholder(); if (this.isMobile) { this.countryList.val(countryCode); } else { // update the active list item this.countryListItems.removeClass("active"); if (countryCode) { this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active"); } } }, // update the input placeholder to an example number from the currently selected country _updatePlaceholder: function() { if (window.intlTelInputUtils && !this.hadInitialPlaceholder && this.options.autoPlaceholder && this.selectedCountryData) { var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = iso2 ? intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType) : ""; this.telInput.attr("placeholder", placeholder); } }, // called when the user selects a list item from the dropdown _selectListItem: function(listItem) { var countryCodeAttr = this.isMobile ? "value" : "data-country-code"; // update selected flag and active list item this._selectFlag(listItem.attr(countryCodeAttr), true); if (!this.isMobile) { this._closeDropdown(); } this._updateDialCode(listItem.attr("data-dial-code"), true); // always fire the change event as even if nationalMode=true (and we haven't updated the input val), the system as a whole has still changed - see country-sync example. think of it as making a selection from a select element. this.telInput.trigger("change"); // focus the input this.telInput.focus(); // fix for FF and IE11 (with nationalMode=false i.e. auto inserting dial code), who try to put the cursor at the beginning the first time if (this.isGoodBrowser) { var len = this.telInput.val().length; this.telInput[0].setSelectionRange(len, len); } }, // close the dropdown and unbind any listeners _closeDropdown: function() { this.countryList.addClass("hide"); // update the arrow this.selectedFlagInner.children(".arrow").removeClass("up"); // unbind key events $(document).off(this.ns); // unbind click-off-to-close $("html").off(this.ns); // unbind hover and click listeners this.countryList.off(this.ns); }, // check if an element is visible within it's container, else scroll until it is _scrollTo: function(element, middle) { var container = this.countryList, containerHeight = container.height(), containerTop = container.offset().top, containerBottom = containerTop + containerHeight, elementHeight = element.outerHeight(), elementTop = element.offset().top, elementBottom = elementTop + elementHeight, newScrollTop = elementTop - containerTop + container.scrollTop(), middleOffset = containerHeight / 2 - elementHeight / 2; if (elementTop < containerTop) { // scroll up if (middle) { newScrollTop -= middleOffset; } container.scrollTop(newScrollTop); } else if (elementBottom > containerBottom) { // scroll down if (middle) { newScrollTop += middleOffset; } var heightDifference = containerHeight - elementHeight; container.scrollTop(newScrollTop - heightDifference); } }, // replace any existing dial code with the new one (if not in nationalMode) // also we need to know if we're focusing for a couple of reasons e.g. if so, we want to add any formatting suffix, also if the input is empty and we're not in nationalMode, then we want to insert the dial code _updateDialCode: function(newDialCode, focusing) { var inputVal = this.telInput.val(), newNumber; // save having to pass this every time newDialCode = "+" + newDialCode; if (this.options.nationalMode && inputVal.charAt(0) != "+") { // if nationalMode, we just want to re-format newNumber = inputVal; } else if (inputVal) { // if the previous number contained a valid dial code, replace it // (if more than just a plus character) var prevDialCode = this._getDialCode(inputVal); if (prevDialCode.length > 1) { newNumber = inputVal.replace(prevDialCode, newDialCode); } else { // if the previous number didn't contain a dial code, we should persist it var existingNumber = inputVal.charAt(0) != "+" ? $.trim(inputVal) : ""; newNumber = newDialCode + existingNumber; } } else { newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : ""; } this._updateVal(newNumber, null, focusing); }, // try and extract a valid international dial code from a full telephone number // Note: returns the raw string inc plus character and any whitespace/dots etc _getDialCode: function(number) { var dialCode = ""; // only interested in international numbers (starting with a plus) if (number.charAt(0) == "+") { var numericChars = ""; // iterate over chars for (var i = 0; i < number.length; i++) { var c = number.charAt(i); // if char is number if ($.isNumeric(c)) { numericChars += c; // if current numericChars make a valid dial code if (this.countryCodes[numericChars]) { // store the actual raw string (useful for matching later) dialCode = number.substr(0, i + 1); } // longest dial code is 4 chars if (numericChars.length == 4) { break; } } } } return dialCode; }, /******************** * PUBLIC METHODS ********************/ // this is called when the geoip call returns autoCountryLoaded: function() { if (this.options.defaultCountry == "auto") { this.options.defaultCountry = $.fn[pluginName].autoCountry; this._setInitialState(); this.autoCountryDeferred.resolve(); } }, // remove plugin destroy: function() { if (!this.isMobile) { // make sure the dropdown is closed (and unbind listeners) this._closeDropdown(); } // key events, and focus/blur events if autoHideDialCode=true this.telInput.off(this.ns); if (this.isMobile) { // change event on select country this.countryList.off(this.ns); } else { // click event to open dropdown this.selectedFlagInner.parent().off(this.ns); // label click hack this.telInput.closest("label").off(this.ns); } // remove markup var container = this.telInput.parent(); container.before(this.telInput).remove(); }, // extract the phone number extension if present getExtension: function() { return this.telInput.val().split(" ext. ")[1] || ""; }, // format the number to the given type getNumber: function(type) { if (window.intlTelInputUtils) { return intlTelInputUtils.formatNumberByType(this.telInput.val(), this.selectedCountryData.iso2, type); } return ""; }, // get the type of the entered number e.g. landline/mobile getNumberType: function() { if (window.intlTelInputUtils) { return intlTelInputUtils.getNumberType(this.telInput.val(), this.selectedCountryData.iso2); } return -99; }, // get the country data for the currently selected flag getSelectedCountryData: function() { // if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense return this.selectedCountryData || {}; }, // get the validation error getValidationError: function() { if (window.intlTelInputUtils) { return intlTelInputUtils.getValidationError(this.telInput.val(), this.selectedCountryData.iso2); } return -99; }, // validate the input val - assumes the global function isValidNumber (from utilsScript) isValidNumber: function() { var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : ""; if (window.intlTelInputUtils) { return intlTelInputUtils.isValidNumber(val, countryCode); } return false; }, // load the utils script loadUtils: function(path) { var that = this; var utilsScript = path || this.options.utilsScript; if (!$.fn[pluginName].loadedUtilsScript && utilsScript) { // don't do this twice! (dont just check if the global intlTelInputUtils exists as if init plugin multiple times in quick succession, it may not have finished loading yet) $.fn[pluginName].loadedUtilsScript = true; // dont use $.getScript as it prevents caching $.ajax({ url: utilsScript, success: function() { // tell all instances the utils are ready $(".intl-tel-input input").intlTelInput("utilsLoaded"); }, complete: function() { that.utilsScriptDeferred.resolve(); }, dataType: "script", cache: true }); } else { this.utilsScriptDeferred.resolve(); } }, // update the selected flag, and update the input val accordingly selectCountry: function(countryCode) { countryCode = countryCode.toLowerCase(); // check if already selected if (!this.selectedFlagInner.hasClass(countryCode)) { this._selectFlag(countryCode, true); this._updateDialCode(this.selectedCountryData.dialCode, false); } }, // set the input value and update the flag setNumber: function(number, format, addSuffix, preventConversion, isAllowedKey) { // ensure starts with plus if (!this.options.nationalMode && number.charAt(0) != "+") { number = "+" + number; } // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it this._updateFlagFromNumber(number); this._updateVal(number, format, addSuffix, preventConversion, isAllowedKey); }, // this is called when the utils are ready utilsLoaded: function() { // if autoFormat is enabled and there's an initial value in the input, then format it if (this.options.autoFormat && this.telInput.val()) { this._updateVal(this.telInput.val()); } this._updatePlaceholder(); } }; // adapted to allow public functions // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate $.fn[pluginName] = function(options) { var args = arguments; // Is the first parameter an object (options), or was omitted, // instantiate a new instance of the plugin. if (options === undefined || typeof options === "object") { var deferreds = []; this.each(function() { if (!$.data(this, "plugin_" + pluginName)) { var instance = new Plugin(this, options); var instanceDeferreds = instance._init(); // we now have 2 deffereds: 1 for auto country, 1 for utils script deferreds.push(instanceDeferreds[0]); deferreds.push(instanceDeferreds[1]); $.data(this, "plugin_" + pluginName, instance); } }); // return the promise from the "master" deferred object that tracks all the others return $.when.apply(null, deferreds); } else if (typeof options === "string" && options[0] !== "_") { // If the first parameter is a string and it doesn't start // with an underscore or "contains" the `init`-function, // treat this as a call to a public method. // Cache the method call to make it possible to return a value var returns; this.each(function() { var instance = $.data(this, "plugin_" + pluginName); // Tests that there's already a plugin-instance // and checks that the requested public method exists if (instance instanceof Plugin && typeof instance[options] === "function") { // Call the method of our plugin instance, // and pass it the supplied arguments. returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1)); } // Allow instances to be destroyed via the 'destroy' method if (options === "destroy") { $.data(this, "plugin_" + pluginName, null); } }); // If the earlier cached method gives a value back return the value, // otherwise return this to preserve chainability. return returns !== undefined ? returns : this; } }; /******************** * STATIC METHODS ********************/ // get the country data object $.fn[pluginName].getCountryData = function() { return allCountries; }; // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers" // jshint -W100 // Array of country objects for the flag dropdown. // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code. // Originally from https://github.com/mledoze/countries // then modified using the following JavaScript (NOW OUT OF DATE): /* var result = []; _.each(countries, function(c) { // ignore countries without a dial code if (c.callingCode[0].length) { result.push({ // var locals contains country names with localised versions in brackets n: _.findWhere(locals, { countryCode: c.cca2 }).name, i: c.cca2.toLowerCase(), d: c.callingCode[0] }); } }); JSON.stringify(result); */ // then with a couple of manual re-arrangements to be alphabetical // then changed Kazakhstan from +76 to +7 // and Vatican City from +379 to +39 (see issue 50) // and Caribean Netherlands from +5997 to +599 // and Curacao from +5999 to +599 // Removed: Åland Islands, Christmas Island, Cocos Islands, Guernsey, Isle of Man, Jersey, Kosovo, Mayotte, Pitcairn Islands, South Georgia, Svalbard, Western Sahara // Update: converted objects to arrays to save bytes! // Update: added "priority" for countries with the same dialCode as others // Update: added array of area codes for countries with the same dialCode as others // So each country array has the following information: // [ // Country name, // iso2 code, // International dial code, // Order (if >1 country with same dial code), // Area codes (if >1 country with same dial code) // ] var allCountries = [ [ "Afghanistan (‫افغانستان‬‎)", "af", "93" ], [ "Albania (Shqipëri)", "al", "355" ], [ "Algeria (‫الجزائر‬‎)", "dz", "213" ], [ "American Samoa", "as", "1684" ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1264" ], [ "Antigua and Barbuda", "ag", "1268" ], [ "Argentina", "ar", "54" ], [ "Armenia (Հայաստան)", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Australia", "au", "61" ], [ "Austria (Österreich)", "at", "43" ], [ "Azerbaijan (Azərbaycan)", "az", "994" ], [ "Bahamas", "bs", "1242" ], [ "Bahrain (‫البحرين‬‎)", "bh", "973" ], [ "Bangladesh (বাংলাদেশ)", "bd", "880" ], [ "Barbados", "bb", "1246" ], [ "Belarus (Беларусь)", "by", "375" ], [ "Belgium (België)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (Bénin)", "bj", "229" ], [ "Bermuda", "bm", "1441" ], [ "Bhutan (འབྲུག)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1284" ], [ "Brunei", "bn", "673" ], [ "Bulgaria (България)", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi (Uburundi)", "bi", "257" ], [ "Cambodia (កម្ពុជា)", "kh", "855" ], [ "Cameroon (Cameroun)", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (中国)", "cn", "86" ], [ "Colombia", "co", "57" ], [ "Comoros (‫جزر القمر‬‎)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (‫مصر‬‎)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358" ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "is", "354" ], [ "India (भारत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (‫ایران‬‎)", "ir", "98" ], [ "Iraq (‫العراق‬‎)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Israel (‫ישראל‬‎)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (日本)", "jp", "81" ], [ "Jordan (‫الأردن‬‎)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kuwait (‫الكويت‬‎)", "kw", "965" ], [ "Kyrgyzstan (Кыргызстан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (‫لبنان‬‎)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (‫ليبيا‬‎)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "Macedonia (FYROM) (Македонија)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (‫موريتانيا‬‎)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (‫المغرب‬‎)", "ma", "212" ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (조선 민주주의 인민 공화국)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47" ], [ "Oman (‫عُمان‬‎)", "om", "968" ], [ "Pakistan (‫پاکستان‬‎)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (‫فلسطين‬‎)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (‫قطر‬‎)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262" ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy (Saint-Barthélemy)", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (‫جنوب السودان‬‎)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94" ], [ "Sudan (‫السودان‬‎)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (‫سوريا‬‎)", "sy", "963" ], [ "Taiwan (台灣)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (ไทย)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (‫تونس‬‎)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (Україна)", "ua", "380" ], [ "United Arab Emirates (‫الإمارات العربية المتحدة‬‎)", "ae", "971" ], [ "United Kingdom", "gb", "44" ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Yemen (‫اليمن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ]; // loop over all of the countries above for (var i = 0; i < allCountries.length; i++) { var c = allCountries[i]; allCountries[i] = { name: c[0], iso2: c[1], dialCode: c[2], priority: c[3] || 0, areaCodes: c[4] || null }; } });
src/shared/components/imageCard/imageCard.js
sethbergman/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './imageCard.css'; const ImageCard = ({ buttonText, cardText, image, link, title }) => ( <div className={styles.imageCard}> <img className={styles.cardImage} src={image} alt={title} /> <div className={styles.cardText}> <h6>{title}</h6> <p>{cardText}</p> {link && <LinkButton text={buttonText} link={link} isExternal />} </div> </div> ); ImageCard.propTypes = { image: PropTypes.string.isRequired, title: PropTypes.string.isRequired, cardText: PropTypes.string.isRequired, buttonText: PropTypes.string, link: PropTypes.string, }; ImageCard.defaultProps = { link: null, buttonText: null, }; export default ImageCard;
src/components/settlement/header/Header.js
HuZai/react_settlement
/** * Created by zhengHu on 16-10-8. */ import React from 'react'; class Header extends React.Component { constructor(props) { super(props); this.state={data:{test:'test'}}; // this.props.location.state location.state; } text(){ this.context.router.replace( {pathname: '/', query: { modal: true }, state: this.state } ) } goOut(){ window.location.href="http://m.secoo.com/"; } back(){ this.props.history.goBack() } handleClick(){ this.context.router.goBack(); } render() { return ( <header className="header"> <div className="back" onClick={()=>this.handleClick()}> <div><span className="secoo_icon_back"></span></div> </div> <div className="content"><div>{this.props.data.title}</div></div> <div className="more" onClick={this.props.rightClick}><div><span>{this.props.data.btnDes}</span></div></div> </header> ); } } Header.defaultProps = { }; Header.contextTypes = { router: React.PropTypes.object.isRequired }; export default Header;
src/components/vis/CalendarChart.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { Chart } from 'react-google-charts'; import { getBrandDarkColor } from '../../styles/colors'; const CalendarChart = (props) => { const numYears = 3; const height = (((props.cellSize * 7) + 20) * numYears) + 40; // based on how the width renders each year return ( <div className="calendar-chart"> <Chart chartType="Calendar" data={[['date', 'count'], ...props.data]} graph_id={props.domId} width="100%" height={`${height}px`} legend_toggle options={{ calendar: { cellSize: props.cellSize, colorAxis: { minValue: 0, colors: ['#FFFFFF', getBrandDarkColor()], }, }, }} /> </div> ); }; CalendarChart.propTypes = { domId: PropTypes.string.isRequired, data: PropTypes.array.isRequired, // an array of [jsDateObj, countInteger] cellSize: PropTypes.number.isRequired, }; export default CalendarChart;
examples/with-koa/src/client.js
jaredpalmer/react-production-starter
import App from './App'; import BrowserRouter from 'react-router-dom/BrowserRouter'; import React from 'react'; import { hydrate } from 'react-dom'; hydrate( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
packages/demos/todomvc/src/components/App/index.js
yusufsafak/cerebral
import React from 'react' import { connect } from 'cerebral/react' import NewTodoForm from '../NewTodo' import TodosList from '../List' import TodosFooter from '../Footer' import computedCounts from '../../computed/counts' export default connect( { counts: computedCounts, }, function App({ counts }) { return ( <div id="todoapp-wrapper"> <section className="todoapp"> <header className="header"> <h1>todos</h1> <NewTodoForm /> </header> {!!counts.visible && <TodosList />} {!!counts.total && <TodosFooter />} </section> <footer className="info"> <p> Double-click to edit a todo </p> <p> Credits: <a href="http://christianalfoni.com">Christian Alfoni</a>, </p> <p> Part of <a href="http://todomvc.com">TodoMVC</a> </p> </footer> </div> ) } )
src/svg-icons/image/image.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageImage = (props) => ( <SvgIcon {...props}> <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/> </SvgIcon> ); ImageImage = pure(ImageImage); ImageImage.displayName = 'ImageImage'; ImageImage.muiName = 'SvgIcon'; export default ImageImage;
ajax/libs/bootstrap.native/2.0.6/bootstrap-native-v4.js
sufuf3/cdnjs
// Native Javascript for Bootstrap 4 v2.0.6 | © dnp_theme | MIT-License (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD support: define([], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like: module.exports = factory(); } else { // Browser globals (root is window) var bsn = factory(); root.Alert = bsn.Alert; root.Button = bsn.Button; root.Carousel = bsn.Carousel; root.Collapse = bsn.Collapse; root.Dropdown = bsn.Dropdown; root.Modal = bsn.Modal; root.Popover = bsn.Popover; root.ScrollSpy = bsn.ScrollSpy; root.Tab = bsn.Tab; root.Tooltip = bsn.Tooltip; } }(this, function () { /* Native Javascript for Bootstrap 4 | Internal Utility Functions ----------------------------------------------------------------*/ // globals var globalObject = typeof global !== 'undefined' ? global : this||window, doc = document.documentElement, body = document.body, // function toggle attributes dataToggle = 'data-toggle', dataDismiss = 'data-dismiss', dataSpy = 'data-spy', dataRide = 'data-ride', // components stringAlert = 'Alert', stringButton = 'Button', stringCarousel = 'Carousel', stringCollapse = 'Collapse', stringDropdown = 'Dropdown', stringModal = 'Modal', stringPopover = 'Popover', stringScrollSpy = 'ScrollSpy', stringTab = 'Tab', stringTooltip = 'Tooltip', // options DATA API databackdrop = 'data-backdrop', dataKeyboard = 'data-keyboard', dataTarget = 'data-target', dataInterval = 'data-interval', dataHeight = 'data-height', dataPause = 'data-pause', dataOriginalTitle = 'data-original-title', dataOriginalText = 'data-original-text', dataDismissible = 'data-dismissible', dataTrigger = 'data-trigger', dataAnimation = 'data-animation', dataContainer = 'data-container', dataPlacement = 'data-placement', dataDelay = 'data-delay', dataOffsetTop = 'data-offset-top', dataOffsetBottom = 'data-offset-bottom', // option keys backdrop = 'backdrop', keyboard = 'keyboard', delay = 'delay', content = 'content', target = 'target', interval = 'interval', pause = 'pause', animation = 'animation', placement = 'placement', container = 'container', // box model offsetTop = 'offsetTop', offsetBottom = 'offsetBottom', offsetLeft = 'offsetLeft', scrollTop = 'scrollTop', scrollLeft = 'scrollLeft', clientWidth = 'clientWidth', clientHeight = 'clientHeight', offsetWidth = 'offsetWidth', offsetHeight = 'offsetHeight', innerWidth = 'innerWidth', innerHeight = 'innerHeight', scrollHeight = 'scrollHeight', height = 'height', // aria ariaExpanded = 'aria-expanded', ariaHidden = 'aria-hidden', // event names clickEvent = 'click', hoverEvent = 'hover', keydownEvent = 'keydown', resizeEvent = 'resize', scrollEvent = 'scroll', // originalEvents showEvent = 'show', shownEvent = 'shown', hideEvent = 'hide', hiddenEvent = 'hidden', closeEvent = 'close', closedEvent = 'closed', slidEvent = 'slid', slideEvent = 'slide', changeEvent = 'change', // other getAttribute = 'getAttribute', setAttribute = 'setAttribute', hasAttribute = 'hasAttribute', getElementsByTagName = 'getElementsByTagName', getBoundingClientRect = 'getBoundingClientRect', getElementsByCLASSNAME = 'getElementsByClassName', indexOf = 'indexOf', parentNode = 'parentNode', length = 'length', toLowerCase = 'toLowerCase', Transition = 'Transition', Webkit = 'Webkit', style = 'style', active = 'active', showClass = 'show', collapsing = 'collapsing', disabled = 'disabled', loading = 'loading', left = 'left', right = 'right', top = 'top', bottom = 'bottom', // tooltip / popover fixedTop = '.fixed-top', fixedBottom = '.fixed-bottom', mouseHover = ('onmouseleave' in document) ? [ 'mouseenter', 'mouseleave'] : [ 'mouseover', 'mouseout' ], tipPositions = /\b(top|bottom|left|top)+/, // transitionEnd since 2.0.4 supportTransitions = Webkit+Transition in doc[style] || Transition[toLowerCase]() in doc[style], transitionEndEvent = Webkit+Transition in doc[style] ? Webkit[toLowerCase]()+Transition+'End' : Transition[toLowerCase]()+'end', // set new focus element since 2.0.3 setFocus = function(element){ element.focus ? element.focus() : element.setActive(); }, // class manipulation, since 2.0.0 requires polyfill.js addClass = function(element,classNAME) { element.classList.add(classNAME); }, removeClass = function(element,classNAME) { element.classList.remove(classNAME); }, hasClass = function(element,classNAME){ // since 2.0.0 return element.classList.contains(classNAME); }, // selection methods getElementsByClassName = function(element,classNAME) { // returns Array return [].slice.call(element[getElementsByCLASSNAME]( classNAME )); }, queryElement = function (selector, parent) { var lookUp = parent ? parent : document; return typeof selector === 'object' ? selector : lookUp.querySelector(selector); }, getClosest = function (element, selector) { //element is the element and selector is for the closest parent element to find // source http://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/ var firstChar = selector.charAt(0); for ( ; element && element !== document; element = element[parentNode] ) {// Get closest match if ( firstChar === '.' ) {// If selector is a class if ( queryElement(selector,element[parentNode]) !== null && hasClass(element,selector.replace('.','')) ) { return element; } } else if ( firstChar === '#' ) { // If selector is an ID if ( element.id === selector.substr(1) ) { return element; } } } return false; }, // event attach jQuery style / trigger since 1.2.0 on = function (element, event, handler) { element.addEventListener(event, handler, false); }, off = function(element, event, handler) { element.removeEventListener(event, handler, false); }, one = function (element, event, handler) { // one since 2.0.4 on(element, event, function handlerWrapper(e){ handler(e); off(element, event, handlerWrapper); }); }, emulateTransitionEnd = function(element,handler){ // emulateTransitionEnd since 2.0.4 if (supportTransitions) { one(element, transitionEndEvent, function(e){ handler(e); }); } else { handler(); } }, bootstrapCustomEvent = function (eventName, componentName, related) { var OriginalCustomEvent = new CustomEvent( eventName + '.bs.' + componentName); OriginalCustomEvent.relatedTarget = related; this.dispatchEvent(OriginalCustomEvent); }, // reference a live collection of the DOM AllDOMElements = document[getElementsByTagName]('*'), // Init DATA API initializeDataAPI = function( component, constructor, dataAttribute, collection ){ var lookUp = collection && collection[length] ? collection : AllDOMElements; for (var i=0; i < lookUp[length]; i++) { var attrValue = lookUp[i][getAttribute](dataAttribute), expectedAttrValue = component.replace(/spy/i,'')[toLowerCase](); if ( attrValue && component === stringButton && ( attrValue[indexOf](expectedAttrValue) > -1 ) // data-toggle="buttons" || attrValue === expectedAttrValue ) { // all other components new constructor(lookUp[i]); } } }, // tab / collapse stuff targetsReg = /^\#(.)+$/, getOuterHeight = function (child) { var childStyle = child && globalObject.getComputedStyle(child), btp = /px/.test(childStyle.borderTopWidth) ? Math.round(childStyle.borderTopWidth.replace('px','')) : 0, btb = /px/.test(childStyle.borderBottomWidth) ? Math.round(childStyle.borderBottomWidth.replace('px','')) : 0, mtp = /px/.test(childStyle.marginTop) ? Math.round(childStyle.marginTop.replace('px','')) : 0, mbp = /px/.test(childStyle.marginBottom) ? Math.round(childStyle.marginBottom.replace('px','')) : 0; return child[clientHeight] + parseInt( btp ) + parseInt( btb ) + parseInt( mtp ) + parseInt( mbp ); }, getMaxHeight = function(parent) { // get collapse trueHeight and border var parentHeight = 0; for (var k = 0, ll = parent.children[length]; k < ll; k++) { parentHeight += getOuterHeight(parent.children[k]); } return parentHeight; }, // tooltip / popover stuff isElementInViewport = function(element) { // check if this.tooltip is in viewport var rect = element[getBoundingClientRect](); return ( rect[top] >= 0 && rect[left] >= 0 && rect[bottom] <= (globalObject[innerHeight] || doc[clientHeight]) && rect[right] <= (globalObject[innerWidth] || doc[clientWidth]) ) }, getScroll = function() { // also Affix and ScrollSpy uses it return { y : globalObject.pageYOffset || doc[scrollTop], x : globalObject.pageXOffset || doc[scrollLeft] } }, styleTip = function(link,element,position,parent) { // both popovers and tooltips var rect = link[getBoundingClientRect](), scroll = parent === body ? getScroll() : { x: parent[offsetLeft] + parent[scrollLeft], y: parent[offsetTop] + parent[scrollTop] }, linkDimensions = { w: rect[right] - rect[left], h: rect[bottom] - rect[top] }, elementDimensions = { w : element[offsetWidth], h: element[offsetHeight] }; // apply styling to tooltip or popover if ( position === top ) { // TOP element[style][top] = rect[top] + scroll.y - elementDimensions.h + 'px'; element[style][left] = rect[left] + scroll.x - elementDimensions.w/2 + linkDimensions.w/2 + 'px' } else if ( position === bottom ) { // BOTTOM element[style][top] = rect[top] + scroll.y + linkDimensions.h + 'px'; element[style][left] = rect[left] + scroll.x - elementDimensions.w/2 + linkDimensions.w/2 + 'px'; } else if ( position === left ) { // LEFT element[style][top] = rect[top] + scroll.y - elementDimensions.h/2 + linkDimensions.h/2 + 'px'; element[style][left] = rect[left] + scroll.x - elementDimensions.w + 'px'; } else if ( position === right ) { // RIGHT element[style][top] = rect[top] + scroll.y - elementDimensions.h/2 + linkDimensions.h/2 + 'px'; element[style][left] = rect[left] + scroll.x + linkDimensions.w + 'px'; } element.className[indexOf](position) === -1 && (element.className = element.className.replace(tipPositions,position)); }, updatePlacement = function(position) { return position === top ? bottom : // top position === bottom ? top : // bottom position === left ? right : // left position === right ? left : position; // right }; /* Native Javascript for Bootstrap 4 | Alert -------------------------------------------*/ // ALERT DEFINITION // ================ var Alert = function( element ) { // initialization element element = queryElement(element); // bind, target alert, duration and stuff var self = this, component = 'alert', alert = getClosest(element,'.'+component), // handlers clickHandler = function(e){ var eventTarget = e[target]; eventTarget = eventTarget[hasAttribute](dataDismiss) ? eventTarget : eventTarget[parentNode]; if (eventTarget && eventTarget[hasAttribute](dataDismiss)) { // we double check the data attribute, it's important alert = getClosest(eventTarget,'.'+component); element = queryElement('['+dataDismiss+'="'+component+'"]',alert); (element === eventTarget || element === eventTarget[parentNode]) && alert && self.close(); } }, transitionEndHandler = function(){ bootstrapCustomEvent.call(alert, closedEvent, component); off(element, clickEvent, clickHandler); // detach it's listener alert[parentNode].removeChild(alert); }; // public method this.close = function() { if ( alert && element && hasClass(alert,showClass) ) { bootstrapCustomEvent.call(alert, closeEvent, component); removeClass(alert,showClass); (function(){ alert && emulateTransitionEnd(alert,transitionEndHandler);}()) } }; // init if ( !(stringAlert in element ) ) { // prevent adding event handlers twice on(element, clickEvent, clickHandler); } element[stringAlert] = this; }; // ALERT DATA API // ============== initializeDataAPI ( stringAlert, Alert, dataDismiss ); /* Native Javascript for Bootstrap 4 | Button ---------------------------------------------*/ // BUTTON DEFINITION // =================== var Button = function( element ) { // initialization element element = queryElement(element); // constant var toggled = false, // toggled makes sure to prevent triggering twice the change.bs.button events // strings component = 'button', checked = 'checked', reset = 'reset', LABEL = 'LABEL', INPUT = 'INPUT', // private methods toggle = function(e) { var parent = e[target][parentNode], label = e[target].tagName === LABEL ? e[target] : parent.tagName === LABEL ? parent : null; // the .btn label if ( !label ) return; //react if a label or its immediate child is clicked var eventTarget = this, // the button group, the target of the handler function labels = getElementsByClassName(eventTarget,'btn'), // all the button group buttons input = label[getElementsByTagName](INPUT)[0]; if ( !input ) return; //return if no input found // manage the dom manipulation if ( input.type === 'checkbox' ) { //checkboxes if ( !input[checked] ) { addClass(label,active); input[getAttribute](checked); input[setAttribute](checked,checked); input[checked] = true; } else { removeClass(label,active); input[getAttribute](checked); input.removeAttribute(checked); input[checked] = false; } if (!toggled) { // prevent triggering the event twice toggled = true; bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group } } if ( input.type === 'radio' && !toggled ) { // radio buttons if ( !input[checked] ) { // don't trigger if already active addClass(label,active); input[setAttribute](checked,checked); input[checked] = true; bootstrapCustomEvent.call(input, changeEvent, component); //trigger the change for the input bootstrapCustomEvent.call(element, changeEvent, component); //trigger the change for the btn-group toggled = true; for (var i = 0, ll = labels[length]; i<ll; i++) { var otherLabel = labels[i], otherInput = otherLabel[getElementsByTagName](INPUT)[0]; if ( otherLabel !== label && hasClass(otherLabel,active) ) { removeClass(otherLabel,active); otherInput.removeAttribute(checked); otherInput[checked] = false; bootstrapCustomEvent.call(otherInput, changeEvent, component); // trigger the change } } } } setTimeout( function() { toggled = false; }, 50 ); }; // init if ( hasClass(element,'btn-group') ) { if ( !( stringButton in element ) ) { // prevent adding event handlers twice on( element, clickEvent, toggle ); } element[stringButton] = this; } }; // BUTTON DATA API // ================= initializeDataAPI( stringButton, Button, dataToggle ); /* Native Javascript for Bootstrap 4 | Carousel ----------------------------------------------*/ // CAROUSEL DEFINITION // =================== var Carousel = function( element, options ) { // initialization element element = queryElement( element ); // set options options = options || {}; // DATA API var intervalData = element[getAttribute](dataInterval) === 'false' ? false : parseInt(element[getAttribute](dataInterval)) || 5000, // bootstrap carousel default interval pauseData = element[getAttribute](dataPause) === hoverEvent || false, keyboardData = element[getAttribute](dataKeyboard) === 'true' || false, // strings component = 'carousel', paused = 'paused', direction = 'direction', carouselItem = 'carousel-item', dataSlideTo = 'data-slide-to'; this[keyboard] = options[keyboard] === true || keyboardData; this[pause] = (options[pause] === hoverEvent || pauseData) ? hoverEvent : false; // false / hover if ( !( options[interval] || intervalData ) ) { // determine slide interval this[interval] = false; } else { this[interval] = parseInt(options[interval]) || intervalData; // default slide interval } // bind, event targets var self = this, index = element.index = 0, timer = element.timer = 0, isSliding = false, // isSliding prevents click event handlers when animation is running slides = getElementsByClassName(element,carouselItem), total = slides[length], slideDirection = this[direction] = left, leftArrow = getElementsByClassName(element,component+'-control-prev')[0], rightArrow = getElementsByClassName(element,component+'-control-next')[0], indicator = queryElement( '.'+component+'-indicators', element ), indicators = indicator[getElementsByTagName]( "LI" ); // handlers var pauseHandler = function () { if ( self[interval] !==false && !hasClass(element,paused) ) { addClass(element,paused); !isSliding && clearInterval( timer ); } }, resumeHandler = function() { if ( self[interval] !== false && hasClass(element,paused) ) { removeClass(element,paused); !isSliding && clearInterval( timer ); !isSliding && self.cycle(); } }, indicatorHandler = function(e) { e.preventDefault(); if (isSliding) return; var eventTarget = e[target], activeIndicator = self.getActiveIndex(); // event target | the current active item if ( eventTarget && !hasClass(eventTarget,active) && eventTarget[getAttribute](dataSlideTo) ) { index = parseInt( eventTarget[getAttribute](dataSlideTo), 10 ); //determine direction first if ( (activeIndicator < index ) || (activeIndicator === 0 && index === total -1 ) ) { slideDirection = self[direction] = left; // next } else if ( (activeIndicator > index) || (activeIndicator === total - 1 && index === 0 ) ) { slideDirection = self[direction] = right; // prev } } else { return false; } self.slideTo( index ); //Do the slide }, controlsHandler = function (e) { e.preventDefault(); if (isSliding) return; var eventTarget = e.currentTarget || e.srcElement; if ( eventTarget === rightArrow ) { index++; slideDirection = self[direction] = left; //set direction first if( index === total - 1 ) { index = total - 1; } else if ( index === total ){ index = 0; } } else if ( eventTarget === leftArrow ) { index--; slideDirection = self[direction] = right; //set direction first if( index === 0 ) { index = 0; } else if ( index < 0 ){ index = total - 1 } } self.slideTo( index ); //Do the slide }, keyHandler = function (e) { if (isSliding) return; switch (e.which) { case 39: index++; slideDirection = self[direction] = left; if( index == total - 1 ) { index = total - 1; } else if ( index == total ){ index = 0 } break; case 37: index--; slideDirection = self[direction] = right; if ( index == 0 ) { index = 0; } else if ( index < 0 ) { index = total - 1 } break; default: return; } self.slideTo( index ); //Do the slide }, // private methods setActivePage = function( pageIndex ) { //indicators for ( var i = 0, icl = indicators[length]; i < icl; i++ ) { removeClass(indicators[i],active); } if (indicators[pageIndex]) addClass(indicators[pageIndex], active); }; // public methods this.cycle = function() { slideDirection = this[direction] = left; // make sure to always come back to default slideDirection timer = setInterval(function() { index++; index = index === total ? 0 : index; self.slideTo( index ); }, this[interval]); }; this.slideTo = function( next ) { var activeItem = this.getActiveIndex(), // the current active orientation = slideDirection === left ? 'next' : 'prev'; //determine type bootstrapCustomEvent.call(element, slideEvent, component, slides[next]); // here we go with the slide isSliding = true; clearInterval(timer); setActivePage( next ); if ( supportTransitions && hasClass(element,'slide') && ( // we now check if the media queries do actually filter out BS4 transitions globalObject.getComputedStyle(slides[next])[Transition[toLowerCase]()] || globalObject.getComputedStyle(slides[next])[Webkit[toLowerCase]() + Transition] || globalObject.getComputedStyle(slides[next])[Webkit + Transition + 'Duration'] // old Safari stuff ) ) { addClass(slides[next],carouselItem +'-'+ orientation); slides[next][offsetWidth]; addClass(slides[next],carouselItem +'-'+ slideDirection); addClass(slides[activeItem],carouselItem +'-'+ slideDirection); one(slides[activeItem], transitionEndEvent, function(e) { var timeout = e[target] !== slides[activeItem] ? e.elapsedTime*1000 : 0; setTimeout(function(){ isSliding = false; addClass(slides[next],active); removeClass(slides[activeItem],active); removeClass(slides[next],carouselItem +'-'+ orientation); removeClass(slides[next],carouselItem +'-'+ slideDirection); removeClass(slides[activeItem],carouselItem +'-'+ slideDirection); bootstrapCustomEvent.call(element, slidEvent, component, slides[next]); if ( !document.hidden && self[interval] && !hasClass(element,paused) ) { self.cycle(); } },timeout); }); } else { addClass(slides[next],active); slides[next][offsetWidth]; removeClass(slides[activeItem],active); setTimeout(function() { isSliding = false; if ( self[interval] && !hasClass(element,paused) ) { self.cycle(); } bootstrapCustomEvent.call(element, slidEvent, component, slides[next]); }, 100 ); } }; this.getActiveIndex = function () { return slides[indexOf](getElementsByClassName(element,carouselItem+' active')[0]) || 0; }; // init if ( !(stringCarousel in element ) ) { // prevent adding event handlers twice if ( this[pause] && this[interval] ) { on( element, mouseHover[0], pauseHandler ); on( element, mouseHover[1], resumeHandler ); on( element, 'touchstart', pauseHandler ); on( element, 'touchend', resumeHandler ); } rightArrow && on( rightArrow, clickEvent, controlsHandler ); leftArrow && on( leftArrow, clickEvent, controlsHandler ); indicator && on( indicator, clickEvent, indicatorHandler, false); this[keyboard] === true && on( globalObject, keydownEvent, keyHandler, false); } if (this.getActiveIndex()<0) { slides[length] && addClass(slides[0],active); indicators[length] && setActivePage(0); } if ( this[interval] ){ this.cycle(); } element[stringCarousel] = this; }; // CAROUSEL DATA API // ================= initializeDataAPI( stringCarousel, Carousel, dataRide ); /* Native Javascript for Bootstrap 4 | Collapse -----------------------------------------------*/ // COLLAPSE DEFINITION // =================== var Collapse = function( element, options ) { // initialization element element = queryElement(element); // set options options = options || {}; // event targets and constants var accordion = null, collapse = null, self = this, isAnimating = false, // when true it will prevent click handlers accordionData = element[getAttribute]('data-parent'), // component strings component = 'collapse', collapsed = 'collapsed', // private methods openAction = function(collapseElement) { bootstrapCustomEvent.call(collapseElement, showEvent, component); isAnimating = true; addClass(collapseElement,collapsing); addClass(collapseElement,showClass); setTimeout(function() { collapseElement[style][height] = getMaxHeight(collapseElement) + 'px'; (function(){ emulateTransitionEnd(collapseElement, function(){ isAnimating = false; collapseElement[setAttribute](ariaExpanded,'true'); removeClass(collapseElement,collapsing); collapseElement[style][height] = ''; bootstrapCustomEvent.call(collapseElement, shownEvent, component); }); }()); }, 20); }, closeAction = function(collapseElement) { bootstrapCustomEvent.call(collapseElement, hideEvent, component); isAnimating = true; collapseElement[style][height] = getMaxHeight(collapseElement) + 'px'; setTimeout(function() { addClass(collapseElement,collapsing); collapseElement[style][height] = '0px'; (function() { emulateTransitionEnd(collapseElement, function(){ isAnimating = false; collapseElement[setAttribute](ariaExpanded,'false'); removeClass(collapseElement,collapsing); removeClass(collapseElement,showClass); collapseElement[style][height] = ''; bootstrapCustomEvent.call(collapseElement, hiddenEvent, component); }); }()); },20); }, getTarget = function() { var href = element.href && element[getAttribute]('href'), parent = element[getAttribute](dataTarget), id = href || ( parent && targetsReg.test(parent) ) && parent; return id && queryElement(id); }; // public methods this.toggle = function(e) { e.preventDefault(); if (isAnimating) return; if (!hasClass(collapse,showClass)) { self.show(); } else { self.hide(); } }; this.hide = function() { closeAction(collapse); addClass(element,collapsed); }; this.show = function() { openAction(collapse); removeClass(element,collapsed); if ( accordion !== null ) { var activeCollapses = getElementsByClassName(accordion,component+' '+showClass); for (var i=0, al=activeCollapses[length]; i<al; i++) { if ( activeCollapses[i] !== collapse) closeAction(activeCollapses[i]); } } }; // init if ( !(stringCollapse in element ) ) { // prevent adding event handlers twice on(element, clickEvent, this.toggle); } collapse = getTarget(); accordion = queryElement(options.parent) || accordionData && getClosest(element, accordionData); element[stringCollapse] = this; }; // COLLAPSE DATA API // ================= initializeDataAPI(stringCollapse, Collapse, dataToggle); /* Native Javascript for Bootstrap 4 | Dropdown ----------------------------------------------*/ // DROPDOWN DEFINITION // =================== var Dropdown = function( element, option ) { // initialization element element = queryElement(element); // set option this.persist = option === true || element[getAttribute]('data-persist') === 'true' || false; // constants, event targets, strings var self = this, isOpen = false, parent = element[parentNode], component = 'dropdown', relatedTarget = null, menu = queryElement('.dropdown-menu', parent), children = [].slice.call( menu[getElementsByTagName]('*')), // handlers keyHandler = function(e) { if (isOpen && (e.which == 27 || e.keyCode == 27)) { relatedTarget = null; hide(); } // e.keyCode for IE8 }, clickHandler = function(e) { var eventTarget = e[target], hasData; hasData = ( eventTarget.nodeType !== 1 && (eventTarget[getAttribute](dataToggle) || eventTarget[parentNode][getAttribute](dataToggle)) ); if ( eventTarget === element || eventTarget === parent || eventTarget[parentNode] === element ) { e.preventDefault(); // comment this line to stop preventing navigation when click target is a link relatedTarget = element; self.toggle(); } else if ( isOpen ) { if ( (eventTarget === menu || children && children[indexOf](eventTarget) > -1) && ( self.persist || hasData ) ) { return; } else { relatedTarget = null; hide(); } } (/\#$/.test(eventTarget.href) || eventTarget[parentNode] && /\#$/.test(eventTarget[parentNode].href)) && e.preventDefault(); // should be here to prevent jumps }, // private methods show = function() { bootstrapCustomEvent.call(parent, showEvent, component, relatedTarget); addClass(parent,showClass); menu[setAttribute](ariaExpanded,true); bootstrapCustomEvent.call(parent, shownEvent, component, relatedTarget); on(document, keydownEvent, keyHandler); isOpen = true; }, hide = function() { bootstrapCustomEvent.call(parent, hideEvent, component, relatedTarget); removeClass(parent,showClass); menu[setAttribute](ariaExpanded,false); bootstrapCustomEvent.call(parent, hiddenEvent, component, relatedTarget); off(document, keydownEvent, keyHandler); isOpen = false; }; // public methods this.toggle = function() { if (hasClass(parent,showClass) && isOpen) { hide(); } else { show(); } }; // init if ( !(stringDropdown in element) ) { // prevent adding event handlers twice menu[setAttribute]('tabindex', '0'); // Fix onblur on Chrome | Safari on(document, clickEvent, clickHandler); } element[stringDropdown] = this; }; // DROPDOWN DATA API // ================= initializeDataAPI( stringDropdown, Dropdown, dataToggle ); /* Native Javascript for Bootstrap 4 | Modal -------------------------------------------*/ // MODAL DEFINITION // =============== var Modal = function(element, options) { // element can be the modal/triggering button // the modal (both JavaScript / DATA API init) / triggering button element (DATA API) element = queryElement(element); // determine modal, triggering element var btnCheck = element[getAttribute](dataTarget)||element[getAttribute]('href'), checkModal = queryElement( btnCheck ), modal = hasClass(element,'modal') ? element : checkModal, // strings component = 'modal', staticString = 'static', paddingLeft = 'paddingLeft', paddingRight = 'paddingRight', modalBackdropString = 'modal-backdrop'; if ( hasClass(element,'modal') ) { element = null; } // modal is now independent of it's triggering element if ( !modal ) { return; } // invalidate // set options options = options || {}; this[keyboard] = options[keyboard] === false || modal[getAttribute](dataKeyboard) === 'false' ? false : true; this[backdrop] = options[backdrop] === staticString || modal[getAttribute](databackdrop) === staticString ? staticString : true; this[backdrop] = options[backdrop] === false || modal[getAttribute](databackdrop) === 'false' ? false : this[backdrop]; this[content] = options[content]; // JavaScript only // bind, constants, event targets and other vars var self = this, open = this.open = false, relatedTarget = null, bodyIsOverflowing, modalIsOverflowing, scrollbarWidth, overlay, // also find fixed-top / fixed-bottom items fixedItems = getElementsByClassName(doc,'fixed-top').concat(getElementsByClassName(doc,'fixed-bottom')), // private methods getWindowWidth = function() { var htmlRect = doc[getBoundingClientRect](); return globalObject[innerWidth] || (htmlRect[right] - Math.abs(htmlRect[left])); }, setScrollbar = function () { var bodyStyle = globalObject.getComputedStyle(body), bodyPad = parseInt((bodyStyle[paddingRight]), 10), itemPad; if (bodyIsOverflowing) { body[style][paddingRight] = (bodyPad + scrollbarWidth) + 'px'; if (fixedItems[length]){ for (var i = 0; i < fixedItems[length]; i++) { itemPad = globalObject.getComputedStyle(fixedItems[i])[paddingRight]; fixedItems[i][style][paddingRight] = ( parseInt(itemPad) + scrollbarWidth) + 'px'; } } } }, resetScrollbar = function () { body[style][paddingRight] = ''; if (fixedItems[length]){ for (var i = 0; i < fixedItems[length]; i++) { fixedItems[i][style][paddingRight] = ''; } } }, measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div'), scrollBarWidth; scrollDiv.className = component+'-scrollbar-measure'; // this is here to stay body.appendChild(scrollDiv); scrollBarWidth = scrollDiv[offsetWidth] - scrollDiv[clientWidth]; body.removeChild(scrollDiv); return scrollBarWidth; }, checkScrollbar = function () { bodyIsOverflowing = body[clientWidth] < getWindowWidth(); modalIsOverflowing = modal[scrollHeight] > doc[clientHeight]; scrollbarWidth = measureScrollbar(); }, adjustDialog = function () { modal[style][paddingLeft] = !bodyIsOverflowing && modalIsOverflowing ? scrollbarWidth + 'px' : ''; modal[style][paddingRight] = bodyIsOverflowing && !modalIsOverflowing ? scrollbarWidth + 'px' : ''; }, resetAdjustments = function () { modal[style][paddingLeft] = ''; modal[style][paddingRight] = ''; }, createOverlay = function() { var newOverlay = document.createElement('div'); overlay = queryElement('.'+modalBackdropString); if ( overlay === null ) { newOverlay[setAttribute]('class',modalBackdropString+' fade'); overlay = newOverlay; body.appendChild(overlay); } }, removeOverlay = function() { overlay = queryElement('.'+modalBackdropString); if ( overlay && overlay !== null && typeof overlay === 'object' ) { body.removeChild(overlay); overlay = null; } }, keydownHandlerToggle = function() { if (!hasClass(modal,showClass)) { on(document, keydownEvent, keyHandler); } else { off(document, keydownEvent, keyHandler); } }, resizeHandlerToggle = function() { if (!hasClass(modal,showClass)) { on(globalObject, resizeEvent, self.update); } else { off(globalObject, resizeEvent, self.update); } }, dismissHandlerToggle = function() { if (!hasClass(modal,showClass)) { on(modal, clickEvent, dismissHandler); } else { off(modal, clickEvent, dismissHandler); } }, // handlers clickHandler = function(e) { var clickTarget = e[target]; clickTarget = clickTarget[hasAttribute](dataTarget) || clickTarget[hasAttribute]('href') ? clickTarget : clickTarget[parentNode]; if ( !open && clickTarget === element && !hasClass(modal,showClass) ) { modal.modalTrigger = element; relatedTarget = element; self.show(); e.preventDefault(); } }, keyHandler = function(e) { var key = e.which || e.keyCode; // keyCode for IE8 if (self[keyboard] && key == 27 && open) { self.hide(); } }, dismissHandler = function(e) { var clickTarget = e[target]; if ( open && (clickTarget[parentNode][getAttribute](dataDismiss) === component || clickTarget[getAttribute](dataDismiss) === component || (clickTarget === modal && self[backdrop] !== staticString) ) ) { self.hide(); relatedTarget = null; e.preventDefault(); } }; // public methods this.toggle = function() { if (open && hasClass(modal,showClass)) {this.hide();} else {this.show();} }; this.show = function() { bootstrapCustomEvent.call(modal, showEvent, component, relatedTarget); // we elegantly hide any opened modal var currentOpen = getElementsByClassName(document,component+' '+showClass)[0]; currentOpen && currentOpen !== modal && currentOpen.modalTrigger[stringModal].hide(); if ( this[backdrop] ) { createOverlay(); } if ( overlay && !hasClass(overlay,showClass)) { setTimeout( function() { addClass(overlay, showClass); },0); } setTimeout( function() { modal[style].display = 'block'; checkScrollbar(); setScrollbar(); adjustDialog(); resizeHandlerToggle(); dismissHandlerToggle(); keydownHandlerToggle(); addClass(body,component+'-open'); addClass(modal,showClass); modal[setAttribute](ariaHidden, false); emulateTransitionEnd(modal, function(){ open = self.open = true; setFocus(modal); bootstrapCustomEvent.call(modal, shownEvent, component, relatedTarget); }); }, supportTransitions ? 150 : 0); }; this.hide = function() { bootstrapCustomEvent.call(modal, hideEvent, component); overlay = queryElement('.'+modalBackdropString); removeClass(modal,showClass); modal[setAttribute](ariaHidden, true); !!overlay && removeClass(overlay,showClass); setTimeout(function(){ emulateTransitionEnd(modal, function(){ resizeHandlerToggle(); dismissHandlerToggle(); keydownHandlerToggle(); modal[style].display = ''; open = self.open = false; element && (setFocus(element)); bootstrapCustomEvent.call(modal, hiddenEvent, component); setTimeout(function(){ if (!getElementsByClassName(document,component+' '+showClass)[0]) { resetAdjustments(); resetScrollbar(); removeClass(body,component+'-open'); removeOverlay(); } }, 100); }); }, supportTransitions ? 150 : 0); }; this.setContent = function( content ) { queryElement('.'+component+'-content',modal).innerHTML = content; }; this.update = function() { if (open) { checkScrollbar(); setScrollbar(); adjustDialog(); } }; // init // prevent adding event handlers over and over // modal is independent of a triggering element if ( !!element && !(stringModal in element) ) { on(element, clickEvent, clickHandler); } if ( !!this[content] ) { this.setContent( this[content] ); } !!element && (element[stringModal] = this); }; // DATA API initializeDataAPI(stringModal, Modal, dataToggle); /* Native Javascript for Bootstrap 4 | Popover ----------------------------------------------*/ // POPOVER DEFINITION // ================== var Popover = function( element, options ) { // initialization element element = queryElement(element); // DATA API var triggerData = element[getAttribute](dataTrigger), // click / hover / focus animationData = element[getAttribute](dataAnimation), // true / false placementData = element[getAttribute](dataPlacement), dismissibleData = element[getAttribute](dataDismissible), delayData = element[getAttribute](dataDelay), containerData = element[getAttribute](dataContainer), // internal strings component = 'popover', template = 'template', trigger = 'trigger', classString = 'class', div = 'div', fade = 'fade', title = 'title', content = 'content', dataTitle = 'data-title', dataContent = 'data-content', dismissible = 'dismissible', closeBtn = '<button type="button" class="close">×</button>', // maybe the element is inside a modal modal = getClosest(element,'.modal'), // maybe the element is inside a fixed navbar navbarFixedTop = getClosest(element,fixedTop), navbarFixedBottom = getClosest(element,fixedBottom); // set options options = options || {}; this[template] = options[template] ? options[template] : null; // JavaScript only this[trigger] = options[trigger] ? options[trigger] : triggerData || hoverEvent; this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade; this[placement] = options[placement] ? options[placement] : placementData || top; this[delay] = parseInt(options[delay] || delayData) || 200; this[dismissible] = options[dismissible] || dismissibleData === 'true' ? true : false; this[container] = queryElement(options[container]) ? queryElement(options[container]) : queryElement(containerData) ? queryElement(containerData) : navbarFixedTop ? navbarFixedTop : navbarFixedBottom ? navbarFixedBottom : modal ? modal : body; // bind, content var self = this, titleString = element[getAttribute](dataTitle) || null, contentString = element[getAttribute](dataContent) || null; if ( !contentString && !this[template] ) return; // invalidate // constants, vars var popover = null, timer = 0, placementSetting = this[placement], // handlers dismissibleHandler = function(e) { if (popover !== null && e[target] === queryElement('.close',popover)) { self.hide(); } }, // private methods removePopover = function() { self[container].removeChild(popover); timer = null; popover = null; }, createPopover = function() { titleString = element[getAttribute](dataTitle); // check content again contentString = element[getAttribute](dataContent); popover = document.createElement(div); if ( contentString !== null && self[template] === null ) { //create the popover from data attributes popover[setAttribute]('role','tooltip'); if (titleString !== null) { var popoverTitle = document.createElement('h3'); popoverTitle[setAttribute](classString,component+'-title'); popoverTitle.innerHTML = self[dismissible] ? titleString + closeBtn : titleString; popover.appendChild(popoverTitle); } //set popover content var popoverContent = document.createElement(div); popoverContent[setAttribute](classString,component+'-content'); popoverContent.innerHTML = self[dismissible] && titleString === null ? contentString + closeBtn : contentString; popover.appendChild(popoverContent); } else { // or create the popover from template var popoverTemplate = document.createElement(div); popoverTemplate.innerHTML = self[template]; popover.innerHTML = popoverTemplate.firstChild.innerHTML; } //append to the container self[container].appendChild(popover); popover[style].display = 'block'; popover[setAttribute](classString, component+ ' ' + component+'-'+placementSetting + ' ' + self[animation]); }, showPopover = function () { !hasClass(popover,showClass) && ( addClass(popover,showClass) ); }, updatePopover = function() { styleTip(element,popover,placementSetting,self[container]); if (!isElementInViewport(popover) ) { placementSetting = updatePlacement(placementSetting); styleTip(element,popover,placementSetting,self[container]); } }; // public methods / handlers this.toggle = function() { if (popover === null) { self.show(); } else { self.hide(); } }; this.show = function() { clearTimeout(timer); timer = setTimeout( function() { if (popover === null) { placementSetting = self[placement]; // we reset placement in all cases createPopover(); updatePopover(); showPopover(); bootstrapCustomEvent.call(element, showEvent, component); emulateTransitionEnd(popover, function(){ bootstrapCustomEvent.call(element, shownEvent, component); }); } }, 20 ); }; this.hide = function() { clearTimeout(timer); timer = setTimeout( function() { if (popover && popover !== null && hasClass(popover,showClass)) { bootstrapCustomEvent.call(element, hideEvent, component); removeClass(popover,showClass); emulateTransitionEnd(popover, function() { removePopover(); bootstrapCustomEvent.call(element, hiddenEvent, component); }); } }, self[delay] ); }; // init if ( !(stringPopover in element) ) { // prevent adding event handlers twice if (self[trigger] === hoverEvent) { on( element, mouseHover[0], self.show ); if (!self[dismissible]) { on( element, mouseHover[1], self.hide ); } } else if (/^(click|focus)$/.test(self[trigger])) { on( element, self[trigger], self.toggle ); if (!self[dismissible]) { on( element, 'blur', self.hide ); } } if (self[dismissible]) { on( document, clickEvent, dismissibleHandler ); } // dismiss on window resize on( globalObject, resizeEvent, self.hide ); } element[stringPopover] = self; }; // POPOVER DATA API // ================ initializeDataAPI(stringPopover, Popover, dataToggle); /* Native Javascript for Bootstrap 4 | ScrollSpy -----------------------------------------------*/ // SCROLLSPY DEFINITION // ==================== var ScrollSpy = function(element, options) { // initialization element, the element we spy on element = queryElement(element); // DATA API var targetData = queryElement(element[getAttribute](dataTarget)); // set options options = options || {}; if ( !options[target] && !targetData ) { return; } // invalidate // event targets, constants var spyTarget = options[target] && queryElement(options[target]) || targetData, links = spyTarget && spyTarget[getElementsByTagName]('A'), items = [], targetItems = [], scrollOffset, scrollTarget = element[offsetHeight] < element[scrollHeight] ? element : globalObject, // determine which is the real scrollTarget isWindow = scrollTarget === globalObject; // populate items and targets for (var i=0, il=links[length]; i<il; i++) { var href = links[i][getAttribute]('href'), targetItem = href && targetsReg.test(href) && queryElement(href); if ( !!targetItem ) { items.push(links[i]); targetItems.push(targetItem); } } // private methods var updateItem = function(index) { // var parent = items[index][parentNode], // item's item LI element var item = items[index], targetItem = targetItems[index], // the menu item targets this element dropdown = item[parentNode][parentNode], dropdownLink = hasClass(dropdown,'dropdown') && dropdown[getElementsByTagName]('A')[0], targetRect = isWindow && targetItem[getBoundingClientRect](), isActive = hasClass(item,active) || false, topEdge = isWindow ? targetRect[top] + scrollOffset : targetItem[offsetTop] - (targetItems[index-1] ? 0 : 10), bottomEdge = isWindow ? targetRect[bottom] + scrollOffset : targetItems[index+1] ? targetItems[index+1][offsetTop] : element[scrollHeight], inside = scrollOffset >= topEdge && bottomEdge > scrollOffset; if ( !isActive && inside ) { if ( !hasClass(item,active) ) { addClass(item,active); isActive = true; if (dropdownLink && !hasClass(dropdownLink,active) ) { addClass(dropdownLink,active); } bootstrapCustomEvent.call(element, 'activate', 'scrollspy', items[index]); } } else if ( !inside ) { if ( hasClass(item,active) ) { removeClass(item,active); isActive = false; if (dropdownLink && hasClass(dropdownLink,active) && !getElementsByClassName(item[parentNode],active).length ) { removeClass(dropdownLink,active); } } } else if ( !inside && !isActive || isActive && inside ) { return; } }, updateItems = function(){ scrollOffset = isWindow ? getScroll().y : element[scrollTop]; for (var index=0, itl=items[length]; index<itl; index++) { updateItem(index) } }; // public method this.refresh = function () { updateItems(); } // init if ( !(stringScrollSpy in element) ) { // prevent adding event handlers twice on( scrollTarget, scrollEvent, this.refresh ); on( globalObject, resizeEvent, this.refresh ); } this.refresh(); element[stringScrollSpy] = this; }; // SCROLLSPY DATA API // ================== initializeDataAPI(stringScrollSpy, ScrollSpy, dataSpy); /* Native Javascript for Bootstrap 4 | Tab -----------------------------------------*/ // TAB DEFINITION // ============== var Tab = function( element, options ) { // initialization element element = queryElement(element); // DATA API var heightData = element[getAttribute](dataHeight), // strings component = 'tab', height = 'height', isAnimating = 'isAnimating'; // set default animation state element[isAnimating] = false; // set options options = options || {}; this[height] = supportTransitions ? (options[height] || heightData === 'true') : false; // bind, event targets var self = this, next, tabs = getClosest(element,'.nav'), tabsContentContainer, dropdown = tabs && queryElement('.dropdown-toggle',tabs); if (!tabs) return; // invalidate // private methods var getActiveTab = function() { var activeTabs = getElementsByClassName(tabs,active), activeTab; if ( activeTabs[length] === 1 && !hasClass(activeTabs[0][parentNode],'dropdown') ) { activeTab = activeTabs[0]; } else if ( activeTabs[length] > 1 ) { activeTab = activeTabs[activeTabs[length]-1]; } return activeTab; }, getActiveContent = function() { return queryElement(getActiveTab()[getAttribute]('href')); }, // handler clickHandler = function(e) { e.preventDefault(); next = e[target][getAttribute](dataToggle) === component || targetsReg.test(e[target][getAttribute]('href')) ? e[target] : e[target][parentNode]; // allow for child elements like icons to use the handler self.show(); }; // public method this.show = function() { // the tab we clicked is now the next tab var nextContent = queryElement(next[getAttribute]('href')), //this is the actual object, the next tab content to activate activeTab = getActiveTab(), activeContent = getActiveContent(); if ( (!activeTab[isAnimating] || !next[isAnimating]) && !hasClass(next,active) ) { activeTab[isAnimating] = next[isAnimating] = true; removeClass(activeTab,active); addClass(next,active); if ( dropdown ) { if ( !hasClass(element[parentNode],'dropdown-menu') ) { if (hasClass(dropdown,active)) removeClass(dropdown,active); } else { if (!hasClass(dropdown,active)) addClass(dropdown,active); } } if (tabsContentContainer) tabsContentContainer[style][height] = getMaxHeight(activeContent) + 'px'; // height animation (function() { removeClass(activeContent,showClass); bootstrapCustomEvent.call(activeTab, hideEvent, component, next); (function(){ emulateTransitionEnd(activeContent, function() { removeClass(activeContent,active); addClass(nextContent,active); setTimeout(function() { addClass(nextContent,showClass); nextContent[offsetHeight]; if (tabsContentContainer) addClass(tabsContentContainer,collapsing); (function() { bootstrapCustomEvent.call(next, showEvent, component, activeTab); (function() { if (tabsContentContainer) tabsContentContainer[style][height] = getMaxHeight(nextContent) + 'px'; // height animation bootstrapCustomEvent.call(activeTab, hiddenEvent, component, next); }()); }()); },20); }); }()); }()); (function(){ emulateTransitionEnd(nextContent, function() { bootstrapCustomEvent.call(next, shownEvent, component, activeTab); if (tabsContentContainer) { // height animation (function(){ emulateTransitionEnd(tabsContentContainer, function(){ setTimeout(function(){ tabsContentContainer[style][height] = ''; removeClass(tabsContentContainer,collapsing); activeTab[isAnimating] = next[isAnimating] = false; },200); }); }()); } else { activeTab[isAnimating] = next[isAnimating] = false; } }); }()); } }; // init if ( !(stringTab in element) ) { // prevent adding event handlers twice on(element, clickEvent, clickHandler); } if (this[height]) { tabsContentContainer = getActiveContent()[parentNode]; } element[stringTab] = this; }; // TAB DATA API // ============ initializeDataAPI(stringTab, Tab, dataToggle); /* Native Javascript for Bootstrap 4 | Tooltip ---------------------------------------------*/ // TOOLTIP DEFINITION // ================== var Tooltip = function( element,options ) { // initialization element element = queryElement(element); // DATA API var animationData = element[getAttribute](dataAnimation); placementData = element[getAttribute](dataPlacement); delayData = element[getAttribute](dataDelay), containerData = element[getAttribute](dataContainer), // strings component = 'tooltip', classString = 'class', title = 'title', fade = 'fade', div = 'div', // maybe the element is inside a modal modal = getClosest(element,'.modal'), // maybe the element is inside a fixed navbar navbarFixedTop = getClosest(element,fixedTop), navbarFixedBottom = getClosest(element,fixedBottom); // set options options = options || {}; this[animation] = options[animation] && options[animation] !== fade ? options[animation] : animationData || fade; this[placement] = options[placement] ? options[placement] : placementData || top; this[delay] = parseInt(options[delay] || delayData) || 200; this[container] = queryElement(options[container]) ? queryElement(options[container]) : queryElement(containerData) ? queryElement(containerData) : navbarFixedTop ? navbarFixedTop : navbarFixedBottom ? navbarFixedBottom : modal ? modal : body; // bind, event targets, title and constants var self = this, timer = 0, placementSetting = this[placement], tooltip = null, titleString = element[getAttribute](title) || element[getAttribute](dataOriginalTitle); if ( !titleString ) return; // invalidate // private methods var removeToolTip = function() { self[container].removeChild(tooltip); tooltip = null; timer = null; }, createToolTip = function() { titleString = element[getAttribute](title) || element[getAttribute](dataOriginalTitle); // read the title again tooltip = document.createElement(div); tooltip[setAttribute]('role',component); var tooltipInner = document.createElement(div); tooltipInner[setAttribute](classString,component+'-inner'); tooltip.appendChild(tooltipInner); tooltipInner.innerHTML = titleString; self[container].appendChild(tooltip); tooltip[setAttribute](classString, component + ' ' + component+'-'+placementSetting + ' ' + self[animation]); }, updateTooltip = function () { styleTip(element,tooltip,placementSetting,self[container]); if (!isElementInViewport(tooltip) ) { placementSetting = updatePlacement(placementSetting); styleTip(element,tooltip,placementSetting,self[container]); } }, showTooltip = function () { !hasClass(tooltip,showClass) && ( addClass(tooltip,showClass) ); }; // public methods this.show = function() { clearTimeout(timer); timer = setTimeout( function() { if (tooltip === null) { placementSetting = self[placement]; // we reset placement in all cases createToolTip(); updateTooltip(); showTooltip(); bootstrapCustomEvent.call(element, showEvent, component); emulateTransitionEnd(tooltip, function() { bootstrapCustomEvent.call(element, shownEvent, component); }); } }, 20 ); }; this.hide = function() { clearTimeout(timer); timer = setTimeout( function() { if (tooltip && tooltip !== null && hasClass(tooltip,showClass)) { bootstrapCustomEvent.call(element, hideEvent, component); removeClass(tooltip,showClass); emulateTransitionEnd(tooltip, function() { removeToolTip(); bootstrapCustomEvent.call(element, hiddenEvent, component); }); } }, self[delay]); }; this.toggle = function() { if (!tooltip) { self.show(); } else { self.hide(); } }; // init if ( !(stringTooltip in element) ) { // prevent adding event handlers twice element[setAttribute](dataOriginalTitle,titleString); element.removeAttribute(title); on(element, mouseHover[0], this.show); on(element, mouseHover[1], this.hide); } element[stringTooltip] = this; }; // TOOLTIP DATA API // ================= initializeDataAPI(stringTooltip, Tooltip, dataToggle); return { Alert: Alert, Button: Button, Carousel: Carousel, Collapse: Collapse, Dropdown: Dropdown, Modal: Modal, Popover: Popover, ScrollSpy: ScrollSpy, Tab: Tab, Tooltip: Tooltip }; }));
ajax/libs/antd/3.3.3/antd.min.js
ahocevar/cdnjs
/*! * * antd v3.3.3 * * Copyright 2015-present, Alipay, Inc. * All rights reserved. * */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom"),require("moment")):"function"==typeof define&&define.amd?define(["react","react-dom","moment"],t):"object"==typeof exports?exports.antd=t(require("react"),require("react-dom"),require("moment")):e.antd=t(e.React,e.ReactDOM,e.moment)}("undefined"!=typeof self?self:this,function(e,t,n){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=569)}([function(t,n){t.exports=e},function(e,t,n){"use strict";t.__esModule=!0;var r=n(256),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=o.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";t.__esModule=!0;var r=n(19),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,o.default)(t))&&"function"!=typeof t?e:t}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(282),i=r(o),a=n(286),s=r(a),l=n(19),u=r(l);t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,u.default)(t)));e.prototype=(0,s.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i.default?(0,i.default)(e,t):e.__proto__=t)}},function(e,t,n){e.exports=n(289)()},function(e,t,n){var r,o;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var a in r)i.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;void 0!==e&&e.exports?e.exports=n:(r=[],void 0!==(o=function(){return n}.apply(t,r))&&(e.exports=o))}()},function(e,t,n){"use strict";t.__esModule=!0;var r=n(165),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),(0,o.default)(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}()},function(e,t,n){"use strict";t.__esModule=!0;var r=n(165),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e,t,n){return t in e?(0,o.default)(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,n){e.exports=t},function(e,t,n){"use strict";function r(e,t,n,r,i,a,s,l){if(o(t),!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,i,a,s,l],p=0;u=new Error(t.replace(/%s/g,function(){return c[p++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}}var o=function(e){};e.exports=r},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){"use strict";function e(e,t){t&&(e.prototype=Object.create(t.prototype)),e.prototype.constructor=e}function t(e){return i(e)?e:N(e)}function n(e){return a(e)?e:P(e)}function r(e){return s(e)?e:M(e)}function o(e){return i(e)&&!l(e)?e:D(e)}function i(e){return!(!e||!e[un])}function a(e){return!(!e||!e[cn])}function s(e){return!(!e||!e[pn])}function l(e){return a(e)||s(e)}function u(e){return!(!e||!e[fn])}function c(e){return e.value=!1,e}function p(e){e&&(e.value=!0)}function f(){}function d(e,t){t=t||0;for(var n=Math.max(0,e.length-t),r=new Array(n),o=0;o<n;o++)r[o]=e[o+t];return r}function h(e){return void 0===e.size&&(e.size=e.__iterate(m)),e.size}function v(e,t){if("number"!=typeof t){var n=t>>>0;if(""+n!==t||4294967295===n)return NaN;t=n}return t<0?h(e)+t:t}function m(){return!0}function y(e,t,n){return(0===e||void 0!==n&&e<=-n)&&(void 0===t||void 0!==n&&t>=n)}function g(e,t){return C(e,t,0)}function b(e,t){return C(e,t,t)}function C(e,t,n){return void 0===e?n:e<0?Math.max(0,t+e):void 0===t?e:Math.min(t,e)}function w(e){this.next=e}function S(e,t,n,r){var o=0===e?t:1===e?n:[t,n];return r?r.value=o:r={value:o,done:!1},r}function x(){return{value:void 0,done:!0}}function _(e){return!!O(e)}function k(e){return e&&"function"==typeof e.next}function E(e){var t=O(e);return t&&t.call(e)}function O(e){var t=e&&(Sn&&e[Sn]||e[xn]);if("function"==typeof t)return t}function T(e){return e&&"number"==typeof e.length}function N(e){return null===e||void 0===e?K():i(e)?e.toSeq():z(e)}function P(e){return null===e||void 0===e?K().toKeyedSeq():i(e)?a(e)?e.toSeq():e.fromEntrySeq():F(e)}function M(e){return null===e||void 0===e?K():i(e)?a(e)?e.entrySeq():e.toIndexedSeq():V(e)}function D(e){return(null===e||void 0===e?K():i(e)?a(e)?e.entrySeq():e:V(e)).toSetSeq()}function I(e){this._array=e,this.size=e.length}function A(e){var t=Object.keys(e);this._object=e,this._keys=t,this.size=t.length}function j(e){this._iterable=e,this.size=e.length||e.size}function R(e){this._iterator=e,this._iteratorCache=[]}function L(e){return!(!e||!e[kn])}function K(){return En||(En=new I([]))}function F(e){var t=Array.isArray(e)?new I(e).fromEntrySeq():k(e)?new R(e).fromEntrySeq():_(e)?new j(e).fromEntrySeq():"object"==typeof e?new A(e):void 0;if(!t)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+e);return t}function V(e){var t=B(e);if(!t)throw new TypeError("Expected Array or iterable object of values: "+e);return t}function z(e){var t=B(e)||"object"==typeof e&&new A(e);if(!t)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+e);return t}function B(e){return T(e)?new I(e):k(e)?new R(e):_(e)?new j(e):void 0}function W(e,t,n,r){var o=e._cache;if(o){for(var i=o.length-1,a=0;a<=i;a++){var s=o[n?i-a:a];if(!1===t(s[1],r?s[0]:a,e))return a+1}return a}return e.__iterateUncached(t,n)}function H(e,t,n,r){var o=e._cache;if(o){var i=o.length-1,a=0;return new w(function(){var e=o[n?i-a:a];return a++>i?x():S(t,r?e[0]:a-1,e[1])})}return e.__iteratorUncached(t,n)}function U(e,t){return t?q(t,e,"",{"":e}):Y(e)}function q(e,t,n,r){return Array.isArray(t)?e.call(r,n,M(t).map(function(n,r){return q(e,n,r,t)})):G(t)?e.call(r,n,P(t).map(function(n,r){return q(e,n,r,t)})):t}function Y(e){return Array.isArray(e)?M(e).map(Y).toList():G(e)?P(e).map(Y).toMap():e}function G(e){return e&&(e.constructor===Object||void 0===e.constructor)}function X(e,t){if(e===t||e!==e&&t!==t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if(e=e.valueOf(),t=t.valueOf(),e===t||e!==e&&t!==t)return!0;if(!e||!t)return!1}return!("function"!=typeof e.equals||"function"!=typeof t.equals||!e.equals(t))}function $(e,t){if(e===t)return!0;if(!i(t)||void 0!==e.size&&void 0!==t.size&&e.size!==t.size||void 0!==e.__hash&&void 0!==t.__hash&&e.__hash!==t.__hash||a(e)!==a(t)||s(e)!==s(t)||u(e)!==u(t))return!1;if(0===e.size&&0===t.size)return!0;var n=!l(e);if(u(e)){var r=e.entries();return t.every(function(e,t){var o=r.next().value;return o&&X(o[1],e)&&(n||X(o[0],t))})&&r.next().done}var o=!1;if(void 0===e.size)if(void 0===t.size)"function"==typeof e.cacheResult&&e.cacheResult();else{o=!0;var c=e;e=t,t=c}var p=!0,f=t.__iterate(function(t,r){if(n?!e.has(t):o?!X(t,e.get(r,mn)):!X(e.get(r,mn),t))return p=!1,!1});return p&&e.size===f}function J(e,t){if(!(this instanceof J))return new J(e,t);if(this._value=e,this.size=void 0===t?1/0:Math.max(0,t),0===this.size){if(On)return On;On=this}}function Z(e,t){if(!e)throw new Error(t)}function Q(e,t,n){if(!(this instanceof Q))return new Q(e,t,n);if(Z(0!==n,"Cannot step a Range by 0"),e=e||0,void 0===t&&(t=1/0),n=void 0===n?1:Math.abs(n),t<e&&(n=-n),this._start=e,this._end=t,this._step=n,this.size=Math.max(0,Math.ceil((t-e)/n-1)+1),0===this.size){if(Tn)return Tn;Tn=this}}function ee(){throw TypeError("Abstract")}function te(){}function ne(){}function re(){}function oe(e){return e>>>1&1073741824|3221225471&e}function ie(e){if(!1===e||null===e||void 0===e)return 0;if("function"==typeof e.valueOf&&(!1===(e=e.valueOf())||null===e||void 0===e))return 0;if(!0===e)return 1;var t=typeof e;if("number"===t){var n=0|e;for(n!==e&&(n^=4294967295*e);e>4294967295;)e/=4294967295,n^=e;return oe(n)}if("string"===t)return e.length>Rn?ae(e):se(e);if("function"==typeof e.hashCode)return e.hashCode();if("object"===t)return le(e);if("function"==typeof e.toString)return se(e.toString());throw new Error("Value type "+t+" cannot be hashed.")}function ae(e){var t=Fn[e];return void 0===t&&(t=se(e),Kn===Ln&&(Kn=0,Fn={}),Kn++,Fn[e]=t),t}function se(e){for(var t=0,n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return oe(t)}function le(e){var t;if(In&&void 0!==(t=Nn.get(e)))return t;if(void 0!==(t=e[jn]))return t;if(!Dn){if(void 0!==(t=e.propertyIsEnumerable&&e.propertyIsEnumerable[jn]))return t;if(void 0!==(t=ue(e)))return t}if(t=++An,1073741824&An&&(An=0),In)Nn.set(e,t);else{if(void 0!==Mn&&!1===Mn(e))throw new Error("Non-extensible objects are not allowed as keys.");if(Dn)Object.defineProperty(e,jn,{enumerable:!1,configurable:!1,writable:!1,value:t});else if(void 0!==e.propertyIsEnumerable&&e.propertyIsEnumerable===e.constructor.prototype.propertyIsEnumerable)e.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},e.propertyIsEnumerable[jn]=t;else{if(void 0===e.nodeType)throw new Error("Unable to set a non-enumerable property on object.");e[jn]=t}}return t}function ue(e){if(e&&e.nodeType>0)switch(e.nodeType){case 1:return e.uniqueID;case 9:return e.documentElement&&e.documentElement.uniqueID}}function ce(e){Z(e!==1/0,"Cannot perform this action with an infinite size.")}function pe(e){return null===e||void 0===e?Se():fe(e)&&!u(e)?e:Se().withMutations(function(t){var r=n(e);ce(r.size),r.forEach(function(e,n){return t.set(n,e)})})}function fe(e){return!(!e||!e[Vn])}function de(e,t){this.ownerID=e,this.entries=t}function he(e,t,n){this.ownerID=e,this.bitmap=t,this.nodes=n}function ve(e,t,n){this.ownerID=e,this.count=t,this.nodes=n}function me(e,t,n){this.ownerID=e,this.keyHash=t,this.entries=n}function ye(e,t,n){this.ownerID=e,this.keyHash=t,this.entry=n}function ge(e,t,n){this._type=t,this._reverse=n,this._stack=e._root&&Ce(e._root)}function be(e,t){return S(e,t[0],t[1])}function Ce(e,t){return{node:e,index:0,__prev:t}}function we(e,t,n,r){var o=Object.create(zn);return o.size=e,o._root=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function Se(){return Bn||(Bn=we(0))}function xe(e,t,n){var r,o;if(e._root){var i=c(yn),a=c(gn);if(r=_e(e._root,e.__ownerID,0,void 0,t,n,i,a),!a.value)return e;o=e.size+(i.value?n===mn?-1:1:0)}else{if(n===mn)return e;o=1,r=new de(e.__ownerID,[[t,n]])}return e.__ownerID?(e.size=o,e._root=r,e.__hash=void 0,e.__altered=!0,e):r?we(o,r):Se()}function _e(e,t,n,r,o,i,a,s){return e?e.update(t,n,r,o,i,a,s):i===mn?e:(p(s),p(a),new ye(t,r,[o,i]))}function ke(e){return e.constructor===ye||e.constructor===me}function Ee(e,t,n,r,o){if(e.keyHash===r)return new me(t,r,[e.entry,o]);var i,a=(0===n?e.keyHash:e.keyHash>>>n)&vn,s=(0===n?r:r>>>n)&vn;return new he(t,1<<a|1<<s,a===s?[Ee(e,t,n+dn,r,o)]:(i=new ye(t,r,o),a<s?[e,i]:[i,e]))}function Oe(e,t,n,r){e||(e=new f);for(var o=new ye(e,ie(n),[n,r]),i=0;i<t.length;i++){var a=t[i];o=o.update(e,0,void 0,a[0],a[1])}return o}function Te(e,t,n,r){for(var o=0,i=0,a=new Array(n),s=0,l=1,u=t.length;s<u;s++,l<<=1){var c=t[s];void 0!==c&&s!==r&&(o|=l,a[i++]=c)}return new he(e,o,a)}function Ne(e,t,n,r,o){for(var i=0,a=new Array(hn),s=0;0!==n;s++,n>>>=1)a[s]=1&n?t[i++]:void 0;return a[r]=o,new ve(e,i+1,a)}function Pe(e,t,r){for(var o=[],a=0;a<r.length;a++){var s=r[a],l=n(s);i(s)||(l=l.map(function(e){return U(e)})),o.push(l)}return Ie(e,t,o)}function Me(e,t,n){return e&&e.mergeDeep&&i(t)?e.mergeDeep(t):X(e,t)?e:t}function De(e){return function(t,n,r){if(t&&t.mergeDeepWith&&i(n))return t.mergeDeepWith(e,n);var o=e(t,n,r);return X(t,o)?t:o}}function Ie(e,t,n){return n=n.filter(function(e){return 0!==e.size}),0===n.length?e:0!==e.size||e.__ownerID||1!==n.length?e.withMutations(function(e){for(var r=t?function(n,r){e.update(r,mn,function(e){return e===mn?n:t(e,n,r)})}:function(t,n){e.set(n,t)},o=0;o<n.length;o++)n[o].forEach(r)}):e.constructor(n[0])}function Ae(e,t,n,r){var o=e===mn,i=t.next();if(i.done){var a=o?n:e,s=r(a);return s===a?e:s}Z(o||e&&e.set,"invalid keyPath");var l=i.value,u=o?mn:e.get(l,mn),c=Ae(u,t,n,r);return c===u?e:c===mn?e.remove(l):(o?Se():e).set(l,c)}function je(e){return e-=e>>1&1431655765,e=(858993459&e)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,127&(e+=e>>16)}function Re(e,t,n,r){var o=r?e:d(e);return o[t]=n,o}function Le(e,t,n,r){var o=e.length+1;if(r&&t+1===o)return e[t]=n,e;for(var i=new Array(o),a=0,s=0;s<o;s++)s===t?(i[s]=n,a=-1):i[s]=e[s+a];return i}function Ke(e,t,n){var r=e.length-1;if(n&&t===r)return e.pop(),e;for(var o=new Array(r),i=0,a=0;a<r;a++)a===t&&(i=1),o[a]=e[a+i];return o}function Fe(e){var t=He();if(null===e||void 0===e)return t;if(Ve(e))return e;var n=r(e),o=n.size;return 0===o?t:(ce(o),o>0&&o<hn?We(0,o,dn,null,new ze(n.toArray())):t.withMutations(function(e){e.setSize(o),n.forEach(function(t,n){return e.set(n,t)})}))}function Ve(e){return!(!e||!e[qn])}function ze(e,t){this.array=e,this.ownerID=t}function Be(e,t){function n(e,t,n){return 0===t?r(e,n):o(e,t,n)}function r(e,n){var r=n===s?l&&l.array:e&&e.array,o=n>i?0:i-n,u=a-n;return u>hn&&(u=hn),function(){if(o===u)return Xn;var e=t?--u:o++;return r&&r[e]}}function o(e,r,o){var s,l=e&&e.array,u=o>i?0:i-o>>r,c=1+(a-o>>r);return c>hn&&(c=hn),function(){for(;;){if(s){var e=s();if(e!==Xn)return e;s=null}if(u===c)return Xn;var i=t?--c:u++;s=n(l&&l[i],r-dn,o+(i<<r))}}}var i=e._origin,a=e._capacity,s=Je(a),l=e._tail;return n(e._root,e._level,0)}function We(e,t,n,r,o,i,a){var s=Object.create(Yn);return s.size=t-e,s._origin=e,s._capacity=t,s._level=n,s._root=r,s._tail=o,s.__ownerID=i,s.__hash=a,s.__altered=!1,s}function He(){return Gn||(Gn=We(0,0,dn))}function Ue(e,t,n){if((t=v(e,t))!==t)return e;if(t>=e.size||t<0)return e.withMutations(function(e){t<0?Xe(e,t).set(0,n):Xe(e,0,t+1).set(t,n)});t+=e._origin;var r=e._tail,o=e._root,i=c(gn);return t>=Je(e._capacity)?r=qe(r,e.__ownerID,0,t,n,i):o=qe(o,e.__ownerID,e._level,t,n,i),i.value?e.__ownerID?(e._root=o,e._tail=r,e.__hash=void 0,e.__altered=!0,e):We(e._origin,e._capacity,e._level,o,r):e}function qe(e,t,n,r,o,i){var a=r>>>n&vn,s=e&&a<e.array.length;if(!s&&void 0===o)return e;var l;if(n>0){var u=e&&e.array[a],c=qe(u,t,n-dn,r,o,i);return c===u?e:(l=Ye(e,t),l.array[a]=c,l)}return s&&e.array[a]===o?e:(p(i),l=Ye(e,t),void 0===o&&a===l.array.length-1?l.array.pop():l.array[a]=o,l)}function Ye(e,t){return t&&e&&t===e.ownerID?e:new ze(e?e.array.slice():[],t)}function Ge(e,t){if(t>=Je(e._capacity))return e._tail;if(t<1<<e._level+dn){for(var n=e._root,r=e._level;n&&r>0;)n=n.array[t>>>r&vn],r-=dn;return n}}function Xe(e,t,n){void 0!==t&&(t|=0),void 0!==n&&(n|=0);var r=e.__ownerID||new f,o=e._origin,i=e._capacity,a=o+t,s=void 0===n?i:n<0?i+n:o+n;if(a===o&&s===i)return e;if(a>=s)return e.clear();for(var l=e._level,u=e._root,c=0;a+c<0;)u=new ze(u&&u.array.length?[void 0,u]:[],r),l+=dn,c+=1<<l;c&&(a+=c,o+=c,s+=c,i+=c);for(var p=Je(i),d=Je(s);d>=1<<l+dn;)u=new ze(u&&u.array.length?[u]:[],r),l+=dn;var h=e._tail,v=d<p?Ge(e,s-1):d>p?new ze([],r):h;if(h&&d>p&&a<i&&h.array.length){u=Ye(u,r);for(var m=u,y=l;y>dn;y-=dn){var g=p>>>y&vn;m=m.array[g]=Ye(m.array[g],r)}m.array[p>>>dn&vn]=h}if(s<i&&(v=v&&v.removeAfter(r,0,s)),a>=d)a-=d,s-=d,l=dn,u=null,v=v&&v.removeBefore(r,0,a);else if(a>o||d<p){for(c=0;u;){var b=a>>>l&vn;if(b!==d>>>l&vn)break;b&&(c+=(1<<l)*b),l-=dn,u=u.array[b]}u&&a>o&&(u=u.removeBefore(r,l,a-c)),u&&d<p&&(u=u.removeAfter(r,l,d-c)),c&&(a-=c,s-=c)}return e.__ownerID?(e.size=s-a,e._origin=a,e._capacity=s,e._level=l,e._root=u,e._tail=v,e.__hash=void 0,e.__altered=!0,e):We(a,s,l,u,v)}function $e(e,t,n){for(var o=[],a=0,s=0;s<n.length;s++){var l=n[s],u=r(l);u.size>a&&(a=u.size),i(l)||(u=u.map(function(e){return U(e)})),o.push(u)}return a>e.size&&(e=e.setSize(a)),Ie(e,t,o)}function Je(e){return e<hn?0:e-1>>>dn<<dn}function Ze(e){return null===e||void 0===e?tt():Qe(e)?e:tt().withMutations(function(t){var r=n(e);ce(r.size),r.forEach(function(e,n){return t.set(n,e)})})}function Qe(e){return fe(e)&&u(e)}function et(e,t,n,r){var o=Object.create(Ze.prototype);return o.size=e?e.size:0,o._map=e,o._list=t,o.__ownerID=n,o.__hash=r,o}function tt(){return $n||($n=et(Se(),He()))}function nt(e,t,n){var r,o,i=e._map,a=e._list,s=i.get(t),l=void 0!==s;if(n===mn){if(!l)return e;a.size>=hn&&a.size>=2*i.size?(o=a.filter(function(e,t){return void 0!==e&&s!==t}),r=o.toKeyedSeq().map(function(e){return e[0]}).flip().toMap(),e.__ownerID&&(r.__ownerID=o.__ownerID=e.__ownerID)):(r=i.remove(t),o=s===a.size-1?a.pop():a.set(s,void 0))}else if(l){if(n===a.get(s)[1])return e;r=i,o=a.set(s,[t,n])}else r=i.set(t,a.size),o=a.set(a.size,[t,n]);return e.__ownerID?(e.size=r.size,e._map=r,e._list=o,e.__hash=void 0,e):et(r,o)}function rt(e,t){this._iter=e,this._useKeys=t,this.size=e.size}function ot(e){this._iter=e,this.size=e.size}function it(e){this._iter=e,this.size=e.size}function at(e){this._iter=e,this.size=e.size}function st(e){var t=Tt(e);return t._iter=e,t.size=e.size,t.flip=function(){return e},t.reverse=function(){var t=e.reverse.apply(this);return t.flip=function(){return e.reverse()},t},t.has=function(t){return e.includes(t)},t.includes=function(t){return e.has(t)},t.cacheResult=Nt,t.__iterateUncached=function(t,n){var r=this;return e.__iterate(function(e,n){return!1!==t(n,e,r)},n)},t.__iteratorUncached=function(t,n){if(t===wn){var r=e.__iterator(t,n);return new w(function(){var e=r.next();if(!e.done){var t=e.value[0];e.value[0]=e.value[1],e.value[1]=t}return e})}return e.__iterator(t===Cn?bn:Cn,n)},t}function lt(e,t,n){var r=Tt(e);return r.size=e.size,r.has=function(t){return e.has(t)},r.get=function(r,o){var i=e.get(r,mn);return i===mn?o:t.call(n,i,r,e)},r.__iterateUncached=function(r,o){var i=this;return e.__iterate(function(e,o,a){return!1!==r(t.call(n,e,o,a),o,i)},o)},r.__iteratorUncached=function(r,o){var i=e.__iterator(wn,o);return new w(function(){var o=i.next();if(o.done)return o;var a=o.value,s=a[0];return S(r,s,t.call(n,a[1],s,e),o)})},r}function ut(e,t){var n=Tt(e);return n._iter=e,n.size=e.size,n.reverse=function(){return e},e.flip&&(n.flip=function(){var t=st(e);return t.reverse=function(){return e.flip()},t}),n.get=function(n,r){return e.get(t?n:-1-n,r)},n.has=function(n){return e.has(t?n:-1-n)},n.includes=function(t){return e.includes(t)},n.cacheResult=Nt,n.__iterate=function(t,n){var r=this;return e.__iterate(function(e,n){return t(e,n,r)},!n)},n.__iterator=function(t,n){return e.__iterator(t,!n)},n}function ct(e,t,n,r){var o=Tt(e);return r&&(o.has=function(r){var o=e.get(r,mn);return o!==mn&&!!t.call(n,o,r,e)},o.get=function(r,o){var i=e.get(r,mn);return i!==mn&&t.call(n,i,r,e)?i:o}),o.__iterateUncached=function(o,i){var a=this,s=0;return e.__iterate(function(e,i,l){if(t.call(n,e,i,l))return s++,o(e,r?i:s-1,a)},i),s},o.__iteratorUncached=function(o,i){var a=e.__iterator(wn,i),s=0;return new w(function(){for(;;){var i=a.next();if(i.done)return i;var l=i.value,u=l[0],c=l[1];if(t.call(n,c,u,e))return S(o,r?u:s++,c,i)}})},o}function pt(e,t,n){var r=pe().asMutable();return e.__iterate(function(o,i){r.update(t.call(n,o,i,e),0,function(e){return e+1})}),r.asImmutable()}function ft(e,t,n){var r=a(e),o=(u(e)?Ze():pe()).asMutable();e.__iterate(function(i,a){o.update(t.call(n,i,a,e),function(e){return e=e||[],e.push(r?[a,i]:i),e})});var i=Ot(e);return o.map(function(t){return _t(e,i(t))})}function dt(e,t,n,r){var o=e.size;if(void 0!==t&&(t|=0),void 0!==n&&(n|=0),y(t,n,o))return e;var i=g(t,o),a=b(n,o);if(i!==i||a!==a)return dt(e.toSeq().cacheResult(),t,n,r);var s,l=a-i;l===l&&(s=l<0?0:l);var u=Tt(e);return u.size=0===s?s:e.size&&s||void 0,!r&&L(e)&&s>=0&&(u.get=function(t,n){return t=v(this,t),t>=0&&t<s?e.get(t+i,n):n}),u.__iterateUncached=function(t,n){var o=this;if(0===s)return 0;if(n)return this.cacheResult().__iterate(t,n);var a=0,l=!0,u=0;return e.__iterate(function(e,n){if(!l||!(l=a++<i))return u++,!1!==t(e,r?n:u-1,o)&&u!==s}),u},u.__iteratorUncached=function(t,n){if(0!==s&&n)return this.cacheResult().__iterator(t,n);var o=0!==s&&e.__iterator(t,n),a=0,l=0;return new w(function(){for(;a++<i;)o.next();if(++l>s)return x();var e=o.next();return r||t===Cn?e:t===bn?S(t,l-1,void 0,e):S(t,l-1,e.value[1],e)})},u}function ht(e,t,n){var r=Tt(e);return r.__iterateUncached=function(r,o){var i=this;if(o)return this.cacheResult().__iterate(r,o);var a=0;return e.__iterate(function(e,o,s){return t.call(n,e,o,s)&&++a&&r(e,o,i)}),a},r.__iteratorUncached=function(r,o){var i=this;if(o)return this.cacheResult().__iterator(r,o);var a=e.__iterator(wn,o),s=!0;return new w(function(){if(!s)return x();var e=a.next();if(e.done)return e;var o=e.value,l=o[0],u=o[1];return t.call(n,u,l,i)?r===wn?e:S(r,l,u,e):(s=!1,x())})},r}function vt(e,t,n,r){var o=Tt(e);return o.__iterateUncached=function(o,i){var a=this;if(i)return this.cacheResult().__iterate(o,i);var s=!0,l=0;return e.__iterate(function(e,i,u){if(!s||!(s=t.call(n,e,i,u)))return l++,o(e,r?i:l-1,a)}),l},o.__iteratorUncached=function(o,i){var a=this;if(i)return this.cacheResult().__iterator(o,i);var s=e.__iterator(wn,i),l=!0,u=0;return new w(function(){var e,i,c;do{if(e=s.next(),e.done)return r||o===Cn?e:o===bn?S(o,u++,void 0,e):S(o,u++,e.value[1],e);var p=e.value;i=p[0],c=p[1],l&&(l=t.call(n,c,i,a))}while(l);return o===wn?e:S(o,i,c,e)})},o}function mt(e,t){var r=a(e),o=[e].concat(t).map(function(e){return i(e)?r&&(e=n(e)):e=r?F(e):V(Array.isArray(e)?e:[e]),e}).filter(function(e){return 0!==e.size});if(0===o.length)return e;if(1===o.length){var l=o[0];if(l===e||r&&a(l)||s(e)&&s(l))return l}var u=new I(o);return r?u=u.toKeyedSeq():s(e)||(u=u.toSetSeq()),u=u.flatten(!0),u.size=o.reduce(function(e,t){if(void 0!==e){var n=t.size;if(void 0!==n)return e+n}},0),u}function yt(e,t,n){var r=Tt(e);return r.__iterateUncached=function(r,o){function a(e,u){var c=this;e.__iterate(function(e,o){return(!t||u<t)&&i(e)?a(e,u+1):!1===r(e,n?o:s++,c)&&(l=!0),!l},o)}var s=0,l=!1;return a(e,0),s},r.__iteratorUncached=function(r,o){var a=e.__iterator(r,o),s=[],l=0;return new w(function(){for(;a;){var e=a.next();if(!1===e.done){var u=e.value;if(r===wn&&(u=u[1]),t&&!(s.length<t)||!i(u))return n?e:S(r,l++,u,e);s.push(a),a=u.__iterator(r,o)}else a=s.pop()}return x()})},r}function gt(e,t,n){var r=Ot(e);return e.toSeq().map(function(o,i){return r(t.call(n,o,i,e))}).flatten(!0)}function bt(e,t){var n=Tt(e);return n.size=e.size&&2*e.size-1,n.__iterateUncached=function(n,r){var o=this,i=0;return e.__iterate(function(e,r){return(!i||!1!==n(t,i++,o))&&!1!==n(e,i++,o)},r),i},n.__iteratorUncached=function(n,r){var o,i=e.__iterator(Cn,r),a=0;return new w(function(){return(!o||a%2)&&(o=i.next(),o.done)?o:a%2?S(n,a++,t):S(n,a++,o.value,o)})},n}function Ct(e,t,n){t||(t=Pt);var r=a(e),o=0,i=e.toSeq().map(function(t,r){return[r,t,o++,n?n(t,r,e):t]}).toArray();return i.sort(function(e,n){return t(e[3],n[3])||e[2]-n[2]}).forEach(r?function(e,t){i[t].length=2}:function(e,t){i[t]=e[1]}),r?P(i):s(e)?M(i):D(i)}function wt(e,t,n){if(t||(t=Pt),n){var r=e.toSeq().map(function(t,r){return[t,n(t,r,e)]}).reduce(function(e,n){return St(t,e[1],n[1])?n:e});return r&&r[0]}return e.reduce(function(e,n){return St(t,e,n)?n:e})}function St(e,t,n){var r=e(n,t);return 0===r&&n!==t&&(void 0===n||null===n||n!==n)||r>0}function xt(e,n,r){var o=Tt(e);return o.size=new I(r).map(function(e){return e.size}).min(),o.__iterate=function(e,t){for(var n,r=this.__iterator(Cn,t),o=0;!(n=r.next()).done&&!1!==e(n.value,o++,this););return o},o.__iteratorUncached=function(e,o){var i=r.map(function(e){return e=t(e),E(o?e.reverse():e)}),a=0,s=!1;return new w(function(){var t;return s||(t=i.map(function(e){return e.next()}),s=t.some(function(e){return e.done})),s?x():S(e,a++,n.apply(null,t.map(function(e){return e.value})))})},o}function _t(e,t){return L(e)?t:e.constructor(t)}function kt(e){if(e!==Object(e))throw new TypeError("Expected [K, V] tuple: "+e)}function Et(e){return ce(e.size),h(e)}function Ot(e){return a(e)?n:s(e)?r:o}function Tt(e){return Object.create((a(e)?P:s(e)?M:D).prototype)}function Nt(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):N.prototype.cacheResult.call(this)}function Pt(e,t){return e>t?1:e<t?-1:0}function Mt(e){var n=E(e);if(!n){if(!T(e))throw new TypeError("Expected iterable or array-like: "+e);n=E(t(e))}return n}function Dt(e,t){var n,r=function(i){if(i instanceof r)return i;if(!(this instanceof r))return new r(i);if(!n){n=!0;var a=Object.keys(e);jt(o,a),o.size=a.length,o._name=t,o._keys=a,o._defaultValues=e}this._map=pe(i)},o=r.prototype=Object.create(Jn);return o.constructor=r,r}function It(e,t,n){var r=Object.create(Object.getPrototypeOf(e));return r._map=t,r.__ownerID=n,r}function At(e){return e._name||e.constructor.name||"Record"}function jt(e,t){try{t.forEach(Rt.bind(void 0,e))}catch(e){}}function Rt(e,t){Object.defineProperty(e,t,{get:function(){return this.get(t)},set:function(e){Z(this.__ownerID,"Cannot set on an immutable record."),this.set(t,e)}})}function Lt(e){return null===e||void 0===e?zt():Kt(e)&&!u(e)?e:zt().withMutations(function(t){var n=o(e);ce(n.size),n.forEach(function(e){return t.add(e)})})}function Kt(e){return!(!e||!e[Zn])}function Ft(e,t){return e.__ownerID?(e.size=t.size,e._map=t,e):t===e._map?e:0===t.size?e.__empty():e.__make(t)}function Vt(e,t){var n=Object.create(Qn);return n.size=e?e.size:0,n._map=e,n.__ownerID=t,n}function zt(){return er||(er=Vt(Se()))}function Bt(e){return null===e||void 0===e?Ut():Wt(e)?e:Ut().withMutations(function(t){var n=o(e);ce(n.size),n.forEach(function(e){return t.add(e)})})}function Wt(e){return Kt(e)&&u(e)}function Ht(e,t){var n=Object.create(tr);return n.size=e?e.size:0,n._map=e,n.__ownerID=t,n}function Ut(){return nr||(nr=Ht(tt()))}function qt(e){return null===e||void 0===e?Xt():Yt(e)?e:Xt().unshiftAll(e)}function Yt(e){return!(!e||!e[rr])}function Gt(e,t,n,r){var o=Object.create(or);return o.size=e,o._head=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function Xt(){return ir||(ir=Gt(0))}function $t(e,t){var n=function(n){e.prototype[n]=t[n]};return Object.keys(t).forEach(n),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach(n),e}function Jt(e,t){return t}function Zt(e,t){return[t,e]}function Qt(e){return function(){return!e.apply(this,arguments)}}function en(e){return function(){return-e.apply(this,arguments)}}function tn(e){return"string"==typeof e?JSON.stringify(e):e}function nn(){return d(arguments)}function rn(e,t){return e<t?1:e>t?-1:0}function on(e){if(e.size===1/0)return 0;var t=u(e),n=a(e),r=t?1:0;return an(e.__iterate(n?t?function(e,t){r=31*r+sn(ie(e),ie(t))|0}:function(e,t){r=r+sn(ie(e),ie(t))|0}:t?function(e){r=31*r+ie(e)|0}:function(e){r=r+ie(e)|0}),r)}function an(e,t){return t=Pn(t,3432918353),t=Pn(t<<15|t>>>-15,461845907),t=Pn(t<<13|t>>>-13,5),t=(t+3864292196|0)^e,t=Pn(t^t>>>16,2246822507),t=Pn(t^t>>>13,3266489909),t=oe(t^t>>>16)}function sn(e,t){return e^t+2654435769+(e<<6)+(e>>2)|0}var ln=Array.prototype.slice;e(n,t),e(r,t),e(o,t),t.isIterable=i,t.isKeyed=a,t.isIndexed=s,t.isAssociative=l,t.isOrdered=u,t.Keyed=n,t.Indexed=r,t.Set=o;var un="@@__IMMUTABLE_ITERABLE__@@",cn="@@__IMMUTABLE_KEYED__@@",pn="@@__IMMUTABLE_INDEXED__@@",fn="@@__IMMUTABLE_ORDERED__@@",dn=5,hn=1<<dn,vn=hn-1,mn={},yn={value:!1},gn={value:!1},bn=0,Cn=1,wn=2,Sn="function"==typeof Symbol&&Symbol.iterator,xn="@@iterator",_n=Sn||xn;w.prototype.toString=function(){return"[Iterator]"},w.KEYS=bn,w.VALUES=Cn,w.ENTRIES=wn,w.prototype.inspect=w.prototype.toSource=function(){return this.toString()},w.prototype[_n]=function(){return this},e(N,t),N.of=function(){return N(arguments)},N.prototype.toSeq=function(){return this},N.prototype.toString=function(){return this.__toString("Seq {","}")},N.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},N.prototype.__iterate=function(e,t){return W(this,e,t,!0)},N.prototype.__iterator=function(e,t){return H(this,e,t,!0)},e(P,N),P.prototype.toKeyedSeq=function(){return this},e(M,N),M.of=function(){return M(arguments)},M.prototype.toIndexedSeq=function(){return this},M.prototype.toString=function(){return this.__toString("Seq [","]")},M.prototype.__iterate=function(e,t){return W(this,e,t,!1)},M.prototype.__iterator=function(e,t){return H(this,e,t,!1)},e(D,N),D.of=function(){return D(arguments)},D.prototype.toSetSeq=function(){return this},N.isSeq=L,N.Keyed=P,N.Set=D,N.Indexed=M;var kn="@@__IMMUTABLE_SEQ__@@";N.prototype[kn]=!0,e(I,M),I.prototype.get=function(e,t){return this.has(e)?this._array[v(this,e)]:t},I.prototype.__iterate=function(e,t){for(var n=this._array,r=n.length-1,o=0;o<=r;o++)if(!1===e(n[t?r-o:o],o,this))return o+1;return o},I.prototype.__iterator=function(e,t){var n=this._array,r=n.length-1,o=0;return new w(function(){return o>r?x():S(e,o,n[t?r-o++:o++])})},e(A,P),A.prototype.get=function(e,t){return void 0===t||this.has(e)?this._object[e]:t},A.prototype.has=function(e){return this._object.hasOwnProperty(e)},A.prototype.__iterate=function(e,t){for(var n=this._object,r=this._keys,o=r.length-1,i=0;i<=o;i++){var a=r[t?o-i:i];if(!1===e(n[a],a,this))return i+1}return i},A.prototype.__iterator=function(e,t){var n=this._object,r=this._keys,o=r.length-1,i=0;return new w(function(){var a=r[t?o-i:i];return i++>o?x():S(e,a,n[a])})},A.prototype[fn]=!0,e(j,M),j.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var n=this._iterable,r=E(n),o=0;if(k(r))for(var i;!(i=r.next()).done&&!1!==e(i.value,o++,this););return o},j.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var n=this._iterable,r=E(n);if(!k(r))return new w(x);var o=0;return new w(function(){var t=r.next();return t.done?t:S(e,o++,t.value)})},e(R,M),R.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);for(var n=this._iterator,r=this._iteratorCache,o=0;o<r.length;)if(!1===e(r[o],o++,this))return o;for(var i;!(i=n.next()).done;){var a=i.value;if(r[o]=a,!1===e(a,o++,this))break}return o},R.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var n=this._iterator,r=this._iteratorCache,o=0;return new w(function(){if(o>=r.length){var t=n.next();if(t.done)return t;r[o]=t.value}return S(e,o,r[o++])})};var En;e(J,M),J.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},J.prototype.get=function(e,t){return this.has(e)?this._value:t},J.prototype.includes=function(e){return X(this._value,e)},J.prototype.slice=function(e,t){var n=this.size;return y(e,t,n)?this:new J(this._value,b(t,n)-g(e,n))},J.prototype.reverse=function(){return this},J.prototype.indexOf=function(e){return X(this._value,e)?0:-1},J.prototype.lastIndexOf=function(e){return X(this._value,e)?this.size:-1},J.prototype.__iterate=function(e,t){for(var n=0;n<this.size;n++)if(!1===e(this._value,n,this))return n+1;return n},J.prototype.__iterator=function(e,t){var n=this,r=0;return new w(function(){return r<n.size?S(e,r++,n._value):x()})},J.prototype.equals=function(e){return e instanceof J?X(this._value,e._value):$(e)};var On;e(Q,M),Q.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},Q.prototype.get=function(e,t){return this.has(e)?this._start+v(this,e)*this._step:t},Q.prototype.includes=function(e){var t=(e-this._start)/this._step;return t>=0&&t<this.size&&t===Math.floor(t)},Q.prototype.slice=function(e,t){return y(e,t,this.size)?this:(e=g(e,this.size),t=b(t,this.size),t<=e?new Q(0,0):new Q(this.get(e,this._end),this.get(t,this._end),this._step))},Q.prototype.indexOf=function(e){var t=e-this._start;if(t%this._step==0){var n=t/this._step;if(n>=0&&n<this.size)return n}return-1},Q.prototype.lastIndexOf=function(e){return this.indexOf(e)},Q.prototype.__iterate=function(e,t){for(var n=this.size-1,r=this._step,o=t?this._start+n*r:this._start,i=0;i<=n;i++){if(!1===e(o,i,this))return i+1;o+=t?-r:r}return i},Q.prototype.__iterator=function(e,t){var n=this.size-1,r=this._step,o=t?this._start+n*r:this._start,i=0;return new w(function(){var a=o;return o+=t?-r:r,i>n?x():S(e,i++,a)})},Q.prototype.equals=function(e){return e instanceof Q?this._start===e._start&&this._end===e._end&&this._step===e._step:$(this,e)};var Tn;e(ee,t),e(te,ee),e(ne,ee),e(re,ee),ee.Keyed=te,ee.Indexed=ne,ee.Set=re;var Nn,Pn="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(e,t){e|=0,t|=0;var n=65535&e,r=65535&t;return n*r+((e>>>16)*r+n*(t>>>16)<<16>>>0)|0},Mn=Object.isExtensible,Dn=function(){try{return Object.defineProperty({},"@",{}),!0}catch(e){return!1}}(),In="function"==typeof WeakMap;In&&(Nn=new WeakMap);var An=0,jn="__immutablehash__";"function"==typeof Symbol&&(jn=Symbol(jn));var Rn=16,Ln=255,Kn=0,Fn={};e(pe,te),pe.prototype.toString=function(){return this.__toString("Map {","}")},pe.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},pe.prototype.set=function(e,t){return xe(this,e,t)},pe.prototype.setIn=function(e,t){return this.updateIn(e,mn,function(){return t})},pe.prototype.remove=function(e){return xe(this,e,mn)},pe.prototype.deleteIn=function(e){return this.updateIn(e,function(){return mn})},pe.prototype.update=function(e,t,n){return 1===arguments.length?e(this):this.updateIn([e],t,n)},pe.prototype.updateIn=function(e,t,n){n||(n=t,t=void 0);var r=Ae(this,Mt(e),t,n);return r===mn?void 0:r},pe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Se()},pe.prototype.merge=function(){return Pe(this,void 0,arguments)},pe.prototype.mergeWith=function(e){return Pe(this,e,ln.call(arguments,1))},pe.prototype.mergeIn=function(e){var t=ln.call(arguments,1);return this.updateIn(e,Se(),function(e){return"function"==typeof e.merge?e.merge.apply(e,t):t[t.length-1]})},pe.prototype.mergeDeep=function(){return Pe(this,Me,arguments)},pe.prototype.mergeDeepWith=function(e){var t=ln.call(arguments,1);return Pe(this,De(e),t)},pe.prototype.mergeDeepIn=function(e){var t=ln.call(arguments,1);return this.updateIn(e,Se(),function(e){return"function"==typeof e.mergeDeep?e.mergeDeep.apply(e,t):t[t.length-1]})},pe.prototype.sort=function(e){return Ze(Ct(this,e))},pe.prototype.sortBy=function(e,t){return Ze(Ct(this,t,e))},pe.prototype.withMutations=function(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this},pe.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new f)},pe.prototype.asImmutable=function(){return this.__ensureOwner()},pe.prototype.wasAltered=function(){return this.__altered},pe.prototype.__iterator=function(e,t){return new ge(this,e,t)},pe.prototype.__iterate=function(e,t){var n=this,r=0;return this._root&&this._root.iterate(function(t){return r++,e(t[1],t[0],n)},t),r},pe.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?we(this.size,this._root,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},pe.isMap=fe;var Vn="@@__IMMUTABLE_MAP__@@",zn=pe.prototype;zn[Vn]=!0,zn.delete=zn.remove,zn.removeIn=zn.deleteIn,de.prototype.get=function(e,t,n,r){for(var o=this.entries,i=0,a=o.length;i<a;i++)if(X(n,o[i][0]))return o[i][1];return r},de.prototype.update=function(e,t,n,r,o,i,a){for(var s=o===mn,l=this.entries,u=0,c=l.length;u<c&&!X(r,l[u][0]);u++);var f=u<c;if(f?l[u][1]===o:s)return this;if(p(a),(s||!f)&&p(i),!s||1!==l.length){if(!f&&!s&&l.length>=Wn)return Oe(e,l,r,o);var h=e&&e===this.ownerID,v=h?l:d(l);return f?s?u===c-1?v.pop():v[u]=v.pop():v[u]=[r,o]:v.push([r,o]),h?(this.entries=v,this):new de(e,v)}},he.prototype.get=function(e,t,n,r){void 0===t&&(t=ie(n));var o=1<<((0===e?t:t>>>e)&vn),i=this.bitmap;return 0==(i&o)?r:this.nodes[je(i&o-1)].get(e+dn,t,n,r)},he.prototype.update=function(e,t,n,r,o,i,a){void 0===n&&(n=ie(r));var s=(0===t?n:n>>>t)&vn,l=1<<s,u=this.bitmap,c=0!=(u&l);if(!c&&o===mn)return this;var p=je(u&l-1),f=this.nodes,d=c?f[p]:void 0,h=_e(d,e,t+dn,n,r,o,i,a);if(h===d)return this;if(!c&&h&&f.length>=Hn)return Ne(e,f,u,s,h);if(c&&!h&&2===f.length&&ke(f[1^p]))return f[1^p];if(c&&h&&1===f.length&&ke(h))return h;var v=e&&e===this.ownerID,m=c?h?u:u^l:u|l,y=c?h?Re(f,p,h,v):Ke(f,p,v):Le(f,p,h,v);return v?(this.bitmap=m,this.nodes=y,this):new he(e,m,y)},ve.prototype.get=function(e,t,n,r){void 0===t&&(t=ie(n));var o=(0===e?t:t>>>e)&vn,i=this.nodes[o];return i?i.get(e+dn,t,n,r):r},ve.prototype.update=function(e,t,n,r,o,i,a){void 0===n&&(n=ie(r));var s=(0===t?n:n>>>t)&vn,l=o===mn,u=this.nodes,c=u[s];if(l&&!c)return this;var p=_e(c,e,t+dn,n,r,o,i,a);if(p===c)return this;var f=this.count;if(c){if(!p&&--f<Un)return Te(e,u,f,s)}else f++;var d=e&&e===this.ownerID,h=Re(u,s,p,d);return d?(this.count=f,this.nodes=h,this):new ve(e,f,h)},me.prototype.get=function(e,t,n,r){for(var o=this.entries,i=0,a=o.length;i<a;i++)if(X(n,o[i][0]))return o[i][1];return r},me.prototype.update=function(e,t,n,r,o,i,a){void 0===n&&(n=ie(r));var s=o===mn;if(n!==this.keyHash)return s?this:(p(a),p(i),Ee(this,e,t,n,[r,o]));for(var l=this.entries,u=0,c=l.length;u<c&&!X(r,l[u][0]);u++);var f=u<c;if(f?l[u][1]===o:s)return this;if(p(a),(s||!f)&&p(i),s&&2===c)return new ye(e,this.keyHash,l[1^u]);var h=e&&e===this.ownerID,v=h?l:d(l);return f?s?u===c-1?v.pop():v[u]=v.pop():v[u]=[r,o]:v.push([r,o]),h?(this.entries=v,this):new me(e,this.keyHash,v)},ye.prototype.get=function(e,t,n,r){return X(n,this.entry[0])?this.entry[1]:r},ye.prototype.update=function(e,t,n,r,o,i,a){var s=o===mn,l=X(r,this.entry[0]);return(l?o===this.entry[1]:s)?this:(p(a),s?void p(i):l?e&&e===this.ownerID?(this.entry[1]=o,this):new ye(e,this.keyHash,[r,o]):(p(i),Ee(this,e,t,ie(r),[r,o])))},de.prototype.iterate=me.prototype.iterate=function(e,t){for(var n=this.entries,r=0,o=n.length-1;r<=o;r++)if(!1===e(n[t?o-r:r]))return!1},he.prototype.iterate=ve.prototype.iterate=function(e,t){for(var n=this.nodes,r=0,o=n.length-1;r<=o;r++){var i=n[t?o-r:r];if(i&&!1===i.iterate(e,t))return!1}},ye.prototype.iterate=function(e,t){return e(this.entry)},e(ge,w),ge.prototype.next=function(){for(var e=this._type,t=this._stack;t;){var n,r=t.node,o=t.index++;if(r.entry){if(0===o)return be(e,r.entry)}else if(r.entries){if(n=r.entries.length-1,o<=n)return be(e,r.entries[this._reverse?n-o:o])}else if(n=r.nodes.length-1,o<=n){var i=r.nodes[this._reverse?n-o:o];if(i){if(i.entry)return be(e,i.entry);t=this._stack=Ce(i,t)}continue}t=this._stack=this._stack.__prev}return x()};var Bn,Wn=hn/4,Hn=hn/2,Un=hn/4;e(Fe,ne),Fe.of=function(){return this(arguments)},Fe.prototype.toString=function(){return this.__toString("List [","]")},Fe.prototype.get=function(e,t){if((e=v(this,e))>=0&&e<this.size){e+=this._origin;var n=Ge(this,e);return n&&n.array[e&vn]}return t},Fe.prototype.set=function(e,t){return Ue(this,e,t)},Fe.prototype.remove=function(e){return this.has(e)?0===e?this.shift():e===this.size-1?this.pop():this.splice(e,1):this},Fe.prototype.insert=function(e,t){return this.splice(e,0,t)},Fe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=dn,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):He()},Fe.prototype.push=function(){var e=arguments,t=this.size;return this.withMutations(function(n){Xe(n,0,t+e.length);for(var r=0;r<e.length;r++)n.set(t+r,e[r])})},Fe.prototype.pop=function(){return Xe(this,0,-1)},Fe.prototype.unshift=function(){var e=arguments;return this.withMutations(function(t){Xe(t,-e.length);for(var n=0;n<e.length;n++)t.set(n,e[n])})},Fe.prototype.shift=function(){return Xe(this,1)},Fe.prototype.merge=function(){return $e(this,void 0,arguments)},Fe.prototype.mergeWith=function(e){return $e(this,e,ln.call(arguments,1))},Fe.prototype.mergeDeep=function(){return $e(this,Me,arguments)},Fe.prototype.mergeDeepWith=function(e){var t=ln.call(arguments,1);return $e(this,De(e),t)},Fe.prototype.setSize=function(e){return Xe(this,0,e)},Fe.prototype.slice=function(e,t){var n=this.size;return y(e,t,n)?this:Xe(this,g(e,n),b(t,n))},Fe.prototype.__iterator=function(e,t){var n=0,r=Be(this,t);return new w(function(){var t=r();return t===Xn?x():S(e,n++,t)})},Fe.prototype.__iterate=function(e,t){for(var n,r=0,o=Be(this,t);(n=o())!==Xn&&!1!==e(n,r++,this););return r},Fe.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?We(this._origin,this._capacity,this._level,this._root,this._tail,e,this.__hash):(this.__ownerID=e,this)},Fe.isList=Ve;var qn="@@__IMMUTABLE_LIST__@@",Yn=Fe.prototype;Yn[qn]=!0,Yn.delete=Yn.remove,Yn.setIn=zn.setIn,Yn.deleteIn=Yn.removeIn=zn.removeIn,Yn.update=zn.update,Yn.updateIn=zn.updateIn,Yn.mergeIn=zn.mergeIn,Yn.mergeDeepIn=zn.mergeDeepIn,Yn.withMutations=zn.withMutations,Yn.asMutable=zn.asMutable,Yn.asImmutable=zn.asImmutable,Yn.wasAltered=zn.wasAltered,ze.prototype.removeBefore=function(e,t,n){if(n===t?1<<t:0===this.array.length)return this;var r=n>>>t&vn;if(r>=this.array.length)return new ze([],e);var o,i=0===r;if(t>0){var a=this.array[r];if((o=a&&a.removeBefore(e,t-dn,n))===a&&i)return this}if(i&&!o)return this;var s=Ye(this,e);if(!i)for(var l=0;l<r;l++)s.array[l]=void 0;return o&&(s.array[r]=o),s},ze.prototype.removeAfter=function(e,t,n){if(n===(t?1<<t:0)||0===this.array.length)return this;var r=n-1>>>t&vn;if(r>=this.array.length)return this;var o;if(t>0){var i=this.array[r];if((o=i&&i.removeAfter(e,t-dn,n))===i&&r===this.array.length-1)return this}var a=Ye(this,e);return a.array.splice(r+1),o&&(a.array[r]=o),a};var Gn,Xn={};e(Ze,pe),Ze.of=function(){return this(arguments)},Ze.prototype.toString=function(){return this.__toString("OrderedMap {","}")},Ze.prototype.get=function(e,t){var n=this._map.get(e);return void 0!==n?this._list.get(n)[1]:t},Ze.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):tt()},Ze.prototype.set=function(e,t){return nt(this,e,t)},Ze.prototype.remove=function(e){return nt(this,e,mn)},Ze.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},Ze.prototype.__iterate=function(e,t){var n=this;return this._list.__iterate(function(t){return t&&e(t[1],t[0],n)},t)},Ze.prototype.__iterator=function(e,t){return this._list.fromEntrySeq().__iterator(e,t)},Ze.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e),n=this._list.__ensureOwner(e);return e?et(t,n,e,this.__hash):(this.__ownerID=e,this._map=t,this._list=n,this)},Ze.isOrderedMap=Qe,Ze.prototype[fn]=!0,Ze.prototype.delete=Ze.prototype.remove;var $n;e(rt,P),rt.prototype.get=function(e,t){return this._iter.get(e,t)},rt.prototype.has=function(e){return this._iter.has(e)},rt.prototype.valueSeq=function(){return this._iter.valueSeq()},rt.prototype.reverse=function(){var e=this,t=ut(this,!0);return this._useKeys||(t.valueSeq=function(){return e._iter.toSeq().reverse()}),t},rt.prototype.map=function(e,t){var n=this,r=lt(this,e,t);return this._useKeys||(r.valueSeq=function(){return n._iter.toSeq().map(e,t)}),r},rt.prototype.__iterate=function(e,t){var n,r=this;return this._iter.__iterate(this._useKeys?function(t,n){return e(t,n,r)}:(n=t?Et(this):0,function(o){return e(o,t?--n:n++,r)}),t)},rt.prototype.__iterator=function(e,t){if(this._useKeys)return this._iter.__iterator(e,t);var n=this._iter.__iterator(Cn,t),r=t?Et(this):0;return new w(function(){var o=n.next();return o.done?o:S(e,t?--r:r++,o.value,o)})},rt.prototype[fn]=!0,e(ot,M),ot.prototype.includes=function(e){return this._iter.includes(e)},ot.prototype.__iterate=function(e,t){var n=this,r=0;return this._iter.__iterate(function(t){return e(t,r++,n)},t)},ot.prototype.__iterator=function(e,t){var n=this._iter.__iterator(Cn,t),r=0;return new w(function(){var t=n.next();return t.done?t:S(e,r++,t.value,t)})},e(it,D),it.prototype.has=function(e){return this._iter.includes(e)},it.prototype.__iterate=function(e,t){var n=this;return this._iter.__iterate(function(t){return e(t,t,n)},t)},it.prototype.__iterator=function(e,t){var n=this._iter.__iterator(Cn,t);return new w(function(){var t=n.next();return t.done?t:S(e,t.value,t.value,t)})},e(at,P),at.prototype.entrySeq=function(){return this._iter.toSeq()},at.prototype.__iterate=function(e,t){var n=this;return this._iter.__iterate(function(t){if(t){kt(t);var r=i(t);return e(r?t.get(1):t[1],r?t.get(0):t[0],n)}},t)},at.prototype.__iterator=function(e,t){var n=this._iter.__iterator(Cn,t);return new w(function(){for(;;){var t=n.next();if(t.done)return t;var r=t.value;if(r){kt(r);var o=i(r);return S(e,o?r.get(0):r[0],o?r.get(1):r[1],t)}}})},ot.prototype.cacheResult=rt.prototype.cacheResult=it.prototype.cacheResult=at.prototype.cacheResult=Nt,e(Dt,te),Dt.prototype.toString=function(){return this.__toString(At(this)+" {","}")},Dt.prototype.has=function(e){return this._defaultValues.hasOwnProperty(e)},Dt.prototype.get=function(e,t){if(!this.has(e))return t;var n=this._defaultValues[e];return this._map?this._map.get(e,n):n},Dt.prototype.clear=function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var e=this.constructor;return e._empty||(e._empty=It(this,Se()))},Dt.prototype.set=function(e,t){if(!this.has(e))throw new Error('Cannot set unknown key "'+e+'" on '+At(this));var n=this._map&&this._map.set(e,t);return this.__ownerID||n===this._map?this:It(this,n)},Dt.prototype.remove=function(e){if(!this.has(e))return this;var t=this._map&&this._map.remove(e);return this.__ownerID||t===this._map?this:It(this,t)},Dt.prototype.wasAltered=function(){return this._map.wasAltered()},Dt.prototype.__iterator=function(e,t){var r=this;return n(this._defaultValues).map(function(e,t){return r.get(t)}).__iterator(e,t)},Dt.prototype.__iterate=function(e,t){var r=this;return n(this._defaultValues).map(function(e,t){return r.get(t)}).__iterate(e,t)},Dt.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map&&this._map.__ensureOwner(e);return e?It(this,t,e):(this.__ownerID=e,this._map=t,this)};var Jn=Dt.prototype;Jn.delete=Jn.remove,Jn.deleteIn=Jn.removeIn=zn.removeIn,Jn.merge=zn.merge,Jn.mergeWith=zn.mergeWith,Jn.mergeIn=zn.mergeIn,Jn.mergeDeep=zn.mergeDeep,Jn.mergeDeepWith=zn.mergeDeepWith,Jn.mergeDeepIn=zn.mergeDeepIn,Jn.setIn=zn.setIn,Jn.update=zn.update,Jn.updateIn=zn.updateIn,Jn.withMutations=zn.withMutations,Jn.asMutable=zn.asMutable,Jn.asImmutable=zn.asImmutable,e(Lt,re),Lt.of=function(){return this(arguments)},Lt.fromKeys=function(e){return this(n(e).keySeq())},Lt.prototype.toString=function(){return this.__toString("Set {","}")},Lt.prototype.has=function(e){return this._map.has(e)},Lt.prototype.add=function(e){return Ft(this,this._map.set(e,!0))},Lt.prototype.remove=function(e){return Ft(this,this._map.remove(e))},Lt.prototype.clear=function(){return Ft(this,this._map.clear())},Lt.prototype.union=function(){var e=ln.call(arguments,0);return e=e.filter(function(e){return 0!==e.size}),0===e.length?this:0!==this.size||this.__ownerID||1!==e.length?this.withMutations(function(t){for(var n=0;n<e.length;n++)o(e[n]).forEach(function(e){return t.add(e)})}):this.constructor(e[0])},Lt.prototype.intersect=function(){var e=ln.call(arguments,0);if(0===e.length)return this;e=e.map(function(e){return o(e)});var t=this;return this.withMutations(function(n){t.forEach(function(t){e.every(function(e){return e.includes(t)})||n.remove(t)})})},Lt.prototype.subtract=function(){var e=ln.call(arguments,0);if(0===e.length)return this;e=e.map(function(e){return o(e)});var t=this;return this.withMutations(function(n){t.forEach(function(t){e.some(function(e){return e.includes(t)})&&n.remove(t)})})},Lt.prototype.merge=function(){return this.union.apply(this,arguments)},Lt.prototype.mergeWith=function(e){var t=ln.call(arguments,1);return this.union.apply(this,t)},Lt.prototype.sort=function(e){return Bt(Ct(this,e))},Lt.prototype.sortBy=function(e,t){return Bt(Ct(this,t,e))},Lt.prototype.wasAltered=function(){return this._map.wasAltered()},Lt.prototype.__iterate=function(e,t){var n=this;return this._map.__iterate(function(t,r){return e(r,r,n)},t)},Lt.prototype.__iterator=function(e,t){return this._map.map(function(e,t){return t}).__iterator(e,t)},Lt.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e);return e?this.__make(t,e):(this.__ownerID=e,this._map=t,this)},Lt.isSet=Kt;var Zn="@@__IMMUTABLE_SET__@@",Qn=Lt.prototype;Qn[Zn]=!0,Qn.delete=Qn.remove,Qn.mergeDeep=Qn.merge,Qn.mergeDeepWith=Qn.mergeWith,Qn.withMutations=zn.withMutations,Qn.asMutable=zn.asMutable,Qn.asImmutable=zn.asImmutable,Qn.__empty=zt,Qn.__make=Vt;var er;e(Bt,Lt),Bt.of=function(){return this(arguments)},Bt.fromKeys=function(e){return this(n(e).keySeq())},Bt.prototype.toString=function(){return this.__toString("OrderedSet {","}")},Bt.isOrderedSet=Wt;var tr=Bt.prototype;tr[fn]=!0,tr.__empty=Ut,tr.__make=Ht;var nr;e(qt,ne),qt.of=function(){return this(arguments)},qt.prototype.toString=function(){return this.__toString("Stack [","]")},qt.prototype.get=function(e,t){var n=this._head;for(e=v(this,e);n&&e--;)n=n.next;return n?n.value:t},qt.prototype.peek=function(){return this._head&&this._head.value},qt.prototype.push=function(){if(0===arguments.length)return this;for(var e=this.size+arguments.length,t=this._head,n=arguments.length-1;n>=0;n--)t={value:arguments[n],next:t};return this.__ownerID?(this.size=e,this._head=t,this.__hash=void 0,this.__altered=!0,this):Gt(e,t)},qt.prototype.pushAll=function(e){if(e=r(e),0===e.size)return this;ce(e.size);var t=this.size,n=this._head;return e.reverse().forEach(function(e){t++,n={value:e,next:n}}),this.__ownerID?(this.size=t,this._head=n,this.__hash=void 0,this.__altered=!0,this):Gt(t,n)},qt.prototype.pop=function(){return this.slice(1)},qt.prototype.unshift=function(){return this.push.apply(this,arguments)},qt.prototype.unshiftAll=function(e){return this.pushAll(e)},qt.prototype.shift=function(){return this.pop.apply(this,arguments)},qt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Xt()},qt.prototype.slice=function(e,t){if(y(e,t,this.size))return this;var n=g(e,this.size);if(b(t,this.size)!==this.size)return ne.prototype.slice.call(this,e,t);for(var r=this.size-n,o=this._head;n--;)o=o.next;return this.__ownerID?(this.size=r,this._head=o,this.__hash=void 0,this.__altered=!0,this):Gt(r,o)},qt.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Gt(this.size,this._head,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},qt.prototype.__iterate=function(e,t){if(t)return this.reverse().__iterate(e);for(var n=0,r=this._head;r&&!1!==e(r.value,n++,this);)r=r.next;return n},qt.prototype.__iterator=function(e,t){if(t)return this.reverse().__iterator(e);var n=0,r=this._head;return new w(function(){if(r){var t=r.value;return r=r.next,S(e,n++,t)}return x()})},qt.isStack=Yt;var rr="@@__IMMUTABLE_STACK__@@",or=qt.prototype;or[rr]=!0,or.withMutations=zn.withMutations,or.asMutable=zn.asMutable,or.asImmutable=zn.asImmutable,or.wasAltered=zn.wasAltered;var ir;t.Iterator=w,$t(t,{toArray:function(){ce(this.size);var e=new Array(this.size||0);return this.valueSeq().__iterate(function(t,n){e[n]=t}),e},toIndexedSeq:function(){return new ot(this)},toJS:function(){return this.toSeq().map(function(e){return e&&"function"==typeof e.toJS?e.toJS():e}).__toJS()},toJSON:function(){return this.toSeq().map(function(e){return e&&"function"==typeof e.toJSON?e.toJSON():e}).__toJS()},toKeyedSeq:function(){return new rt(this,!0)},toMap:function(){return pe(this.toKeyedSeq())},toObject:function(){ce(this.size);var e={};return this.__iterate(function(t,n){e[n]=t}),e},toOrderedMap:function(){return Ze(this.toKeyedSeq())},toOrderedSet:function(){return Bt(a(this)?this.valueSeq():this)},toSet:function(){return Lt(a(this)?this.valueSeq():this)},toSetSeq:function(){return new it(this)},toSeq:function(){return s(this)?this.toIndexedSeq():a(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return qt(a(this)?this.valueSeq():this)},toList:function(){return Fe(a(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(e,t){return 0===this.size?e+t:e+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+t},concat:function(){return _t(this,mt(this,ln.call(arguments,0)))},includes:function(e){return this.some(function(t){return X(t,e)})},entries:function(){return this.__iterator(wn)},every:function(e,t){ce(this.size);var n=!0;return this.__iterate(function(r,o,i){if(!e.call(t,r,o,i))return n=!1,!1}),n},filter:function(e,t){return _t(this,ct(this,e,t,!0))},find:function(e,t,n){var r=this.findEntry(e,t);return r?r[1]:n},findEntry:function(e,t){var n;return this.__iterate(function(r,o,i){if(e.call(t,r,o,i))return n=[o,r],!1}),n},findLastEntry:function(e,t){return this.toSeq().reverse().findEntry(e,t)},forEach:function(e,t){return ce(this.size),this.__iterate(t?e.bind(t):e)},join:function(e){ce(this.size),e=void 0!==e?""+e:",";var t="",n=!0;return this.__iterate(function(r){n?n=!1:t+=e,t+=null!==r&&void 0!==r?r.toString():""}),t},keys:function(){return this.__iterator(bn)},map:function(e,t){return _t(this,lt(this,e,t))},reduce:function(e,t,n){ce(this.size);var r,o;return arguments.length<2?o=!0:r=t,this.__iterate(function(t,i,a){o?(o=!1,r=t):r=e.call(n,r,t,i,a)}),r},reduceRight:function(e,t,n){var r=this.toKeyedSeq().reverse();return r.reduce.apply(r,arguments)},reverse:function(){return _t(this,ut(this,!0))},slice:function(e,t){return _t(this,dt(this,e,t,!0))},some:function(e,t){return!this.every(Qt(e),t)},sort:function(e){return _t(this,Ct(this,e))},values:function(){return this.__iterator(Cn)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(e,t){return h(e?this.toSeq().filter(e,t):this)},countBy:function(e,t){return pt(this,e,t)},equals:function(e){return $(this,e)},entrySeq:function(){var e=this;if(e._cache)return new I(e._cache);var t=e.toSeq().map(Zt).toIndexedSeq();return t.fromEntrySeq=function(){return e.toSeq()},t},filterNot:function(e,t){return this.filter(Qt(e),t)},findLast:function(e,t,n){return this.toKeyedSeq().reverse().find(e,t,n)},first:function(){return this.find(m)},flatMap:function(e,t){return _t(this,gt(this,e,t))},flatten:function(e){return _t(this,yt(this,e,!0))},fromEntrySeq:function(){return new at(this)},get:function(e,t){return this.find(function(t,n){return X(n,e)},void 0,t)},getIn:function(e,t){for(var n,r=this,o=Mt(e);!(n=o.next()).done;){var i=n.value;if((r=r&&r.get?r.get(i,mn):mn)===mn)return t}return r},groupBy:function(e,t){return ft(this,e,t)},has:function(e){return this.get(e,mn)!==mn},hasIn:function(e){return this.getIn(e,mn)!==mn},isSubset:function(e){return e="function"==typeof e.includes?e:t(e),this.every(function(t){return e.includes(t)})},isSuperset:function(e){return e="function"==typeof e.isSubset?e:t(e),e.isSubset(this)},keySeq:function(){return this.toSeq().map(Jt).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},max:function(e){return wt(this,e)},maxBy:function(e,t){return wt(this,t,e)},min:function(e){return wt(this,e?en(e):rn)},minBy:function(e,t){return wt(this,t?en(t):rn,e)},rest:function(){return this.slice(1)},skip:function(e){return this.slice(Math.max(0,e))},skipLast:function(e){return _t(this,this.toSeq().reverse().skip(e).reverse())},skipWhile:function(e,t){return _t(this,vt(this,e,t,!0))},skipUntil:function(e,t){return this.skipWhile(Qt(e),t)},sortBy:function(e,t){return _t(this,Ct(this,t,e))},take:function(e){return this.slice(0,Math.max(0,e))},takeLast:function(e){return _t(this,this.toSeq().reverse().take(e).reverse())},takeWhile:function(e,t){return _t(this,ht(this,e,t))},takeUntil:function(e,t){return this.takeWhile(Qt(e),t)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=on(this))}});var ar=t.prototype;ar[un]=!0,ar[_n]=ar.values,ar.__toJS=ar.toArray,ar.__toStringMapper=tn,ar.inspect=ar.toSource=function(){return this.toString()},ar.chain=ar.flatMap,ar.contains=ar.includes,function(){try{Object.defineProperty(ar,"length",{get:function(){if(!t.noLengthWarning){var e;try{throw new Error}catch(t){e=t.stack}if(-1===e.indexOf("_wrapObject"))return console&&console.warn&&console.warn("iterable.length has been deprecated, use iterable.size or iterable.count(). This warning will become a silent error in a future version. "+e),this.size}}})}catch(e){}}(),$t(n,{flip:function(){return _t(this,st(this))},findKey:function(e,t){var n=this.findEntry(e,t);return n&&n[0]},findLastKey:function(e,t){return this.toSeq().reverse().findKey(e,t)},keyOf:function(e){return this.findKey(function(t){return X(t,e)})},lastKeyOf:function(e){return this.findLastKey(function(t){return X(t,e)})},mapEntries:function(e,t){var n=this,r=0;return _t(this,this.toSeq().map(function(o,i){return e.call(t,[i,o],r++,n)}).fromEntrySeq())},mapKeys:function(e,t){var n=this;return _t(this,this.toSeq().flip().map(function(r,o){return e.call(t,r,o,n)}).flip())}});var sr=n.prototype;return sr[cn]=!0,sr[_n]=ar.entries,sr.__toJS=ar.toObject,sr.__toStringMapper=function(e,t){return JSON.stringify(t)+": "+tn(e)},$t(r,{toKeyedSeq:function(){return new rt(this,!1)},filter:function(e,t){return _t(this,ct(this,e,t,!1))},findIndex:function(e,t){var n=this.findEntry(e,t);return n?n[0]:-1},indexOf:function(e){var t=this.toKeyedSeq().keyOf(e);return void 0===t?-1:t},lastIndexOf:function(e){var t=this.toKeyedSeq().reverse().keyOf(e);return void 0===t?-1:t},reverse:function(){return _t(this,ut(this,!1))},slice:function(e,t){return _t(this,dt(this,e,t,!1))},splice:function(e,t){var n=arguments.length;if(t=Math.max(0|t,0),0===n||2===n&&!t)return this;e=g(e,e<0?this.count():this.size);var r=this.slice(0,e);return _t(this,1===n?r:r.concat(d(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){var n=this.toKeyedSeq().findLastKey(e,t);return void 0===n?-1:n},first:function(){return this.get(0)},flatten:function(e){return _t(this,yt(this,e,!1))},get:function(e,t){return e=v(this,e),e<0||this.size===1/0||void 0!==this.size&&e>this.size?t:this.find(function(t,n){return n===e},void 0,t)},has:function(e){return(e=v(this,e))>=0&&(void 0!==this.size?this.size===1/0||e<this.size:-1!==this.indexOf(e))},interpose:function(e){return _t(this,bt(this,e))},interleave:function(){var e=[this].concat(d(arguments)),t=xt(this.toSeq(),M.of,e),n=t.flatten(!0);return t.size&&(n.size=t.size*e.length),_t(this,n)},last:function(){return this.get(-1)},skipWhile:function(e,t){return _t(this,vt(this,e,t,!1))},zip:function(){return _t(this,xt(this,nn,[this].concat(d(arguments))))},zipWith:function(e){var t=d(arguments);return t[0]=this,_t(this,xt(this,e,t))}}),r.prototype[pn]=!0,r.prototype[fn]=!0,$t(o,{get:function(e,t){return this.has(e)?e:t},includes:function(e){return this.has(e)},keySeq:function(){return this.valueSeq()}}),o.prototype.has=ar.includes,$t(P,n.prototype),$t(M,r.prototype),$t(D,o.prototype),$t(te,n.prototype),$t(ne,r.prototype),$t(re,o.prototype),{Iterable:t,Seq:N,Collection:ee,Map:pe,OrderedMap:Ze,List:Fe,Stack:qt,Set:Lt,OrderedSet:Bt,Record:Dt,Range:Q,Repeat:J,is:X,fromJS:U}})},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t,n){return _.set(e,{selection:t,forceSelection:n,nativelyRenderedContent:null,inlineStyleOverride:null})}function i(e,t){return e.getBlockMap().map(function(n){return h.generate(e,n,t)}).toOrderedMap()}function a(e,t,n,r){var o=e.getCurrentContent().set("entityMap",n),i=o.getBlockMap();return e.getImmutable().get("treeMap").merge(t.toSeq().filter(function(e,t){return e!==i.get(t)}).map(function(e){return h.generate(o,e,r)}))}function s(e,t,n,r,o){return n.merge(t.toSeq().filter(function(t){return r.getDecorations(t,e)!==o.getDecorations(t,e)}).map(function(t){return h.generate(e,t,r)}))}function l(e,t){return t!==e.getLastChangeType()||"insert-characters"!==t&&"backspace-character"!==t&&"delete-character"!==t}function u(e,t){var n=t.getStartKey(),r=t.getStartOffset(),o=e.getBlockForKey(n);return r>0?o.getInlineStyleAt(r-1):o.getLength()?o.getInlineStyleAt(0):p(e,n)}function c(e,t){var n=t.getStartKey(),r=t.getStartOffset(),o=e.getBlockForKey(n);return r<o.getLength()?o.getInlineStyleAt(r):r>0?o.getInlineStyleAt(r-1):p(e,n)}function p(e,t){var n=e.getBlockMap().reverse().skipUntil(function(e,n){return n===t}).skip(1).skipUntil(function(e,t){return e.getLength()}).first();return n?n.getInlineStyleAt(n.getLength()-1):b()}var f=n(16),d=f||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=n(212),v=n(147),m=n(434),y=n(11),g=n(65),b=y.OrderedSet,C=y.Record,w=y.Stack,S={allowUndo:!0,currentContent:null,decorator:null,directionMap:null,forceSelection:!1,inCompositionMode:!1,inlineStyleOverride:null,lastChangeType:null,nativelyRenderedContent:null,redoStack:w(),selection:null,treeMap:null,undoStack:w()},x=C(S),_=function(){function e(t){r(this,e),this._immutable=t}return e.createEmpty=function(t){return e.createWithContent(v.createFromText(""),t)},e.createWithContent=function(t,n){var r=t.getBlockMap().first().getKey();return e.create({currentContent:t,undoStack:w(),redoStack:w(),decorator:n||null,selection:g.createEmpty(r)})},e.create=function(t){var n=t.currentContent,r=t.decorator,o=d({},t,{treeMap:i(n,r),directionMap:m.getDirectionMap(n)});return new e(new x(o))},e.set=function(t,n){return new e(t.getImmutable().withMutations(function(e){var r=e.get("decorator"),o=r;null===n.decorator?o=null:n.decorator&&(o=n.decorator);var l=n.currentContent||t.getCurrentContent();if(o!==r){var u,c=e.get("treeMap");return u=o&&r?s(l,l.getBlockMap(),c,o,r):i(l,o),void e.merge({decorator:o,treeMap:u,nativelyRenderedContent:null})}l!==t.getCurrentContent()&&e.set("treeMap",a(t,l.getBlockMap(),l.getEntityMap(),o)),e.merge(n)}))},e.prototype.toJS=function(){return this.getImmutable().toJS()},e.prototype.getAllowUndo=function(){return this.getImmutable().get("allowUndo")},e.prototype.getCurrentContent=function(){return this.getImmutable().get("currentContent")},e.prototype.getUndoStack=function(){return this.getImmutable().get("undoStack")},e.prototype.getRedoStack=function(){return this.getImmutable().get("redoStack")},e.prototype.getSelection=function(){return this.getImmutable().get("selection")},e.prototype.getDecorator=function(){return this.getImmutable().get("decorator")},e.prototype.isInCompositionMode=function(){return this.getImmutable().get("inCompositionMode")},e.prototype.mustForceSelection=function(){return this.getImmutable().get("forceSelection")},e.prototype.getNativelyRenderedContent=function(){return this.getImmutable().get("nativelyRenderedContent")},e.prototype.getLastChangeType=function(){return this.getImmutable().get("lastChangeType")},e.prototype.getInlineStyleOverride=function(){return this.getImmutable().get("inlineStyleOverride")},e.setInlineStyleOverride=function(t,n){return e.set(t,{inlineStyleOverride:n})},e.prototype.getCurrentInlineStyle=function(){var e=this.getInlineStyleOverride();if(null!=e)return e;var t=this.getCurrentContent(),n=this.getSelection();return n.isCollapsed()?u(t,n):c(t,n)},e.prototype.getBlockTree=function(e){return this.getImmutable().getIn(["treeMap",e])},e.prototype.isSelectionAtStartOfContent=function(){var e=this.getCurrentContent().getBlockMap().first().getKey();return this.getSelection().hasEdgeWithin(e,0,0)},e.prototype.isSelectionAtEndOfContent=function(){var e=this.getCurrentContent(),t=e.getBlockMap(),n=t.last(),r=n.getLength();return this.getSelection().hasEdgeWithin(n.getKey(),r,r)},e.prototype.getDirectionMap=function(){return this.getImmutable().get("directionMap")},e.acceptSelection=function(e,t){return o(e,t,!1)},e.forceSelection=function(e,t){return t.getHasFocus()||(t=t.set("hasFocus",!0)),o(e,t,!0)},e.moveSelectionToEnd=function(t){var n=t.getCurrentContent(),r=n.getLastBlock(),o=r.getKey(),i=r.getLength();return e.acceptSelection(t,new g({anchorKey:o,anchorOffset:i,focusKey:o,focusOffset:i,isBackward:!1}))},e.moveFocusToEnd=function(t){var n=e.moveSelectionToEnd(t);return e.forceSelection(n,n.getSelection())},e.push=function(t,n,r){if(t.getCurrentContent()===n)return t;var o="insert-characters"!==r,i=m.getDirectionMap(n,t.getDirectionMap());if(!t.getAllowUndo())return e.set(t,{currentContent:n,directionMap:i,lastChangeType:r,selection:n.getSelectionAfter(),forceSelection:o,inlineStyleOverride:null});var a=t.getSelection(),s=t.getCurrentContent(),u=t.getUndoStack(),c=n;a!==s.getSelectionAfter()||l(t,r)?(u=u.push(s),c=c.set("selectionBefore",a)):"insert-characters"!==r&&"backspace-character"!==r&&"delete-character"!==r||(c=c.set("selectionBefore",s.getSelectionBefore()));var p=t.getInlineStyleOverride();-1===["adjust-depth","change-block-type","split-block"].indexOf(r)&&(p=null);var f={currentContent:c,directionMap:i,undoStack:u,redoStack:w(),lastChangeType:r,selection:n.getSelectionAfter(),forceSelection:o,inlineStyleOverride:p};return e.set(t,f)},e.undo=function(t){if(!t.getAllowUndo())return t;var n=t.getUndoStack(),r=n.peek();if(!r)return t;var o=t.getCurrentContent(),i=m.getDirectionMap(r,t.getDirectionMap());return e.set(t,{currentContent:r,directionMap:i,undoStack:n.shift(),redoStack:t.getRedoStack().push(o),forceSelection:!0,inlineStyleOverride:null,lastChangeType:"undo",nativelyRenderedContent:null,selection:o.getSelectionBefore()})},e.redo=function(t){if(!t.getAllowUndo())return t;var n=t.getRedoStack(),r=n.peek();if(!r)return t;var o=t.getCurrentContent(),i=m.getDirectionMap(r,t.getDirectionMap());return e.set(t,{currentContent:r,directionMap:i,undoStack:t.getUndoStack().push(o),redoStack:n.shift(),forceSelection:!0,inlineStyleOverride:null,lastChangeType:"redo",nativelyRenderedContent:null,selection:r.getSelectionAfter()})},e.prototype.getImmutable=function(){return this._immutable},e}();e.exports=_},function(e,t){},function(e,t,n){"use strict";var r=n(1),o=n.n(r),i=n(8),a=n.n(i),s=n(0),l=(n.n(s),n(6)),u=n.n(l),c=n(20),p=function(e){var t=e.type,n=e.className,r=void 0===n?"":n,i=e.spin,l=u()(a()({anticon:!0,"anticon-spin":!!i||"loading"===t},"anticon-"+t,!0),r);return s.createElement("i",o()({},Object(c.a)(e,["type","spin"]),{className:l}))};t.a=p},function(e,t,n){"use strict";var r=n(0),o=n(301);if(void 0===r)throw Error("create-react-class could not find the React object. If you are using script tags, make sure that React is being loaded before create-react-class.");var i=(new r.Component).updater;e.exports=o(r.Component,r.isValidElement,i)},function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}/* object-assign (c) Sindre Sorhus @license MIT */ var o=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,s,l=r(e),u=1;u<arguments.length;u++){n=Object(arguments[u]);for(var c in n)i.call(n,c)&&(l[c]=n[c]);if(o){s=o(n);for(var p=0;p<s.length;p++)a.call(n,s[p])&&(l[s[p]]=n[s[p]])}}return l}},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}},function(e,t,n){"use strict";function r(e){var t=[];return x.a.Children.forEach(e,function(e){t.push(e)}),t}function o(e,t){var n=null;return e&&e.forEach(function(e){n||e&&e.key===t&&(n=e)}),n}function i(e,t,n){var r=null;return e&&e.forEach(function(e){if(e&&e.key===t&&e.props[n]){if(r)throw new Error("two child with same key for <rc-animate> children");r=e}}),r}function a(e,t,n){var r=e.length===t.length;return r&&e.forEach(function(e,o){var i=t[o];e&&i&&(e&&!i||!e&&i?r=!1:e.key!==i.key?r=!1:n&&e.props[n]!==i.props[n]&&(r=!1))}),r}function s(e,t){var n=[],r={},i=[];return e.forEach(function(e){e&&o(t,e.key)?i.length&&(r[e.key]=i,i=[]):i.push(e)}),t.forEach(function(e){e&&r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e)}),n=n.concat(i)}function l(e){var t=e.children;return x.a.isValidElement(t)&&!t.key?x.a.cloneElement(t,{key:R}):t}function u(){}var c=n(1),p=n.n(c),f=n(8),d=n.n(f),h=n(2),v=n.n(h),m=n(7),y=n.n(m),g=n(3),b=n.n(g),C=n(4),w=n.n(C),S=n(0),x=n.n(S),_=n(5),k=n.n(_),E=n(19),O=n.n(E),T=n(9),N=n.n(T),P=n(118),M={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}},D=M,I={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},A=function(e){function t(){return v()(this,t),b()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return w()(t,e),y()(t,[{key:"componentWillUnmount",value:function(){this.stop()}},{key:"componentWillEnter",value:function(e){D.isEnterSupported(this.props)?this.transition("enter",e):e()}},{key:"componentWillAppear",value:function(e){D.isAppearSupported(this.props)?this.transition("appear",e):e()}},{key:"componentWillLeave",value:function(e){D.isLeaveSupported(this.props)?this.transition("leave",e):e()}},{key:"transition",value:function(e,t){var n=this,r=N.a.findDOMNode(this),o=this.props,i=o.transitionName,a="object"===(void 0===i?"undefined":O()(i));this.stop();var s=function(){n.stopper=null,t()};if((P.b||!o.animation[e])&&i&&o[I[e]]){var l=a?i[e]:i+"-"+e,u=l+"-active";a&&i[e+"Active"]&&(u=i[e+"Active"]),this.stopper=Object(P.a)(r,{name:l,active:u},s)}else this.stopper=o.animation[e](r,s)}},{key:"stop",value:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())}},{key:"render",value:function(){return this.props.children}}]),t}(x.a.Component);A.propTypes={children:k.a.any};var j=A,R="rc_animate_"+Date.now(),L=function(e){function t(e){v()(this,t);var n=b()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return K.call(n),n.currentlyAnimatingKeys={},n.keysToEnter=[],n.keysToLeave=[],n.state={children:r(l(e))},n.childrenRefs={},n}return w()(t,e),y()(t,[{key:"componentDidMount",value:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){t&&e.performAppear(t.key)})}},{key:"componentWillReceiveProps",value:function(e){var t=this;this.nextProps=e;var n=r(l(e)),a=this.props;a.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var u=a.showProp,c=this.currentlyAnimatingKeys,p=a.exclusive?r(l(a)):this.state.children,f=[];u?(p.forEach(function(e){var t=e&&o(n,e.key),r=void 0;(r=t&&t.props[u]||!e.props[u]?t:x.a.cloneElement(t||e,d()({},u,!0)))&&f.push(r)}),n.forEach(function(e){e&&o(p,e.key)||f.push(e)})):f=s(p,n),this.setState({children:f}),n.forEach(function(e){var n=e&&e.key;if(!e||!c[n]){var r=e&&o(p,n);if(u){var a=e.props[u];if(r){!i(p,n,u)&&a&&t.keysToEnter.push(n)}else a&&t.keysToEnter.push(n)}else r||t.keysToEnter.push(n)}}),p.forEach(function(e){var r=e&&e.key;if(!e||!c[r]){var a=e&&o(n,r);if(u){var s=e.props[u];if(a){!i(n,r,u)&&s&&t.keysToLeave.push(r)}else s&&t.keysToLeave.push(r)}else a||t.keysToLeave.push(r)}})}},{key:"componentDidUpdate",value:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)}},{key:"isValidChildByKey",value:function(e,t){var n=this.props.showProp;return n?i(e,t,n):o(e,t)}},{key:"stop",value:function(e){delete this.currentlyAnimatingKeys[e];var t=this.childrenRefs[e];t&&t.stop()}},{key:"render",value:function(){var e=this,t=this.props;this.nextProps=t;var n=this.state.children,r=null;n&&(r=n.map(function(n){if(null===n||void 0===n)return n;if(!n.key)throw new Error("must set key for <rc-animate> children");return x.a.createElement(j,{key:n.key,ref:function(t){return e.childrenRefs[n.key]=t},animation:t.animation,transitionName:t.transitionName,transitionEnter:t.transitionEnter,transitionAppear:t.transitionAppear,transitionLeave:t.transitionLeave},n)}));var o=t.component;if(o){var i=t;return"string"==typeof o&&(i=p()({className:t.className,style:t.style},t.componentProps)),x.a.createElement(o,i,r)}return r[0]||null}}]),t}(x.a.Component);L.isAnimate=!0,L.propTypes={component:k.a.any,componentProps:k.a.object,animation:k.a.object,transitionName:k.a.oneOfType([k.a.string,k.a.object]),transitionEnter:k.a.bool,transitionAppear:k.a.bool,exclusive:k.a.bool,transitionLeave:k.a.bool,onEnd:k.a.func,onEnter:k.a.func,onLeave:k.a.func,onAppear:k.a.func,showProp:k.a.string},L.defaultProps={animation:{},component:"span",componentProps:{},transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:u,onEnter:u,onLeave:u,onAppear:u};var K=function(){var e=this;this.performEnter=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillEnter(e.handleDoneAdding.bind(e,t,"enter")))},this.performAppear=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillAppear(e.handleDoneAdding.bind(e,t,"appear")))},this.handleDoneAdding=function(t,n){var o=e.props;if(delete e.currentlyAnimatingKeys[t],!o.exclusive||o===e.nextProps){var i=r(l(o));e.isValidChildByKey(i,t)?"appear"===n?D.allowAppearCallback(o)&&(o.onAppear(t),o.onEnd(t,!0)):D.allowEnterCallback(o)&&(o.onEnter(t),o.onEnd(t,!0)):e.performLeave(t)}},this.performLeave=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillLeave(e.handleDoneLeaving.bind(e,t)))},this.handleDoneLeaving=function(t){var n=e.props;if(delete e.currentlyAnimatingKeys[t],!n.exclusive||n===e.nextProps){var o=r(l(n));if(e.isValidChildByKey(o,t))e.performEnter(t);else{var i=function(){D.allowLeaveCallback(n)&&(n.onLeave(t),n.onEnd(t,!1))};a(e.state.children,o,n.showProp)?i():e.setState({children:o},i)}}}};t.a=L},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(262),i=r(o),a=n(272),s=r(a),l="function"==typeof s.default&&"symbol"==typeof i.default?function(e){return typeof e}:function(e){return e&&"function"==typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":typeof e};t.default="function"==typeof s.default&&"symbol"===l(i.default)?function(e){return void 0===e?"undefined":l(e)}:function(e){return e&&"function"==typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":void 0===e?"undefined":l(e)}},function(e,t,n){"use strict";function r(e,t){for(var n=i()({},e),r=0;r<t.length;r++){delete n[t[r]]}return n}var o=n(1),i=n.n(o);t.a=r},function(e,t){e.exports=n},function(e,t,n){"use strict";var r=n(25),o=n(423),i=n(45),a=n(11),s=n(424),l=n(426),u=n(97),c=n(429),p=n(430),f=n(10),d=n(431),h=n(209),v=n(432),m=n(433),y=a.OrderedSet,g={replaceText:function(e,t,n,o,i){var a=h(e,t),s=v(a,t),l=r.create({style:o||y(),entity:i||null});return p(s,s.getSelectionAfter(),n,l)},insertText:function(e,t,n,r,o){return t.isCollapsed()||f(!1),g.replaceText(e,t,n,r,o)},moveText:function(e,t,n){var r=u(e,t),o=g.removeRange(e,t,"backward");return g.replaceWithFragment(o,n,r)},replaceWithFragment:function(e,t,n){var r=h(e,t),o=v(r,t);return c(o,o.getSelectionAfter(),n)},removeRange:function(e,t,n){var r=void 0,o=void 0,a=void 0,s=void 0;t.getIsBackward()&&(t=t.merge({anchorKey:t.getFocusKey(),anchorOffset:t.getFocusOffset(),focusKey:t.getAnchorKey(),focusOffset:t.getAnchorOffset(),isBackward:!1})),r=t.getAnchorKey(),o=t.getFocusKey(),a=e.getBlockForKey(r),s=e.getBlockForKey(o);var u=t.getStartOffset(),c=t.getEndOffset(),p=a.getEntityAt(u),f=s.getEntityAt(c-1);if(r===o&&p&&p===f){var d=l(e.getEntityMap(),a,s,t,n);return v(e,d)}var m=t;i.draft_segmented_entities_behavior&&(m=l(e.getEntityMap(),a,s,t,n));var y=h(e,m);return v(y,m)},splitBlock:function(e,t){var n=h(e,t),r=v(n,t);return m(r,r.getSelectionAfter())},applyInlineStyle:function(e,t,n){return o.add(e,t,n)},removeInlineStyle:function(e,t,n){return o.remove(e,t,n)},setBlockType:function(e,t,n){return d(e,t,function(e){return e.merge({type:n,depth:0})})},setBlockData:function(e,t,n){return d(e,t,function(e){return e.merge({data:n})})},mergeBlockData:function(e,t,n){return d(e,t,function(e){return e.merge({data:e.getData().merge(n)})})},applyEntity:function(e,t,n){var r=h(e,t);return s(r,t,n)}};e.exports=g},function(e,t,n){"use strict";var r={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,QUESTION_MARK:63,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,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION: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,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,WIN_IME:229};r.isTextModifyingKeyEvent=function(e){var t=e.keyCode;if(e.altKey&&!e.ctrlKey||e.metaKey||t>=r.F1&&t<=r.F12)return!1;switch(t){case r.ALT:case r.CAPS_LOCK:case r.CONTEXT_MENU:case r.CTRL:case r.DOWN:case r.END:case r.ESC:case r.HOME:case r.INSERT:case r.LEFT:case r.MAC_FF_META:case r.META:case r.NUMLOCK:case r.NUM_CENTER:case r.PAGE_DOWN:case r.PAGE_UP:case r.PAUSE:case r.PRINT_SCREEN:case r.RIGHT:case r.SHIFT:case r.UP:case r.WIN_KEY:case r.WIN_KEY_RIGHT:return!1;default:return!0}},r.isCharacterKey=function(e){if(e>=r.ZERO&&e<=r.NINE)return!0;if(e>=r.NUM_ZERO&&e<=r.NUM_MULTIPLY)return!0;if(e>=r.A&&e<=r.Z)return!0;if(-1!==window.navigation.userAgent.indexOf("WebKit")&&0===e)return!0;switch(e){case r.SPACE:case r.QUESTION_MARK:case r.NUM_PLUS:case r.NUM_MINUS:case r.NUM_PERIOD:case r.NUM_DIVISION:case r.SEMICOLON:case r.DASH:case r.EQUALS:case r.COMMA:case r.PERIOD:case r.SLASH:case r.APOSTROPHE:case r.SINGLE_QUOTE:case r.OPEN_SQUARE_BRACKET:case r.BACKSLASH:case r.CLOSE_SQUARE_BRACKET:return!0;default:return!1}},t.a=r},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(11),s=a.Map,l=a.OrderedSet,u=a.Record,c=l(),p={style:c,entity:null},f=u(p),d=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.getStyle=function(){return this.get("style")},t.prototype.getEntity=function(){return this.get("entity")},t.prototype.hasStyle=function(e){return this.getStyle().includes(e)},t.applyStyle=function(e,n){var r=e.set("style",e.getStyle().add(n));return t.create(r)},t.removeStyle=function(e,n){var r=e.set("style",e.getStyle().remove(n));return t.create(r)},t.applyEntity=function(e,n){var r=e.getEntity()===n?e:e.set("entity",n);return t.create(r)},t.create=function(e){if(!e)return h;var n={style:c,entity:null},r=s(n).merge(e),o=v.get(r);if(o)return o;var i=new t(r);return v=v.set(r,i),i},t}(f),h=new d,v=s([[s(p),h]]);d.EMPTY=h,e.exports=d},function(e,t,n){"use strict";var r=n(1),o=n.n(r),i=n(2),a=n.n(i),s=n(7),l=n.n(s),u=n(3),c=n.n(u),p=n(4),f=n.n(p),d=n(0),h=(n.n(d),n(5)),v=n.n(h),m=function(e){function t(){return a()(this,t),c()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return f()(t,e),l()(t,[{key:"getLocale",value:function(){var e=this.props,t=e.componentName,n=e.defaultLocale,r=this.context.antLocale,i=r&&r[t];return o()({},"function"==typeof n?n():n,i||{})}},{key:"getLocaleCode",value:function(){var e=this.context.antLocale,t=e&&e.locale;return e&&e.exist&&!t?"en-us":t}},{key:"render",value:function(){return this.props.children(this.getLocale(),this.getLocaleCode())}}]),t}(d.Component);t.a=m,m.contextTypes={antLocale:v.a.object}},function(e,t,n){"use strict";var r=n(36),o=n.n(r),i={};t.a=function(e,t){e||i[t]||(o()(!1,t),i[t]=!0)}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(25),s=n(11),l=n(78),u=s.List,c=s.Map,p=s.OrderedSet,f=s.Record,d=s.Repeat,h=p(),v={parent:null,characterList:u(),data:c(),depth:0,key:"",text:"",type:"unstyled",children:u(),prevSibling:null,nextSibling:null},m=function(e,t){return e.getStyle()===t.getStyle()},y=function(e,t){return e.getEntity()===t.getEntity()},g=function(e){if(!e)return e;var t=e.characterList,n=e.text;return n&&!t&&(e.characterList=u(d(a.EMPTY,n.length))),e},b=function(e){function t(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:v;return r(this,t),o(this,e.call(this,g(n)))}return i(t,e),t.prototype.getKey=function(){return this.get("key")},t.prototype.getType=function(){return this.get("type")},t.prototype.getText=function(){return this.get("text")},t.prototype.getCharacterList=function(){return this.get("characterList")},t.prototype.getLength=function(){return this.getText().length},t.prototype.getDepth=function(){return this.get("depth")},t.prototype.getData=function(){return this.get("data")},t.prototype.getInlineStyleAt=function(e){var t=this.getCharacterList().get(e);return t?t.getStyle():h},t.prototype.getEntityAt=function(e){var t=this.getCharacterList().get(e);return t?t.getEntity():null},t.prototype.getChildKeys=function(){return this.get("children")},t.prototype.getParentKey=function(){return this.get("parent")},t.prototype.getPrevSiblingKey=function(){return this.get("prevSibling")},t.prototype.getNextSiblingKey=function(){return this.get("nextSibling")},t.prototype.findStyleRanges=function(e,t){l(this.getCharacterList(),m,e,t)},t.prototype.findEntityRanges=function(e,t){l(this.getCharacterList(),y,e,t)},t}(f(v));e.exports=b},function(e,t){var n=e.exports={version:"2.5.3"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(108)("wks"),o=n(83),i=n(40).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t){e.exports=function(e,t,n,r){var o=n?n.call(r,e,t):void 0;if(void 0!==o)return!!o;if(e===t)return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;var i=Object.keys(e),a=Object.keys(t);if(i.length!==a.length)return!1;for(var s=Object.prototype.hasOwnProperty.bind(t),l=0;l<i.length;l++){var u=i[l];if(!s(u))return!1;var c=e[u],p=t[u];if(!1===(o=n?n.call(r,c,p,u):void 0)||void 0===o&&c!==p)return!1}return!0}},function(e,t){function n(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){var r=n(184),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();e.exports=i},function(e,t,n){"use strict";var r=function(e){if(null!=e)return e;throw new Error("Got unexpected null or undefined")};e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=s.a.unstable_batchedUpdates?function(e){s.a.unstable_batchedUpdates(n,e)}:n;return i()(e,t,r)}t.a=r;var o=n(291),i=n.n(o),a=n(9),s=n.n(a)},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){"use strict";function r(e,t,n,r){if(e===n)return!0;if(!n.startsWith(e))return!1;var o=n.slice(e.length);return!!t&&(o=r?r(o):o,a.contains(o,t))}function o(e){return"Windows"===i.platformName?e.replace(/^\s*NT/,""):e}var i=n(444),a=n(447),s=n(448),l=n(449),u={isBrowser:function(e){return r(i.browserName,i.browserFullVersion,e)},isBrowserArchitecture:function(e){return r(i.browserArchitecture,null,e)},isDevice:function(e){return r(i.deviceName,null,e)},isEngine:function(e){return r(i.engineName,i.engineVersion,e)},isPlatform:function(e){return r(i.platformName,i.platformFullVersion,e,o)},isPlatformArchitecture:function(e){return r(i.platformArchitecture,null,e)}};e.exports=s(u,l)},function(e,t,n){"use strict";function r(){for(var e=void 0;void 0===e||o.hasOwnProperty(e)||!isNaN(+e);)e=Math.floor(Math.random()*i).toString(32);return o[e]=!0,e}var o={},i=Math.pow(2,24);e.exports=r},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(48),o=n(166),i=n(103),a=Object.defineProperty;t.f=n(49)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){"use strict";function r(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}function o(){if(void 0!==Se)return Se;Se="";var e=document.createElement("p").style;for(var t in xe)t+"Transform"in e&&(Se=t);return Se}function i(){return o()?o()+"TransitionProperty":"transitionProperty"}function a(){return o()?o()+"Transform":"transform"}function s(e,t){var n=i();n&&(e.style[n]=t,"transitionProperty"!==n&&(e.style.transitionProperty=t))}function l(e,t){var n=a();n&&(e.style[n]=t,"transform"!==n&&(e.style.transform=t))}function u(e){return e.style.transitionProperty||e.style[i()]}function c(e){var t=window.getComputedStyle(e,null),n=t.getPropertyValue("transform")||t.getPropertyValue(a());if(n&&"none"!==n){var r=n.replace(/[^0-9\-.,]/g,"").split(",");return{x:parseFloat(r[12]||r[4],0),y:parseFloat(r[13]||r[5],0)}}return{x:0,y:0}}function p(e,t){var n=window.getComputedStyle(e,null),r=n.getPropertyValue("transform")||n.getPropertyValue(a());if(r&&"none"!==r){var o=void 0,i=r.match(_e);if(i)i=i[1],o=i.split(",").map(function(e){return parseFloat(e,10)}),o[4]=t.x,o[5]=t.y,l(e,"matrix("+o.join(",")+")");else{o=r.match(ke)[1].split(",").map(function(e){return parseFloat(e,10)}),o[12]=t.x,o[13]=t.y,l(e,"matrix3d("+o.join(",")+")")}}else l(e,"translateX("+t.x+"px) translateY("+t.y+"px) translateZ(0)")}function f(e){var t=e.style.display;e.style.display="none",e.offsetHeight,e.style.display=t}function d(e,t,n){var r=n;{if("object"!==(void 0===t?"undefined":Ee(t)))return void 0!==r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):Te(e,t);for(var o in t)t.hasOwnProperty(o)&&d(e,o,t[o])}}function h(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function v(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function m(e){return v(e)}function y(e){return v(e,!0)}function g(e){var t=h(e),n=e.ownerDocument,r=n.defaultView||n.parentWindow;return t.left+=m(r),t.top+=y(r),t}function b(e){return null!==e&&void 0!==e&&e==e.window}function C(e){return b(e)?e.document:9===e.nodeType?e:e.ownerDocument}function w(e,t,n){var r=n,o="",i=C(e);return r=r||i.defaultView.getComputedStyle(e,null),r&&(o=r.getPropertyValue(t)||r[t]),o}function S(e,t){var n=e[Me]&&e[Me][t];if(Ne.test(n)&&!Pe.test(t)){var r=e.style,o=r[Ie],i=e[De][Ie];e[De][Ie]=e[Me][Ie],r[Ie]="fontSize"===t?"1em":n||0,n=r.pixelLeft+Ae,r[Ie]=o,e[De][Ie]=i}return""===n?"auto":n}function x(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function _(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function k(e,t,n){"static"===d(e,"position")&&(e.style.position="relative");var r=-999,o=-999,i=x("left",n),a=x("top",n),l=_(i),c=_(a);"left"!==i&&(r=999),"top"!==a&&(o=999);var p="",h=g(e);("left"in t||"top"in t)&&(p=u(e)||"",s(e,"none")),"left"in t&&(e.style[l]="",e.style[i]=r+"px"),"top"in t&&(e.style[c]="",e.style[a]=o+"px"),f(e);var v=g(e),m={};for(var y in t)if(t.hasOwnProperty(y)){var b=x(y,n),C="left"===y?r:o,w=h[y]-v[y];m[b]=b===y?C+w:C-w}d(e,m),f(e),("left"in t||"top"in t)&&s(e,p);var S={};for(var k in t)if(t.hasOwnProperty(k)){var E=x(k,n),O=t[k]-h[k];S[E]=k===E?m[E]+O:m[E]-O}d(e,S)}function E(e,t){var n=g(e),r=c(e),o={x:r.x,y:r.y};"left"in t&&(o.x=r.x+t.left-n.left),"top"in t&&(o.y=r.y+t.top-n.top),p(e,o)}function O(e,t,n){n.useCssRight||n.useCssBottom?k(e,t,n):n.useCssTransform&&a()in document.body.style?E(e,t,n):k(e,t,n)}function T(e,t){for(var n=0;n<e.length;n++)t(e[n])}function N(e){return"border-box"===Te(e,"boxSizing")}function P(e,t,n){var r={},o=e.style,i=void 0;for(i in t)t.hasOwnProperty(i)&&(r[i]=o[i],o[i]=t[i]);n.call(e);for(i in t)t.hasOwnProperty(i)&&(o[i]=r[i])}function M(e,t,n){var r=0,o=void 0,i=void 0,a=void 0;for(i=0;i<t.length;i++)if(o=t[i])for(a=0;a<n.length;a++){var s=void 0;s="border"===o?""+o+n[a]+"Width":o+n[a],r+=parseFloat(Te(e,s))||0}return r}function D(e,t,n){var r=n;if(b(e))return"width"===t?Fe.viewportWidth(e):Fe.viewportHeight(e);if(9===e.nodeType)return"width"===t?Fe.docWidth(e):Fe.docHeight(e);var o="width"===t?["Left","Right"]:["Top","Bottom"],i="width"===t?e.getBoundingClientRect().width:e.getBoundingClientRect().height,a=Te(e),s=N(e,a),l=0;(null===i||void 0===i||i<=0)&&(i=void 0,l=Te(e,t),(null===l||void 0===l||Number(l)<0)&&(l=e.style[t]||0),l=parseFloat(l)||0),void 0===r&&(r=s?Ke:Re);var u=void 0!==i||s,c=i||l;return r===Re?u?c-M(e,["border","padding"],o,a):l:u?r===Ke?c:c+(r===Le?-M(e,["border"],o,a):M(e,["margin"],o,a)):l+M(e,je.slice(r),o,a)}function I(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=void 0,o=t[0];return 0!==o.offsetWidth?r=D.apply(void 0,t):P(o,Ve,function(){r=D.apply(void 0,t)}),r}function A(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function j(e){if(Be.isWindow(e)||9===e.nodeType)return null;var t=Be.getDocument(e),n=t.body,r=void 0,o=Be.css(e,"position");if("fixed"!==o&&"absolute"!==o)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(r=e.parentNode;r&&r!==n;r=r.parentNode)if("static"!==(o=Be.css(r,"position")))return r;return null}function R(e){if(Be.isWindow(e)||9===e.nodeType)return!1;var t=Be.getDocument(e),n=t.body,r=null;for(r=e.parentNode;r&&r!==n;r=r.parentNode){if("fixed"===Be.css(r,"position"))return!0}return!1}function L(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=We(e),r=Be.getDocument(e),o=r.defaultView||r.parentWindow,i=r.body,a=r.documentElement;n;){if(-1!==navigator.userAgent.indexOf("MSIE")&&0===n.clientWidth||n===i||n===a||"visible"===Be.css(n,"overflow")){if(n===i||n===a)break}else{var s=Be.offset(n);s.left+=n.clientLeft,s.top+=n.clientTop,t.top=Math.max(t.top,s.top),t.right=Math.min(t.right,s.left+n.clientWidth),t.bottom=Math.min(t.bottom,s.top+n.clientHeight),t.left=Math.max(t.left,s.left)}n=We(n)}var l=null;if(!Be.isWindow(e)&&9!==e.nodeType){l=e.style.position;"absolute"===Be.css(e,"position")&&(e.style.position="fixed")}var u=Be.getWindowScrollLeft(o),c=Be.getWindowScrollTop(o),p=Be.viewportWidth(o),f=Be.viewportHeight(o),d=a.scrollWidth,h=a.scrollHeight;if(e.style&&(e.style.position=l),R(e))t.left=Math.max(t.left,u),t.top=Math.max(t.top,c),t.right=Math.min(t.right,u+p),t.bottom=Math.min(t.bottom,c+f);else{var v=Math.max(d,u+p);t.right=Math.min(t.right,v);var m=Math.max(h,c+f);t.bottom=Math.min(t.bottom,m)}return t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}function K(e,t,n,r){var o=Be.clone(e),i={width:t.width,height:t.height};return r.adjustX&&o.left<n.left&&(o.left=n.left),r.resizeWidth&&o.left>=n.left&&o.left+i.width>n.right&&(i.width-=o.left+i.width-n.right),r.adjustX&&o.left+i.width>n.right&&(o.left=Math.max(n.right-i.width,n.left)),r.adjustY&&o.top<n.top&&(o.top=n.top),r.resizeHeight&&o.top>=n.top&&o.top+i.height>n.bottom&&(i.height-=o.top+i.height-n.bottom),r.adjustY&&o.top+i.height>n.bottom&&(o.top=Math.max(n.bottom-i.height,n.top)),Be.mix(o,i)}function F(e){var t=void 0,n=void 0,r=void 0;if(Be.isWindow(e)||9===e.nodeType){var o=Be.getWindow(e);t={left:Be.getWindowScrollLeft(o),top:Be.getWindowScrollTop(o)},n=Be.viewportWidth(o),r=Be.viewportHeight(o)}else t=Be.offset(e),n=Be.outerWidth(e),r=Be.outerHeight(e);return t.width=n,t.height=r,t}function V(e,t){var n=t.charAt(0),r=t.charAt(1),o=e.width,i=e.height,a=e.left,s=e.top;return"c"===n?s+=i/2:"b"===n&&(s+=i),"c"===r?a+=o/2:"r"===r&&(a+=o),{left:a,top:s}}function z(e,t,n,r,o){var i=Ye(t,n[1]),a=Ye(e,n[0]),s=[a.left-i.left,a.top-i.top];return{left:e.left-s[0]+r[0]-o[0],top:e.top-s[1]+r[1]-o[1]}}function B(e,t,n){return e.left<n.left||e.left+t.width>n.right}function W(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function H(e,t,n){return e.left>n.right||e.left+t.width<n.left}function U(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function q(e){var t=He(e),n=qe(e);return!t||n.left+n.width<=t.left||n.top+n.height<=t.top||n.left>=t.right||n.top>=t.bottom}function Y(e,t,n){var r=[];return Be.each(e,function(e){r.push(e.replace(t,function(e){return n[e]}))}),r}function G(e,t){return e[t]=-e[t],e}function X(e,t){return(/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10))||0}function $(e,t){e[0]=X(e[0],t.width),e[1]=X(e[1],t.height)}function J(e,t,n){var r=n.points,o=n.offset||[0,0],i=n.targetOffset||[0,0],a=n.overflow,s=n.target||t,l=n.source||e;o=[].concat(o),i=[].concat(i),a=a||{};var u={},c=0,p=He(l),f=qe(l),d=qe(s);$(o,f),$(i,d);var h=Ge(f,d,r,o,i),v=Be.merge(f,h),m=!q(s);if(p&&(a.adjustX||a.adjustY)&&m){if(a.adjustX&&B(h,f,p)){var y=Y(r,/[lr]/gi,{l:"r",r:"l"}),g=G(o,0),b=G(i,0);H(Ge(f,d,y,g,b),f,p)||(c=1,r=y,o=g,i=b)}if(a.adjustY&&W(h,f,p)){var C=Y(r,/[tb]/gi,{t:"b",b:"t"}),w=G(o,1),S=G(i,1);U(Ge(f,d,C,w,S),f,p)||(c=1,r=C,o=w,i=S)}c&&(h=Ge(f,d,r,o,i),Be.mix(v,h));var x=B(h,f,p),_=W(h,f,p);(x||_)&&(r=n.points,o=n.offset||[0,0],i=n.targetOffset||[0,0]),u.adjustX=a.adjustX&&x,u.adjustY=a.adjustY&&_,(u.adjustX||u.adjustY)&&(v=Ue(h,f,p,u))}return v.width!==f.width&&Be.css(l,"width",Be.width(l)+v.width-f.width),v.height!==f.height&&Be.css(l,"height",Be.height(l)+v.height-f.height),Be.offset(l,{left:v.left,top:v.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform}),{points:r,offset:o,targetOffset:i,overflow:u}}function Z(e){return null!=e&&e==e.window}function Q(e,t){function n(){o&&(clearTimeout(o),o=null)}function r(){n(),o=setTimeout(e,t)}var o=void 0;return r.clear=n,r}function ee(e,t){return e[0]===t[0]&&e[1]===t[1]}function te(e,t,n){var r=e[t]||{};return le()({},r,n)}function ne(e,t,n){var r=n.points;for(var o in e)if(e.hasOwnProperty(o)&&ee(e[o].points,r))return t+"-placement-"+o;return""}function re(e,t){this[e]=t}function oe(){}function ie(){return""}function ae(){return window.document}var se=n(1),le=n.n(se),ue=n(2),ce=n.n(ue),pe=n(3),fe=n.n(pe),de=n(4),he=n.n(de),ve=n(0),me=n.n(ve),ye=n(5),ge=n.n(ye),be=n(9),Ce=n.n(be),we=n(35),Se=void 0,xe={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-"},_e=/matrix\((.*)\)/,ke=/matrix3d\((.*)\)/,Ee="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Oe=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,Te=void 0,Ne=new RegExp("^("+Oe+")(?!px)[a-z%]+$","i"),Pe=/^(top|right|bottom|left)$/,Me="currentStyle",De="runtimeStyle",Ie="left",Ae="px";"undefined"!=typeof window&&(Te=window.getComputedStyle?w:S);var je=["margin","border","padding"],Re=-1,Le=2,Ke=1,Fe={};T(["Width","Height"],function(e){Fe["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],Fe["viewport"+e](n))},Fe["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,i=r.documentElement,a=i[n];return"CSS1Compat"===r.compatMode&&a||o&&o[n]||a}});var Ve={position:"absolute",visibility:"hidden",display:"block"};T(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);Fe["outer"+t]=function(t,n){return t&&I(t,e,n?0:Ke)};var n="width"===e?["Left","Right"]:["Top","Bottom"];Fe[e]=function(t,r){var o=r;if(void 0===o)return t&&I(t,e,Re);if(t){var i=Te(t);return N(t)&&(o+=M(t,["padding","border"],n,i)),d(t,e,o)}}});var ze={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},getDocument:C,offset:function(e,t,n){if(void 0===t)return g(e);O(e,t,n||{})},isWindow:b,each:T,css:d,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);if(e.overflow)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:A,getWindowScrollLeft:function(e){return m(e)},getWindowScrollTop:function(e){return y(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var o=0;o<n.length;o++)ze.mix(e,n[o]);return e},viewportWidth:0,viewportHeight:0};A(ze,Fe);var Be=ze,We=j,He=L,Ue=K,qe=F,Ye=V,Ge=z;J.__getOffsetParent=We,J.__getVisibleRectForElement=He;var Xe=J,$e=n(31),Je=n.n($e),Ze=function(e){function t(){var n,r,o;ce()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=fe()(this,e.call.apply(e,[this].concat(a))),r.forceAlign=function(){var e=r.props;if(!e.disabled){var t=Ce.a.findDOMNode(r);e.onAlign(t,Xe(t,e.target(),e.align))}},o=n,fe()(r,o)}return he()(t,e),t.prototype.componentDidMount=function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()},t.prototype.componentDidUpdate=function(e){var t=!1,n=this.props;if(!n.disabled)if(e.disabled||!Je()(e.align,n.align))t=!0;else{var r=e.target(),o=n.target();Z(r)&&Z(o)?t=!1:r!==o&&(t=!0)}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()},t.prototype.componentWillUnmount=function(){this.stopMonitorWindowResize()},t.prototype.startMonitorWindowResize=function(){this.resizeHandler||(this.bufferMonitor=Q(this.forceAlign,this.props.monitorBufferTime),this.resizeHandler=Object(we.a)(window,"resize",this.bufferMonitor))},t.prototype.stopMonitorWindowResize=function(){this.resizeHandler&&(this.bufferMonitor.clear(),this.resizeHandler.remove(),this.resizeHandler=null)},t.prototype.render=function(){var e=this.props,t=e.childrenProps,n=e.children,r=me.a.Children.only(n);if(t){var o={};for(var i in t)t.hasOwnProperty(i)&&(o[i]=this.props[t[i]]);return me.a.cloneElement(r,o)}return r},t}(ve.Component);Ze.propTypes={childrenProps:ge.a.object,align:ge.a.object.isRequired,target:ge.a.func,onAlign:ge.a.func,monitorBufferTime:ge.a.number,monitorWindowResize:ge.a.bool,disabled:ge.a.bool,children:ge.a.any},Ze.defaultProps={target:function(){return window},onAlign:function(){},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1};var Qe=Ze,et=Qe,tt=n(18),nt=n(17),rt=n.n(nt),ot=function(e){function t(){return ce()(this,t),fe()(this,e.apply(this,arguments))}return he()(t,e),t.prototype.shouldComponentUpdate=function(e){return e.hiddenClassName||e.visible},t.prototype.render=function(){var e=this.props,t=e.hiddenClassName,n=e.visible,r=rt()(e,["hiddenClassName","visible"]);return t||me.a.Children.count(r.children)>1?(!n&&t&&(r.className+=" "+t),me.a.createElement("div",r)):me.a.Children.only(r.children)},t}(ve.Component);ot.propTypes={children:ge.a.any,className:ge.a.string,visible:ge.a.bool,hiddenClassName:ge.a.string};var it=ot,at=function(e){function t(){return ce()(this,t),fe()(this,e.apply(this,arguments))}return he()(t,e),t.prototype.render=function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),me.a.createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:e.style},me.a.createElement(it,{className:e.prefixCls+"-content",visible:e.visible},e.children))},t}(ve.Component);at.propTypes={hiddenClassName:ge.a.string,className:ge.a.string,prefixCls:ge.a.string,onMouseEnter:ge.a.func,onMouseLeave:ge.a.func,children:ge.a.any};var st=at,lt=function(e){function t(n){ce()(this,t);var r=fe()(this,e.call(this,n));return ut.call(r),r.savePopupRef=re.bind(r,"popupInstance"),r.saveAlignRef=re.bind(r,"alignInstance"),r}return he()(t,e),t.prototype.componentDidMount=function(){this.rootNode=this.getPopupDomNode()},t.prototype.getPopupDomNode=function(){return Ce.a.findDOMNode(this.popupInstance)},t.prototype.getMaskTransitionName=function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},t.prototype.getTransitionName=function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},t.prototype.getClassName=function(e){return this.props.prefixCls+" "+this.props.className+" "+e},t.prototype.getPopupElement=function(){var e=this.savePopupRef,t=this.props,n=t.align,r=t.style,o=t.visible,i=t.prefixCls,a=t.destroyPopupOnHide,s=this.getClassName(this.currentAlignClassName||t.getClassNameFromAlign(n)),l=i+"-hidden";o||(this.currentAlignClassName=null);var u=le()({},r,this.getZIndexStyle()),c={className:s,prefixCls:i,ref:e,onMouseEnter:t.onMouseEnter,onMouseLeave:t.onMouseLeave,style:u};return a?me.a.createElement(tt.a,{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},o?me.a.createElement(et,{target:this.getTarget,key:"popup",ref:this.saveAlignRef,monitorWindowResize:!0,align:n,onAlign:this.onAlign},me.a.createElement(st,le()({visible:!0},c),t.children)):null):me.a.createElement(tt.a,{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},me.a.createElement(et,{target:this.getTarget,key:"popup",ref:this.saveAlignRef,monitorWindowResize:!0,xVisible:o,childrenProps:{visible:"xVisible"},disabled:!o,align:n,onAlign:this.onAlign},me.a.createElement(st,le()({hiddenClassName:l},c),t.children)))},t.prototype.getZIndexStyle=function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},t.prototype.getMaskElement=function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=me.a.createElement(it,{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=me.a.createElement(tt.a,{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},t.prototype.render=function(){return me.a.createElement("div",null,this.getMaskElement(),this.getPopupElement())},t}(ve.Component);lt.propTypes={visible:ge.a.bool,style:ge.a.object,getClassNameFromAlign:ge.a.func,onAlign:ge.a.func,getRootDomNode:ge.a.func,onMouseEnter:ge.a.func,align:ge.a.any,destroyPopupOnHide:ge.a.bool,className:ge.a.string,prefixCls:ge.a.string,onMouseLeave:ge.a.func};var ut=function(){var e=this;this.onAlign=function(t,n){var r=e.props,o=r.getClassNameFromAlign(n);e.currentAlignClassName!==o&&(e.currentAlignClassName=o,t.className=e.getClassName(o)),r.onAlign(t,n)},this.getTarget=function(){return e.props.getRootDomNode()}},ct=lt,pt=n(179),ft=n(180),dt=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur","onContextMenu"],ht=!!be.createPortal,vt=function(e){function t(n){ce()(this,t);var r=fe()(this,e.call(this,n));mt.call(r);var o=void 0;return o="popupVisible"in n?!!n.popupVisible:!!n.defaultPopupVisible,r.prevPopupVisible=o,r.state={popupVisible:o},r}return he()(t,e),t.prototype.componentWillMount=function(){var e=this;dt.forEach(function(t){e["fire"+t]=function(n){e.fireEvents(t,n)}})},t.prototype.componentDidMount=function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},t.prototype.componentWillReceiveProps=function(e){var t=e.popupVisible;void 0!==t&&this.setState({popupVisible:t})},t.prototype.componentDidUpdate=function(e,t){var n=this.props,r=this.state,o=function(){t.popupVisible!==r.popupVisible&&n.afterPopupVisibleChange(r.popupVisible)};if(ht||this.renderComponent(null,o),this.prevPopupVisible=t.popupVisible,r.popupVisible){var i=void 0;return this.clickOutsideHandler||!this.isClickToHide()&&!this.isContextMenuToShow()||(i=n.getDocument(),this.clickOutsideHandler=Object(we.a)(i,"mousedown",this.onDocumentClick)),this.touchOutsideHandler||(i=i||n.getDocument(),this.touchOutsideHandler=Object(we.a)(i,"touchstart",this.onDocumentClick)),!this.contextMenuOutsideHandler1&&this.isContextMenuToShow()&&(i=i||n.getDocument(),this.contextMenuOutsideHandler1=Object(we.a)(i,"scroll",this.onContextMenuClose)),void(!this.contextMenuOutsideHandler2&&this.isContextMenuToShow()&&(this.contextMenuOutsideHandler2=Object(we.a)(window,"blur",this.onContextMenuClose)))}this.clearOutsideHandler()},t.prototype.componentWillUnmount=function(){this.clearDelayTimer(),this.clearOutsideHandler()},t.prototype.getPopupDomNode=function(){return this._component&&this._component.getPopupDomNode?this._component.getPopupDomNode():null},t.prototype.getPopupAlign=function(){var e=this.props,t=e.popupPlacement,n=e.popupAlign,r=e.builtinPlacements;return t&&r?te(r,t,n):n},t.prototype.setPopupVisible=function(e){this.clearDelayTimer(),this.state.popupVisible!==e&&("popupVisible"in this.props||this.setState({popupVisible:e}),this.props.onPopupVisibleChange(e))},t.prototype.delaySetPopupVisible=function(e,t){var n=this,r=1e3*t;this.clearDelayTimer(),r?this.delayTimer=setTimeout(function(){n.setPopupVisible(e),n.clearDelayTimer()},r):this.setPopupVisible(e)},t.prototype.clearDelayTimer=function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},t.prototype.clearOutsideHandler=function(){this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.clickOutsideHandler=null),this.contextMenuOutsideHandler1&&(this.contextMenuOutsideHandler1.remove(),this.contextMenuOutsideHandler1=null),this.contextMenuOutsideHandler2&&(this.contextMenuOutsideHandler2.remove(),this.contextMenuOutsideHandler2=null),this.touchOutsideHandler&&(this.touchOutsideHandler.remove(),this.touchOutsideHandler=null)},t.prototype.createTwoChains=function(e){var t=this.props.children.props,n=this.props;return t[e]&&n[e]?this["fire"+e]:t[e]||n[e]},t.prototype.isClickToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},t.prototype.isContextMenuToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("contextMenu")||-1!==n.indexOf("contextMenu")},t.prototype.isClickToHide=function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},t.prototype.isMouseEnterToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseEnter")},t.prototype.isMouseLeaveToHide=function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseLeave")},t.prototype.isFocusToShow=function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("focus")},t.prototype.isBlurToHide=function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("blur")},t.prototype.forcePopupAlign=function(){this.state.popupVisible&&this._component&&this._component.alignInstance&&this._component.alignInstance.forceAlign()},t.prototype.fireEvents=function(e,t){var n=this.props.children.props[e];n&&n(t);var r=this.props[e];r&&r(t)},t.prototype.close=function(){this.setPopupVisible(!1)},t.prototype.render=function(){var e=this,t=this.state.popupVisible,n=this.props,r=n.children,o=me.a.Children.only(r),i={key:"trigger"};this.isContextMenuToShow()?i.onContextMenu=this.onContextMenu:i.onContextMenu=this.createTwoChains("onContextMenu"),this.isClickToHide()||this.isClickToShow()?(i.onClick=this.onClick,i.onMouseDown=this.onMouseDown,i.onTouchStart=this.onTouchStart):(i.onClick=this.createTwoChains("onClick"),i.onMouseDown=this.createTwoChains("onMouseDown"),i.onTouchStart=this.createTwoChains("onTouchStart")),this.isMouseEnterToShow()?i.onMouseEnter=this.onMouseEnter:i.onMouseEnter=this.createTwoChains("onMouseEnter"),this.isMouseLeaveToHide()?i.onMouseLeave=this.onMouseLeave:i.onMouseLeave=this.createTwoChains("onMouseLeave"),this.isFocusToShow()||this.isBlurToHide()?(i.onFocus=this.onFocus,i.onBlur=this.onBlur):(i.onFocus=this.createTwoChains("onFocus"),i.onBlur=this.createTwoChains("onBlur"));var a=me.a.cloneElement(o,i);if(!ht)return me.a.createElement(pt.a,{parent:this,visible:t,autoMount:!1,forceRender:n.forceRender,getComponent:this.getComponent,getContainer:this.getContainer},function(t){var n=t.renderComponent;return e.renderComponent=n,a});var s=void 0;return(t||this._component||n.forceRender)&&(s=me.a.createElement(ft.a,{key:"portal",getContainer:this.getContainer,didUpdate:this.handlePortalUpdate},this.getComponent())),[a,s]},t}(me.a.Component);vt.propTypes={children:ge.a.any,action:ge.a.oneOfType([ge.a.string,ge.a.arrayOf(ge.a.string)]),showAction:ge.a.any,hideAction:ge.a.any,getPopupClassNameFromAlign:ge.a.any,onPopupVisibleChange:ge.a.func,afterPopupVisibleChange:ge.a.func,popup:ge.a.oneOfType([ge.a.node,ge.a.func]).isRequired,popupStyle:ge.a.object,prefixCls:ge.a.string,popupClassName:ge.a.string,popupPlacement:ge.a.string,builtinPlacements:ge.a.object,popupTransitionName:ge.a.oneOfType([ge.a.string,ge.a.object]),popupAnimation:ge.a.any,mouseEnterDelay:ge.a.number,mouseLeaveDelay:ge.a.number,zIndex:ge.a.number,focusDelay:ge.a.number,blurDelay:ge.a.number,getPopupContainer:ge.a.func,getDocument:ge.a.func,forceRender:ge.a.bool,destroyPopupOnHide:ge.a.bool,mask:ge.a.bool,maskClosable:ge.a.bool,onPopupAlign:ge.a.func,popupAlign:ge.a.object,popupVisible:ge.a.bool,defaultPopupVisible:ge.a.bool,maskTransitionName:ge.a.oneOfType([ge.a.string,ge.a.object]),maskAnimation:ge.a.string},vt.defaultProps={prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:ie,getDocument:ae,onPopupVisibleChange:oe,afterPopupVisibleChange:oe,onPopupAlign:oe,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0,action:[],showAction:[],hideAction:[]};var mt=function(){var e=this;this.onMouseEnter=function(t){e.fireEvents("onMouseEnter",t),e.delaySetPopupVisible(!0,e.props.mouseEnterDelay)},this.onMouseLeave=function(t){e.fireEvents("onMouseLeave",t),e.delaySetPopupVisible(!1,e.props.mouseLeaveDelay)},this.onPopupMouseEnter=function(){e.clearDelayTimer()},this.onPopupMouseLeave=function(t){t.relatedTarget&&!t.relatedTarget.setTimeout&&e._component&&e._component.getPopupDomNode&&r(e._component.getPopupDomNode(),t.relatedTarget)||e.delaySetPopupVisible(!1,e.props.mouseLeaveDelay)},this.onFocus=function(t){e.fireEvents("onFocus",t),e.clearDelayTimer(),e.isFocusToShow()&&(e.focusTime=Date.now(),e.delaySetPopupVisible(!0,e.props.focusDelay))},this.onMouseDown=function(t){e.fireEvents("onMouseDown",t),e.preClickTime=Date.now()},this.onTouchStart=function(t){e.fireEvents("onTouchStart",t),e.preTouchTime=Date.now()},this.onBlur=function(t){e.fireEvents("onBlur",t),e.clearDelayTimer(),e.isBlurToHide()&&e.delaySetPopupVisible(!1,e.props.blurDelay)},this.onContextMenu=function(t){t.preventDefault(),e.fireEvents("onContextMenu",t),e.setPopupVisible(!0)},this.onContextMenuClose=function(){e.isContextMenuToShow()&&e.close()},this.onClick=function(t){if(e.fireEvents("onClick",t),e.focusTime){var n=void 0;if(e.preClickTime&&e.preTouchTime?n=Math.min(e.preClickTime,e.preTouchTime):e.preClickTime?n=e.preClickTime:e.preTouchTime&&(n=e.preTouchTime),Math.abs(n-e.focusTime)<20)return;e.focusTime=0}e.preClickTime=0,e.preTouchTime=0,t.preventDefault();var r=!e.state.popupVisible;(e.isClickToHide()&&!r||r&&e.isClickToShow())&&e.setPopupVisible(!e.state.popupVisible)},this.onDocumentClick=function(t){if(!e.props.mask||e.props.maskClosable){var n=t.target,o=Object(be.findDOMNode)(e),i=e.getPopupDomNode();r(o,n)||r(i,n)||e.close()}},this.getRootDomNode=function(){return Object(be.findDOMNode)(e)},this.getPopupClassNameFromAlign=function(t){var n=[],r=e.props,o=r.popupPlacement,i=r.builtinPlacements,a=r.prefixCls;return o&&i&&n.push(ne(i,a,t)),r.getPopupClassNameFromAlign&&n.push(r.getPopupClassNameFromAlign(t)),n.join(" ")},this.getComponent=function(){var t=e.props,n=e.state,r={};return e.isMouseEnterToShow()&&(r.onMouseEnter=e.onPopupMouseEnter),e.isMouseLeaveToHide()&&(r.onMouseLeave=e.onPopupMouseLeave),me.a.createElement(ct,le()({prefixCls:t.prefixCls,destroyPopupOnHide:t.destroyPopupOnHide,visible:n.popupVisible,className:t.popupClassName,action:t.action,align:e.getPopupAlign(),onAlign:t.onPopupAlign,animation:t.popupAnimation,getClassNameFromAlign:e.getPopupClassNameFromAlign},r,{getRootDomNode:e.getRootDomNode,style:t.popupStyle,mask:t.mask,zIndex:t.zIndex,transitionName:t.popupTransitionName,maskAnimation:t.maskAnimation,maskTransitionName:t.maskTransitionName,ref:e.savePopup}),"function"==typeof t.popup?t.popup():t.popup)},this.getContainer=function(){var t=e.props,n=document.createElement("div");return n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",(t.getPopupContainer?t.getPopupContainer(Object(be.findDOMNode)(e)):t.getDocument().body).appendChild(n),n},this.handlePortalUpdate=function(){e.prevPopupVisible!==e.state.popupVisible&&e.props.afterPopupVisibleChange(e.state.popupVisible)},this.savePopup=function(t){e._component=t}};t.a=vt},function(e,t){function n(e){return null!=e&&"object"==typeof e}e.exports=n},function(e,t,n){"use strict";var r=n(421),o=n(77),i=n(25),a=n(437),s=n(54),l=n(147),u=n(150),c=n(215),p=n(438),f=n(217),d=n(98),h=n(22),v=n(213),m=n(12),y=n(158),g=n(231),b=n(65),C=n(500),w=n(229),S=n(503),x=n(39),_=n(232),k=n(508),E={Editor:p,EditorBlock:f,EditorState:m,CompositeDecorator:a,Entity:d,EntityInstance:v,BlockMapBuilder:o,CharacterMetadata:i,ContentBlock:s,ContentState:l,SelectionState:b,AtomicBlockUtils:r,KeyBindingUtil:y,Modifier:h,RichUtils:g,DefaultDraftBlockRenderMap:u,DefaultDraftInlineStyle:c,convertFromHTML:w,convertFromRaw:S,convertToRaw:C,genKey:x,getDefaultKeyBinding:_,getVisibleSelectionRect:k};e.exports=E},function(e,t,n){"use strict";var r=n(422);e.exports=r},function(e,t,n){"use strict";var r=n(181),o=n(121),i=n(100),a=n(182);t.a={locale:"en",Pagination:r.a,DatePicker:o.a,TimePicker:i.a,Calendar:a.a,Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],notFoundContent:"Not Found",searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items"},Select:{notFoundContent:"Not Found"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file"}}},function(e,t,n){var r=n(40),o=n(29),i=n(102),a=n(56),s=function(e,t,n){var l,u,c,p=e&s.F,f=e&s.G,d=e&s.S,h=e&s.P,v=e&s.B,m=e&s.W,y=f?o:o[t]||(o[t]={}),g=y.prototype,b=f?r:d?r[t]:(r[t]||{}).prototype;f&&(n=t);for(l in n)(u=!p&&b&&void 0!==b[l])&&l in y||(c=u?b[l]:n[l],y[l]=f&&"function"!=typeof b[l]?n[l]:v&&u?i(c,r):m&&b[l]==c?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(c):h&&"function"==typeof c?i(Function.call,c):c,h&&((y.virtual||(y.virtual={}))[l]=c,e&s.R&&g&&!g[l]&&a(g,l,c)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,e.exports=s},function(e,t,n){var r=n(57);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){e.exports=!n(68)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){"use strict";function r(e){return"string"==typeof e}function o(e,t){if(null!=e){var n=t?" ":"";return"string"!=typeof e&&"number"!=typeof e&&r(e.type)&&O(e.props.children)?y.cloneElement(e,{},e.props.children.split("").join(n)):"string"==typeof e?(O(e)&&(e=e.split("").join(n)),y.createElement("span",null,e)):e}}var i=n(1),a=n.n(i),s=n(8),l=n.n(s),u=n(2),c=n.n(u),p=n(7),f=n.n(p),d=n(3),h=n.n(d),v=n(4),m=n.n(v),y=n(0),g=n(9),b=n(5),C=n.n(b),w=n(6),S=n.n(w),x=n(20),_=n(14),k=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},E=/^[\u4e00-\u9fa5]{2}$/,O=E.test.bind(E),T=function(e){function t(e){c()(this,t);var n=h()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleClick=function(e){n.setState({clicked:!0}),clearTimeout(n.timeout),n.timeout=window.setTimeout(function(){return n.setState({clicked:!1})},500);var t=n.props.onClick;t&&t(e)},n.state={loading:e.loading,clicked:!1,hasTwoCNChar:!1},n}return m()(t,e),f()(t,[{key:"componentDidMount",value:function(){this.fixTwoCNChar()}},{key:"componentWillReceiveProps",value:function(e){var t=this,n=this.props.loading,r=e.loading;n&&clearTimeout(this.delayTimeout),"boolean"!=typeof r&&r&&r.delay?this.delayTimeout=window.setTimeout(function(){return t.setState({loading:r})},r.delay):this.setState({loading:r})}},{key:"componentDidUpdate",value:function(){this.fixTwoCNChar()}},{key:"componentWillUnmount",value:function(){this.timeout&&clearTimeout(this.timeout),this.delayTimeout&&clearTimeout(this.delayTimeout)}},{key:"fixTwoCNChar",value:function(){var e=Object(g.findDOMNode)(this),t=e.textContent||e.innerText;this.isNeedInserted()&&O(t)?this.state.hasTwoCNChar||this.setState({hasTwoCNChar:!0}):this.state.hasTwoCNChar&&this.setState({hasTwoCNChar:!1})}},{key:"isNeedInserted",value:function(){var e=this.props,t=e.loading,n=e.icon,r=e.children,o=t?"loading":n;return 1===y.Children.count(r)&&(!o||"loading"===o)}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.type,i=n.shape,s=n.size,u=n.className,c=n.htmlType,p=n.children,f=n.icon,d=n.prefixCls,h=n.ghost,v=k(n,["type","shape","size","className","htmlType","children","icon","prefixCls","ghost"]),m=this.state,g=m.loading,b=m.clicked,C=m.hasTwoCNChar,w="";switch(s){case"large":w="lg";break;case"small":w="sm"}var E=v.href?"a":"button",O=S()(d,u,(e={},l()(e,d+"-"+r,r),l()(e,d+"-"+i,i),l()(e,d+"-"+w,w),l()(e,d+"-icon-only",!p&&f),l()(e,d+"-loading",g),l()(e,d+"-clicked",b),l()(e,d+"-background-ghost",h),l()(e,d+"-two-chinese-chars",C),e)),T=g?"loading":f,N=T?y.createElement(_.a,{type:T}):null,P=p||0===p?y.Children.map(p,function(e){return o(e,t.isNeedInserted())}):null;return y.createElement(E,a()({},Object(x.a)(v,["loading"]),{type:v.href?void 0:c||"button",className:O,onClick:this.handleClick}),N,P)}}]),t}(y.Component),N=T;T.__ANT_BUTTON=!0,T.defaultProps={prefixCls:"ant-btn",loading:!1,ghost:!1},T.propTypes={type:C.a.string,shape:C.a.oneOf(["circle","circle-outline"]),size:C.a.oneOf(["large","default","small"]),htmlType:C.a.oneOf(["submit","button","reset"]),onClick:C.a.func,loading:C.a.oneOfType([C.a.bool,C.a.object]),className:C.a.string,icon:C.a.string};var P=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},M=function(e){var t=e.prefixCls,n=void 0===t?"ant-btn-group":t,r=e.size,o=e.className,i=P(e,["prefixCls","size","className"]),s="";switch(r){case"large":s="lg";break;case"small":s="sm"}var u=S()(n,l()({},n+"-"+s,s),o);return y.createElement("div",a()({},i,{className:u}))},D=M;n.d(t,!1,function(){}),n.d(t,!1,function(){}),n.d(t,!1,function(){}),n.d(t,!1,function(){}),n.d(t,!1,function(){}),N.Group=D;t.a=N},function(e,t,n){function r(e){return null==e?void 0===e?l:s:u&&u in Object(e)?i(e):a(e)}var o=n(72),i=n(321),a=n(322),s="[object Null]",l="[object Undefined]",u=o?o.toStringTag:void 0;e.exports=r},function(e,t,n){function r(e,t){var n=i(e,t);return o(n)?n:void 0}var o=n(346),i=n(349);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e,t){return e.getStyle()===t.getStyle()}function s(e,t){return e.getEntity()===t.getEntity()}var l=n(25),u=n(11),c=n(78),p=u.List,f=u.Map,d=u.OrderedSet,h=u.Record,v=u.Repeat,m=d(),y={key:"",type:"unstyled",text:"",characterList:p(),depth:0,data:f()},g=h(y),b=function(e){if(!e)return e;var t=e.characterList,n=e.text;return n&&!t&&(e.characterList=p(v(l.EMPTY,n.length))),e},C=function(e){function t(n){return r(this,t),o(this,e.call(this,b(n)))}return i(t,e),t.prototype.getKey=function(){return this.get("key")},t.prototype.getType=function(){return this.get("type")},t.prototype.getText=function(){return this.get("text")},t.prototype.getCharacterList=function(){return this.get("characterList")},t.prototype.getLength=function(){return this.getText().length},t.prototype.getDepth=function(){return this.get("depth")},t.prototype.getData=function(){return this.get("data")},t.prototype.getInlineStyleAt=function(e){var t=this.getCharacterList().get(e);return t?t.getStyle():m},t.prototype.getEntityAt=function(e){var t=this.getCharacterList().get(e);return t?t.getEntity():null},t.prototype.findStyleRanges=function(e,t){c(this.getCharacterList(),a,e,t)},t.prototype.findEntityRanges=function(e,t){c(this.getCharacterList(),s,e,t)},t}(g);e.exports=C},function(e,t,n){"use strict";function r(e){return f<=e&&e<=v}function o(e,t){if(0<=t&&t<e.length||p(!1),t+1===e.length)return!1;var n=e.charCodeAt(t),r=e.charCodeAt(t+1);return f<=n&&n<=d&&h<=r&&r<=v}function i(e){return m.test(e)}function a(e,t){return 1+r(e.charCodeAt(t))}function s(e){if(!i(e))return e.length;for(var t=0,n=0;n<e.length;n+=a(e,n))t++;return t}function l(e,t,n){if(t=t||0,n=void 0===n?1/0:n||0,!i(e))return e.substr(t,n);var r=e.length;if(r<=0||t>r||n<=0)return"";var o=0;if(t>0){for(;t>0&&o<r;t--)o+=a(e,o);if(o>=r)return""}else if(t<0){for(o=r;t<0&&0<o;t++)o-=a(e,o-1);o<0&&(o=0)}var s=r;if(n<r)for(s=o;n>0&&s<r;n--)s+=a(e,s);return e.substring(o,s)}function u(e,t,n){t=t||0,n=void 0===n?1/0:n||0,t<0&&(t=0),n<0&&(n=0);var r=Math.abs(n-t);return t=t<n?t:n,l(e,t,r)}function c(e){for(var t=[],n=0;n<e.length;n+=a(e,n))t.push(e.codePointAt(n));return t}var p=n(10),f=55296,d=56319,h=56320,v=57343,m=/[\uD800-\uDFFF]/,y={getCodePoints:c,getUTF16Length:a,hasSurrogateUnit:i,isCodeUnitInSurrogateRange:r,isSurrogatePair:o,strlen:s,substring:u,substr:l};e.exports=y},function(e,t,n){var r=n(41),o=n(69);e.exports=n(49)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){var r=n(169),o=n(105);e.exports=function(e){return r(o(e))}},function(e,t){e.exports={}},function(e,t,n){"use strict";t.__esModule=!0;var r=n(294),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,o.default)(e)}},function(e,t,n){"use strict";function r(){}function o(e,t,n){var r=t||"";return e.key||r+"item_"+n}function i(e,t){var n=-1;y.a.Children.forEach(e,function(e){n++,e&&e.type&&e.type.isMenuItemGroup?y.a.Children.forEach(e.props.children,function(e){n++,t(e,n)}):t(e,n)})}function a(e,t,n){e&&!n.find&&y.a.Children.forEach(e,function(e){if(!n.find&&e){var r=e.type;if(!r||!(r.isSubMenu||r.isMenuItem||r.isMenuItemGroup))return;-1!==t.indexOf(e.key)?n.find=!0:e.props.children&&a(e.props.children,t,n)}})}function s(e){return!e.length||e.every(function(e){return!!e.props.disabled})}function l(e,t){var n=t,r=e.children,a=e.eventKey;if(n){var s=void 0;if(i(r,function(e,t){e&&!e.props.disabled&&n===o(e,a,t)&&(s=!0)}),s)return n}return n=null,e.defaultActiveFirst?(i(r,function(e,t){n||!e||e.props.disabled||(n=o(e,a,t))}),n):n}function u(e,t,n){n&&(void 0!==t?(this.instanceArray[e]=this.instanceArray[e]||[],this.instanceArray[e][t]=n):this.instanceArray[e]=n)}var c=n(1),p=n.n(c),f=n(5),d=n.n(f),h=n(15),v=n.n(h),m=n(0),y=n.n(m),g=n(9),b=n.n(g),C=n(23),w=n(120),S=n(6),x=n.n(S),_=n(89),k=n.n(_),E=v()({displayName:"DOMWrap",propTypes:{tag:d.a.string,hiddenClassName:d.a.string,visible:d.a.bool},getDefaultProps:function(){return{tag:"div"}},render:function(){var e=p()({},this.props);e.visible||(e.className=e.className||"",e.className+=" "+e.hiddenClassName);var t=e.tag;return delete e.tag,delete e.hiddenClassName,delete e.visible,y.a.createElement(t,e)}}),O=E,T={propTypes:{focusable:d.a.bool,multiple:d.a.bool,style:d.a.object,defaultActiveFirst:d.a.bool,visible:d.a.bool,activeKey:d.a.string,selectedKeys:d.a.arrayOf(d.a.string),defaultSelectedKeys:d.a.arrayOf(d.a.string),defaultOpenKeys:d.a.arrayOf(d.a.string),openKeys:d.a.arrayOf(d.a.string),children:d.a.any},getDefaultProps:function(){return{prefixCls:"rc-menu",className:"",mode:"vertical",level:1,inlineIndent:24,visible:!0,focusable:!0,style:{}}},getInitialState:function(){var e=this.props;return{activeKey:l(e,e.activeKey)}},componentWillReceiveProps:function(e){var t=void 0;if("activeKey"in e)t={activeKey:l(e,e.activeKey)};else{var n=this.state.activeKey,r=l(e,n);r!==n&&(t={activeKey:r})}t&&this.setState(t)},shouldComponentUpdate:function(e){return this.props.visible||e.visible},componentWillMount:function(){this.instanceArray=[]},onKeyDown:function(e,t){var n=this,r=e.keyCode,o=void 0;if(this.getFlatInstanceArray().forEach(function(t){t&&t.props.active&&t.onKeyDown&&(o=t.onKeyDown(e))}),o)return 1;var i=null;return r!==C.a.UP&&r!==C.a.DOWN||(i=this.step(r===C.a.UP?-1:1)),i?(e.preventDefault(),this.setState({activeKey:i.props.eventKey},function(){k()(b.a.findDOMNode(i),b.a.findDOMNode(n),{onlyScrollIfNeeded:!0}),"function"==typeof t&&t(i)}),1):void 0===i?(e.preventDefault(),this.setState({activeKey:null}),1):void 0},onItemHover:function(e){var t=e.key,n=e.hover;this.setState({activeKey:n?t:null})},getFlatInstanceArray:function(){var e=this.instanceArray;return e.some(function(e){return Array.isArray(e)})&&(e=[],this.instanceArray.forEach(function(t){Array.isArray(t)?e.push.apply(e,t):e.push(t)}),this.instanceArray=e),e},renderCommonMenuItem:function(e,t,n,r){var i=this.state,a=this.props,s=o(e,a.eventKey,t),l=e.props,c=s===i.activeKey,f=p()({mode:a.mode,level:a.level,inlineIndent:a.inlineIndent,renderMenuItem:this.renderMenuItem,rootPrefixCls:a.prefixCls,index:t,parentMenu:this,ref:l.disabled?void 0:Object(w.a)(e.ref,u.bind(this,t,n)),eventKey:s,active:!l.disabled&&c,multiple:a.multiple,onClick:this.onClick,onItemHover:this.onItemHover,openTransitionName:this.getOpenTransitionName(),openAnimation:a.openAnimation,subMenuOpenDelay:a.subMenuOpenDelay,subMenuCloseDelay:a.subMenuCloseDelay,forceSubMenuRender:a.forceSubMenuRender,onOpenChange:this.onOpenChange,onDeselect:this.onDeselect,onSelect:this.onSelect},r);return"inline"===a.mode&&(f.triggerSubMenuAction="click"),y.a.cloneElement(e,f)},renderRoot:function(e){this.instanceArray=[];var t=x()(e.prefixCls,e.className,e.prefixCls+"-"+e.mode),n={className:t,role:"menu","aria-activedescendant":""};return e.id&&(n.id=e.id),e.focusable&&(n.tabIndex="0",n.onKeyDown=this.onKeyDown),y.a.createElement(O,p()({style:e.style,tag:"ul",hiddenClassName:e.prefixCls+"-hidden",visible:e.visible},n),y.a.Children.map(e.children,this.renderMenuItem))},step:function(e){var t=this.getFlatInstanceArray(),n=this.state.activeKey,r=t.length;if(!r)return null;e<0&&(t=t.concat().reverse());var o=-1;if(t.every(function(e,t){return!e||e.props.eventKey!==n||(o=t,!1)}),this.props.defaultActiveFirst||-1===o||!s(t.slice(o,r-1)))for(var i=(o+1)%r,a=i;;){var l=t[a];if(l&&!l.props.disabled)return l;if((a=(a+1+r)%r)===i)return null}}},N=T,P=v()({displayName:"Menu",propTypes:{defaultSelectedKeys:d.a.arrayOf(d.a.string),selectedKeys:d.a.arrayOf(d.a.string),defaultOpenKeys:d.a.arrayOf(d.a.string),openKeys:d.a.arrayOf(d.a.string),mode:d.a.oneOf(["horizontal","vertical","vertical-left","vertical-right","inline"]),getPopupContainer:d.a.func,onClick:d.a.func,onSelect:d.a.func,onDeselect:d.a.func,onDestroy:d.a.func,openTransitionName:d.a.string,openAnimation:d.a.oneOfType([d.a.string,d.a.object]),subMenuOpenDelay:d.a.number,subMenuCloseDelay:d.a.number,forceSubMenuRender:d.a.bool,triggerSubMenuAction:d.a.string,level:d.a.number,selectable:d.a.bool,multiple:d.a.bool,children:d.a.any},mixins:[N],isRootMenu:!0,getDefaultProps:function(){return{selectable:!0,onClick:r,onSelect:r,onOpenChange:r,onDeselect:r,defaultSelectedKeys:[],defaultOpenKeys:[],subMenuOpenDelay:.1,subMenuCloseDelay:.1,triggerSubMenuAction:"hover"}},getInitialState:function(){var e=this.props,t=e.defaultSelectedKeys,n=e.defaultOpenKeys;return"selectedKeys"in e&&(t=e.selectedKeys||[]),"openKeys"in e&&(n=e.openKeys||[]),{selectedKeys:t,openKeys:n}},componentWillReceiveProps:function(e){"selectedKeys"in e&&this.setState({selectedKeys:e.selectedKeys||[]}),"openKeys"in e&&this.setState({openKeys:e.openKeys||[]})},onSelect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys,r=e.key;n=t.multiple?n.concat([r]):[r],"selectedKeys"in t||this.setState({selectedKeys:n}),t.onSelect(p()({},e,{selectedKeys:n}))}},onClick:function(e){this.props.onClick(e)},onOpenChange:function(e){var t=this.props,n=this.state.openKeys.concat(),r=!1,o=function(e){var t=!1;if(e.open)(t=-1===n.indexOf(e.key))&&n.push(e.key);else{var o=n.indexOf(e.key);t=-1!==o,t&&n.splice(o,1)}r=r||t};Array.isArray(e)?e.forEach(o):o(e),r&&("openKeys"in this.props||this.setState({openKeys:n}),t.onOpenChange(n))},onDeselect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys.concat(),r=e.key,o=n.indexOf(r);-1!==o&&n.splice(o,1),"selectedKeys"in t||this.setState({selectedKeys:n}),t.onDeselect(p()({},e,{selectedKeys:n}))}},getOpenTransitionName:function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t},isInlineMode:function(){return"inline"===this.props.mode},lastOpenSubMenu:function(){var e=[],t=this.state.openKeys;return t.length&&(e=this.getFlatInstanceArray().filter(function(e){return e&&-1!==t.indexOf(e.props.eventKey)})),e[0]},renderMenuItem:function(e,t,n){if(!e)return null;var r=this.state,o={openKeys:r.openKeys,selectedKeys:r.selectedKeys,triggerSubMenuAction:this.props.triggerSubMenuAction};return this.renderCommonMenuItem(e,t,n,o)},render:function(){var e=p()({},this.props);return e.className+=" "+e.prefixCls+"-root",this.renderRoot(e)}}),M=P,D=n(42),I=n(18),A=v()({displayName:"SubPopupMenu",propTypes:{onSelect:d.a.func,onClick:d.a.func,onDeselect:d.a.func,onOpenChange:d.a.func,onDestroy:d.a.func,openTransitionName:d.a.string,openAnimation:d.a.oneOfType([d.a.string,d.a.object]),openKeys:d.a.arrayOf(d.a.string),visible:d.a.bool,children:d.a.any},mixins:[N],onDeselect:function(e){this.props.onDeselect(e)},onSelect:function(e){this.props.onSelect(e)},onClick:function(e){this.props.onClick(e)},onOpenChange:function(e){this.props.onOpenChange(e)},onDestroy:function(e){this.props.onDestroy(e)},getOpenTransitionName:function(){return this.props.openTransitionName},renderMenuItem:function(e,t,n){if(!e)return null;var r=this.props,o={openKeys:r.openKeys,selectedKeys:r.selectedKeys,triggerSubMenuAction:r.triggerSubMenuAction};return this.renderCommonMenuItem(e,t,n,o)},render:function(){var e=p()({},this.props),t=this.haveRendered;if(this.haveRendered=!0,this.haveOpened=this.haveOpened||e.visible||e.forceSubMenuRender,!this.haveOpened)return null;var n=!(!t&&e.visible&&"inline"===e.mode);e.className+=" "+e.prefixCls+"-sub";var r={};return e.openTransitionName?r.transitionName=e.openTransitionName:"object"==typeof e.openAnimation&&(r.animation=p()({},e.openAnimation),n||delete r.animation.appear),y.a.createElement(I.a,p()({},r,{showProp:"visible",component:"",transitionAppear:n}),this.renderRoot(e))}}),j=A,R={adjustX:1,adjustY:1},L={topLeft:{points:["bl","tl"],overflow:R,offset:[0,-7]},bottomLeft:{points:["tl","bl"],overflow:R,offset:[0,7]},leftTop:{points:["tr","tl"],overflow:R,offset:[-4,0]},rightTop:{points:["tl","tr"],overflow:R,offset:[4,0]}},K=L,F=0,V={horizontal:"bottomLeft",vertical:"rightTop","vertical-left":"rightTop","vertical-right":"leftTop"},z=v()({displayName:"SubMenu",propTypes:{parentMenu:d.a.object,title:d.a.node,children:d.a.any,selectedKeys:d.a.array,openKeys:d.a.array,onClick:d.a.func,onOpenChange:d.a.func,rootPrefixCls:d.a.string,eventKey:d.a.string,multiple:d.a.bool,active:d.a.bool,onItemHover:d.a.func,onSelect:d.a.func,triggerSubMenuAction:d.a.string,onDeselect:d.a.func,onDestroy:d.a.func,onMouseEnter:d.a.func,onMouseLeave:d.a.func,onTitleMouseEnter:d.a.func,onTitleMouseLeave:d.a.func,onTitleClick:d.a.func},isRootMenu:!1,getDefaultProps:function(){return{onMouseEnter:r,onMouseLeave:r,onTitleMouseEnter:r,onTitleMouseLeave:r,onTitleClick:r,title:""}},getInitialState:function(){return this.isSubMenu=1,{defaultActiveFirst:!1}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){var e=this,t=this.props,n=t.mode,r=t.parentMenu;"horizontal"===n&&r.isRootMenu&&this.isOpen()&&(this.minWidthTimeout=setTimeout(function(){if(e.subMenuTitle&&e.menuInstance){var t=b.a.findDOMNode(e.menuInstance);t.offsetWidth>=e.subMenuTitle.offsetWidth||(t.style.minWidth=e.subMenuTitle.offsetWidth+"px")}},0))},componentWillUnmount:function(){var e=this.props,t=e.onDestroy,n=e.eventKey;t&&t(n),this.minWidthTimeout&&clearTimeout(this.minWidthTimeout),this.mouseenterTimeout&&clearTimeout(this.mouseenterTimeout)},onDestroy:function(e){this.props.onDestroy(e)},onKeyDown:function(e){var t=e.keyCode,n=this.menuInstance,r=this.isOpen();if(t===C.a.ENTER)return this.onTitleClick(e),this.setState({defaultActiveFirst:!0}),!0;if(t===C.a.RIGHT)return r?n.onKeyDown(e):(this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!0})),!0;if(t===C.a.LEFT){var o=void 0;if(!r)return;return o=n.onKeyDown(e),o||(this.triggerOpenChange(!1),o=!0),o}return!r||t!==C.a.UP&&t!==C.a.DOWN?void 0:n.onKeyDown(e)},onOpenChange:function(e){this.props.onOpenChange(e)},onPopupVisibleChange:function(e){this.triggerOpenChange(e,e?"mouseenter":"mouseleave")},onMouseEnter:function(e){var t=this.props,n=t.eventKey,r=t.onMouseEnter;this.setState({defaultActiveFirst:!1}),r({key:n,domEvent:e})},onMouseLeave:function(e){var t=this.props,n=t.parentMenu,r=t.eventKey,o=t.onMouseLeave;n.subMenuInstance=this,o({key:r,domEvent:e})},onTitleMouseEnter:function(e){var t=this.props,n=t.eventKey,r=t.onItemHover,o=t.onTitleMouseEnter;r({key:n,hover:!0}),o({key:n,domEvent:e})},onTitleMouseLeave:function(e){var t=this.props,n=t.parentMenu,r=t.eventKey,o=t.onItemHover,i=t.onTitleMouseLeave;n.subMenuInstance=this,o({key:r,hover:!1}),i({key:r,domEvent:e})},onTitleClick:function(e){var t=this.props;t.onTitleClick({key:t.eventKey,domEvent:e}),"hover"!==t.triggerSubMenuAction&&(this.triggerOpenChange(!this.isOpen(),"click"),this.setState({defaultActiveFirst:!1}))},onSubMenuClick:function(e){this.props.onClick(this.addKeyPath(e))},onSelect:function(e){this.props.onSelect(e)},onDeselect:function(e){this.props.onDeselect(e)},getPrefixCls:function(){return this.props.rootPrefixCls+"-submenu"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},getSelectedClassName:function(){return this.getPrefixCls()+"-selected"},getOpenClassName:function(){return this.props.rootPrefixCls+"-submenu-open"},saveMenuInstance:function(e){this.menuInstance=e},addKeyPath:function(e){return p()({},e,{keyPath:(e.keyPath||[]).concat(this.props.eventKey)})},triggerOpenChange:function(e,t){var n=this,r=this.props.eventKey,o=function(){n.onOpenChange({key:r,item:n,trigger:t,open:e})};"mouseenter"===t?this.mouseenterTimeout=setTimeout(function(){o()},0):o()},isChildrenSelected:function(){var e={find:!1};return a(this.props.children,this.props.selectedKeys,e),e.find},isOpen:function(){return-1!==this.props.openKeys.indexOf(this.props.eventKey)},renderChildren:function(e){var t=this.props,n={mode:"horizontal"===t.mode?"vertical":t.mode,visible:this.isOpen(),level:t.level+1,inlineIndent:t.inlineIndent,focusable:!1,onClick:this.onSubMenuClick,onSelect:this.onSelect,onDeselect:this.onDeselect,onDestroy:this.onDestroy,selectedKeys:t.selectedKeys,eventKey:t.eventKey+"-menu-",openKeys:t.openKeys,openTransitionName:t.openTransitionName,openAnimation:t.openAnimation,onOpenChange:this.onOpenChange,subMenuOpenDelay:t.subMenuOpenDelay,subMenuCloseDelay:t.subMenuCloseDelay,forceSubMenuRender:t.forceSubMenuRender,triggerSubMenuAction:t.triggerSubMenuAction,defaultActiveFirst:this.state.defaultActiveFirst,multiple:t.multiple,prefixCls:t.rootPrefixCls,id:this._menuId,ref:this.saveMenuInstance};return y.a.createElement(j,n,e)},saveSubMenuTitle:function(e){this.subMenuTitle=e},render:function(){var e,t=this.props,n=this.isOpen(),r=this.getPrefixCls(),o="inline"===t.mode,i=x()(r,r+"-"+t.mode,(e={},e[t.className]=!!t.className,e[this.getOpenClassName()]=n,e[this.getActiveClassName()]=t.active||n&&!o,e[this.getDisabledClassName()]=t.disabled,e[this.getSelectedClassName()]=this.isChildrenSelected(),e));this._menuId||(t.eventKey?this._menuId=t.eventKey+"$Menu":this._menuId="$__$"+ ++F+"$Menu");var a={},s={},l={};t.disabled||(a={onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter},s={onClick:this.onTitleClick},l={onMouseEnter:this.onTitleMouseEnter,onMouseLeave:this.onTitleMouseLeave});var u={};o&&(u.paddingLeft=t.inlineIndent*t.level);var c=y.a.createElement("div",p()({ref:this.saveSubMenuTitle,style:u,className:r+"-title"},l,s,{"aria-expanded":n,"aria-owns":this._menuId,"aria-haspopup":"true",title:"string"==typeof t.title?t.title:void 0}),t.title,y.a.createElement("i",{className:r+"-arrow"})),f=this.renderChildren(t.children),d=t.parentMenu.isRootMenu?t.parentMenu.props.getPopupContainer:function(e){return e.parentNode},h=V[t.mode],v="inline"===t.mode?"":t.popupClassName;return y.a.createElement("li",p()({},a,{className:i,style:t.style}),o&&c,o&&f,!o&&y.a.createElement(D.a,{prefixCls:r,popupClassName:r+"-popup "+v,getPopupContainer:d,builtinPlacements:K,popupPlacement:h,popupVisible:n,popup:f,action:t.disabled?[]:[t.triggerSubMenuAction],mouseEnterDelay:t.subMenuOpenDelay,mouseLeaveDelay:t.subMenuCloseDelay,onPopupVisibleChange:this.onPopupVisibleChange,forceRender:t.forceSubMenuRender},c))}});z.isSubMenu=1;var B=z,W=v()({displayName:"MenuItem",propTypes:{rootPrefixCls:d.a.string,eventKey:d.a.string,active:d.a.bool,children:d.a.any,selectedKeys:d.a.array,disabled:d.a.bool,title:d.a.string,onItemHover:d.a.func,onSelect:d.a.func,onClick:d.a.func,onDeselect:d.a.func,parentMenu:d.a.object,onDestroy:d.a.func,onMouseEnter:d.a.func,onMouseLeave:d.a.func},getDefaultProps:function(){return{onSelect:r,onMouseEnter:r,onMouseLeave:r}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey)},onKeyDown:function(e){if(e.keyCode===C.a.ENTER)return this.onClick(e),!0},onMouseLeave:function(e){var t=this.props,n=t.eventKey,r=t.onItemHover,o=t.onMouseLeave;r({key:n,hover:!1}),o({key:n,domEvent:e})},onMouseEnter:function(e){var t=this.props,n=t.eventKey,r=t.onItemHover,o=t.onMouseEnter;r({key:n,hover:!0}),o({key:n,domEvent:e})},onClick:function(e){var t=this.props,n=t.eventKey,r=t.multiple,o=t.onClick,i=t.onSelect,a=t.onDeselect,s=this.isSelected(),l={key:n,keyPath:[n],item:this,domEvent:e};o(l),r?s?a(l):i(l):s||i(l)},getPrefixCls:function(){return this.props.rootPrefixCls+"-item"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getSelectedClassName:function(){return this.getPrefixCls()+"-selected"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},isSelected:function(){return-1!==this.props.selectedKeys.indexOf(this.props.eventKey)},render:function(){var e,t=this.props,n=this.isSelected(),r=x()(this.getPrefixCls(),t.className,(e={},e[this.getActiveClassName()]=!t.disabled&&t.active,e[this.getSelectedClassName()]=n,e[this.getDisabledClassName()]=t.disabled,e)),o=p()({},t.attribute,{title:t.title,className:r,role:"menuitem","aria-selected":n,"aria-disabled":t.disabled}),i={};t.disabled||(i={onClick:this.onClick,onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter});var a=p()({},t.style);return"inline"===t.mode&&(a.paddingLeft=t.inlineIndent*t.level),y.a.createElement("li",p()({},o,i,{style:a}),t.children)}});W.isMenuItem=1;var H=W,U=v()({displayName:"MenuItemGroup",propTypes:{renderMenuItem:d.a.func,index:d.a.number,className:d.a.string,rootPrefixCls:d.a.string},getDefaultProps:function(){return{disabled:!0}},renderInnerMenuItem:function(e,t){var n=this.props;return(0,n.renderMenuItem)(e,n.index,t)},render:function(){var e=this.props,t=e.className,n=void 0===t?"":t,r=e.rootPrefixCls,o=r+"-item-group-title",i=r+"-item-group-list";return y.a.createElement("li",{className:n+" "+r+"-item-group"},y.a.createElement("div",{className:o,title:"string"==typeof e.title?e.title:void 0},e.title),y.a.createElement("ul",{className:i},y.a.Children.map(e.children,this.renderInnerMenuItem)))}});U.isMenuItemGroup=!0;var q=U,Y=v()({displayName:"Divider",propTypes:{className:d.a.string,rootPrefixCls:d.a.string},getDefaultProps:function(){return{disabled:!0}},render:function(){var e=this.props,t=e.className,n=void 0===t?"":t,r=e.rootPrefixCls;return y.a.createElement("li",{className:n+" "+r+"-item-divider"})}}),G=Y;n.d(t,"d",function(){return B}),n.d(t,"b",function(){return H}),n.d(t,!1,function(){return H}),n.d(t,!1,function(){return q}),n.d(t,"c",function(){return q}),n.d(t,"a",function(){return G});t.e=M},function(e,t,n){"use strict";var r=n(8),o=n.n(r),i=n(1),a=n.n(i),s=n(2),l=n.n(s),u=n(7),c=n.n(u),p=n(3),f=n.n(p),d=n(4),h=n.n(d),v=n(0),m=n(5),y=n.n(m),g=n(6),b=n.n(g),C=n(183),w=n(31),S=n.n(w),x=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},_=function(e){function t(){l()(this,t);var e=f()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveCheckbox=function(t){e.rcCheckbox=t},e}return h()(t,e),c()(t,[{key:"shouldComponentUpdate",value:function(e,t,n){return!S()(this.props,e)||!S()(this.state,t)||!S()(this.context.checkboxGroup,n.checkboxGroup)}},{key:"focus",value:function(){this.rcCheckbox.focus()}},{key:"blur",value:function(){this.rcCheckbox.blur()}},{key:"render",value:function(){var e=this.props,t=this.context,n=e.prefixCls,r=e.className,i=e.children,s=e.indeterminate,l=e.style,u=e.onMouseEnter,c=e.onMouseLeave,p=x(e,["prefixCls","className","children","indeterminate","style","onMouseEnter","onMouseLeave"]),f=t.checkboxGroup,d=a()({},p);f&&(d.onChange=function(){return f.toggleOption({label:i,value:e.value})},d.checked=-1!==f.value.indexOf(e.value),d.disabled=e.disabled||f.disabled);var h=b()(r,o()({},n+"-wrapper",!0)),m=b()(o()({},n+"-indeterminate",s));return v.createElement("label",{className:h,style:l,onMouseEnter:u,onMouseLeave:c},v.createElement(C.a,a()({},d,{prefixCls:n,className:m,ref:this.saveCheckbox})),void 0!==i?v.createElement("span",null,i):null)}}]),t}(v.Component),k=_;_.defaultProps={prefixCls:"ant-checkbox",indeterminate:!1},_.contextTypes={checkboxGroup:y.a.any};var E=n(60),O=n.n(E),T=function(e){function t(e){l()(this,t);var n=f()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.toggleOption=function(e){var t=n.state.value.indexOf(e.value),r=[].concat(O()(n.state.value));-1===t?r.push(e.value):r.splice(t,1),"value"in n.props||n.setState({value:r});var o=n.props.onChange;o&&o(r)},n.state={value:e.value||e.defaultValue||[]},n}return h()(t,e),c()(t,[{key:"getChildContext",value:function(){return{checkboxGroup:{toggleOption:this.toggleOption,value:this.state.value,disabled:this.props.disabled}}}},{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value||[]})}},{key:"shouldComponentUpdate",value:function(e,t){return!S()(this.props,e)||!S()(this.state,t)}},{key:"getOptions",value:function(){return this.props.options.map(function(e){return"string"==typeof e?{label:e,value:e}:e})}},{key:"render",value:function(){var e=this,t=this.props,n=this.state,r=t.prefixCls,o=t.className,i=t.style,a=t.options,s=t.children;a&&a.length>0&&(s=this.getOptions().map(function(o){return v.createElement(k,{key:o.value,disabled:"disabled"in o?o.disabled:t.disabled,value:o.value,checked:-1!==n.value.indexOf(o.value),onChange:function(){return e.toggleOption(o)},className:r+"-item"},o.label)}));var l=b()(r,o);return v.createElement("div",{className:l,style:i},s)}}]),t}(v.Component),N=T;T.defaultProps={options:[],prefixCls:"ant-checkbox-group"},T.propTypes={defaultValue:y.a.array,value:y.a.array,options:y.a.array.isRequired,onChange:y.a.func},T.childContextTypes={checkboxGroup:y.a.any},n.d(t,!1,function(){}),n.d(t,!1,function(){}),n.d(t,!1,function(){}),n.d(t,!1,function(){}),k.Group=N;t.a=k},function(e,t,n){"use strict";function r(e){return"boolean"==typeof e?e?D:I:m()({},I,e)}function o(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.arrowWidth,n=void 0===t?5:t,o=e.horizontalArrowShift,i=void 0===o?16:o,a=e.verticalArrowShift,s=void 0===a?12:a,l=e.autoAdjustOverflow,u=void 0===l||l,c={left:{points:["cr","cl"],offset:[-4,0]},right:{points:["cl","cr"],offset:[4,0]},top:{points:["bc","tc"],offset:[0,-4]},bottom:{points:["tc","bc"],offset:[0,4]},topLeft:{points:["bl","tc"],offset:[-(i+n),-4]},leftTop:{points:["tr","cl"],offset:[-4,-(s+n)]},topRight:{points:["br","tc"],offset:[i+n,-4]},rightTop:{points:["tl","cr"],offset:[4,-(s+n)]},bottomRight:{points:["tr","bc"],offset:[i+n,4]},rightBottom:{points:["bl","cr"],offset:[4,s+n]},bottomLeft:{points:["tl","bc"],offset:[-(i+n),4]},leftBottom:{points:["br","cl"],offset:[-4,s+n]}};return Object.keys(c).forEach(function(t){c[t]=e.arrowPointAtCenter?m()({},c[t],{overflow:r(u),targetOffset:A}):m()({},E[t],{overflow:r(u)})}),c}var i=n(8),a=n.n(i),s=n(2),l=n.n(s),u=n(7),c=n.n(u),p=n(3),f=n.n(p),d=n(4),h=n.n(d),v=n(1),m=n.n(v),y=n(0),g=n.n(y),b=n(17),C=n.n(b),w=n(5),S=n.n(w),x=n(42),_={adjustX:1,adjustY:1},k=[0,0],E={left:{points:["cr","cl"],overflow:_,offset:[-4,0],targetOffset:k},right:{points:["cl","cr"],overflow:_,offset:[4,0],targetOffset:k},top:{points:["bc","tc"],overflow:_,offset:[0,-4],targetOffset:k},bottom:{points:["tc","bc"],overflow:_,offset:[0,4],targetOffset:k},topLeft:{points:["bl","tl"],overflow:_,offset:[0,-4],targetOffset:k},leftTop:{points:["tr","tl"],overflow:_,offset:[-4,0],targetOffset:k},topRight:{points:["br","tr"],overflow:_,offset:[0,-4],targetOffset:k},rightTop:{points:["tl","tr"],overflow:_,offset:[4,0],targetOffset:k},bottomRight:{points:["tr","br"],overflow:_,offset:[0,4],targetOffset:k},rightBottom:{points:["bl","br"],overflow:_,offset:[4,0],targetOffset:k},bottomLeft:{points:["tl","bl"],overflow:_,offset:[0,4],targetOffset:k},leftBottom:{points:["br","bl"],overflow:_,offset:[-4,0],targetOffset:k}},O=function(e){function t(){var n,r,o;l()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=f()(this,e.call.apply(e,[this].concat(a))),r.getPopupElement=function(){var e=r.props,t=e.arrowContent,n=e.overlay,o=e.prefixCls,i=e.id;return[g.a.createElement("div",{className:o+"-arrow",key:"arrow"},t),g.a.createElement("div",{className:o+"-inner",key:"content",id:i},"function"==typeof n?n():n)]},r.saveTrigger=function(e){r.trigger=e},o=n,f()(r,o)}return h()(t,e),t.prototype.getPopupDomNode=function(){return this.trigger.getPopupDomNode()},t.prototype.render=function(){var e=this.props,t=e.overlayClassName,n=e.trigger,r=e.mouseEnterDelay,o=e.mouseLeaveDelay,i=e.overlayStyle,a=e.prefixCls,s=e.children,l=e.onVisibleChange,u=e.afterVisibleChange,c=e.transitionName,p=e.animation,f=e.placement,d=e.align,h=e.destroyTooltipOnHide,v=e.defaultVisible,y=e.getTooltipContainer,b=C()(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","afterVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),w=m()({},b);return"visible"in this.props&&(w.popupVisible=this.props.visible),g.a.createElement(x.a,m()({popupClassName:t,ref:this.saveTrigger,prefixCls:a,popup:this.getPopupElement,action:n,builtinPlacements:E,popupPlacement:f,popupAlign:d,getPopupContainer:y,onPopupVisibleChange:l,afterPopupVisibleChange:u,popupTransitionName:c,popupAnimation:p,defaultPopupVisible:v,destroyPopupOnHide:h,mouseLeaveDelay:o,popupStyle:i,mouseEnterDelay:r},w),s)},t}(y.Component);O.propTypes={trigger:S.a.any,children:S.a.any,defaultVisible:S.a.bool,visible:S.a.bool,placement:S.a.string,transitionName:S.a.oneOfType([S.a.string,S.a.object]),animation:S.a.any,onVisibleChange:S.a.func,afterVisibleChange:S.a.func,overlay:S.a.oneOfType([S.a.node,S.a.func]).isRequired,overlayStyle:S.a.object,overlayClassName:S.a.string,prefixCls:S.a.string,mouseEnterDelay:S.a.number,mouseLeaveDelay:S.a.number,getTooltipContainer:S.a.func,destroyTooltipOnHide:S.a.bool,align:S.a.object,arrowContent:S.a.any,id:S.a.string},O.defaultProps={prefixCls:"rc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null};var T=O,N=T,P=n(6),M=n.n(P),D={adjustX:1,adjustY:1},I={adjustX:0,adjustY:0},A=[0,0];n.d(t,!1,function(){}),n.d(t,!1,function(){});var j=function(e,t){var n={},r=m()({},e);return t.forEach(function(t){e&&t in e&&(n[t]=e[t],delete r[t])}),{picked:n,omited:r}},R=function(e){function t(e){l()(this,t);var n=f()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onVisibleChange=function(e){var t=n.props.onVisibleChange;"visible"in n.props||n.setState({visible:!n.isNoTitle()&&e}),t&&!n.isNoTitle()&&t(e)},n.onPopupAlign=function(e,t){var r=n.getPlacements(),o=Object.keys(r).filter(function(e){return r[e].points[0]===t.points[0]&&r[e].points[1]===t.points[1]})[0];if(o){var i=e.getBoundingClientRect(),a={top:"50%",left:"50%"};o.indexOf("top")>=0||o.indexOf("Bottom")>=0?a.top=i.height-t.offset[1]+"px":(o.indexOf("Top")>=0||o.indexOf("bottom")>=0)&&(a.top=-t.offset[1]+"px"),o.indexOf("left")>=0||o.indexOf("Right")>=0?a.left=i.width-t.offset[0]+"px":(o.indexOf("right")>=0||o.indexOf("Left")>=0)&&(a.left=-t.offset[0]+"px"),e.style.transformOrigin=a.left+" "+a.top}},n.saveTooltip=function(e){n.tooltip=e},n.state={visible:!!e.visible||!!e.defaultVisible},n}return h()(t,e),c()(t,[{key:"componentWillReceiveProps",value:function(e){"visible"in e&&this.setState({visible:e.visible})}},{key:"getPopupDomNode",value:function(){return this.tooltip.getPopupDomNode()}},{key:"getPlacements",value:function(){var e=this.props,t=e.builtinPlacements,n=e.arrowPointAtCenter,r=e.autoAdjustOverflow;return t||o({arrowPointAtCenter:n,verticalArrowShift:8,autoAdjustOverflow:r})}},{key:"isHoverTrigger",value:function(){var e=this.props.trigger;return!e||"hover"===e||!!Array.isArray(e)&&e.indexOf("hover")>=0}},{key:"getDisabledCompatibleChildren",value:function(e){if((e.type.__ANT_BUTTON||"button"===e.type)&&e.props.disabled&&this.isHoverTrigger()){var t=j(e.props.style,["position","left","right","top","bottom","float","display","zIndex"]),n=t.picked,r=t.omited,o=m()({display:"inline-block"},n,{cursor:"not-allowed"}),i=m()({},r,{pointerEvents:"none"}),a=Object(y.cloneElement)(e,{style:i,className:null});return y.createElement("span",{style:o,className:e.props.className},a)}return e}},{key:"isNoTitle",value:function(){var e=this.props,t=e.title,n=e.overlay;return!t&&!n}},{key:"render",value:function(){var e=this.props,t=this.state,n=e.prefixCls,r=e.title,o=e.overlay,i=e.openClassName,s=e.getPopupContainer,l=e.getTooltipContainer,u=e.children,c=t.visible;"visible"in e||!this.isNoTitle()||(c=!1);var p=this.getDisabledCompatibleChildren(y.isValidElement(u)?u:y.createElement("span",null,u)),f=p.props,d=M()(f.className,a()({},i||n+"-open",!0));return y.createElement(N,m()({},this.props,{getTooltipContainer:s||l,ref:this.saveTooltip,builtinPlacements:this.getPlacements(),overlay:o||r||"",visible:c,onVisibleChange:this.onVisibleChange,onPopupAlign:this.onPopupAlign}),c?Object(y.cloneElement)(p,{className:d}):p)}}]),t}(y.Component);t.a=R;R.defaultProps={prefixCls:"ant-tooltip",placement:"top",transitionName:"zoom-big-fast",mouseEnterDelay:.1,mouseLeaveDelay:.1,arrowPointAtCenter:!1,autoAdjustOverflow:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.create=t.connect=t.Provider=void 0;var o=n(372),i=r(o),a=n(373),s=r(a),l=n(374),u=r(l);t.Provider=i.default,t.connect=s.default,t.create=u.default},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(11),s=a.Record,l={anchorKey:"",anchorOffset:0,focusKey:"",focusOffset:0,isBackward:!1,hasFocus:!1},u=s(l),c=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.serialize=function(){return"Anchor: "+this.getAnchorKey()+":"+this.getAnchorOffset()+", Focus: "+this.getFocusKey()+":"+this.getFocusOffset()+", Is Backward: "+String(this.getIsBackward())+", Has Focus: "+String(this.getHasFocus())},t.prototype.getAnchorKey=function(){return this.get("anchorKey")},t.prototype.getAnchorOffset=function(){return this.get("anchorOffset")},t.prototype.getFocusKey=function(){return this.get("focusKey")},t.prototype.getFocusOffset=function(){return this.get("focusOffset")},t.prototype.getIsBackward=function(){return this.get("isBackward")},t.prototype.getHasFocus=function(){return this.get("hasFocus")},t.prototype.hasEdgeWithin=function(e,t,n){var r=this.getAnchorKey(),o=this.getFocusKey();if(r===o&&r===e){var i=this.getStartOffset();return t<=this.getEndOffset()&&i<=n}if(e!==r&&e!==o)return!1;var a=e===r?this.getAnchorOffset():this.getFocusOffset();return t<=a&&n>=a},t.prototype.isCollapsed=function(){return this.getAnchorKey()===this.getFocusKey()&&this.getAnchorOffset()===this.getFocusOffset()},t.prototype.getStartKey=function(){return this.getIsBackward()?this.getFocusKey():this.getAnchorKey()},t.prototype.getStartOffset=function(){return this.getIsBackward()?this.getFocusOffset():this.getAnchorOffset()},t.prototype.getEndKey=function(){return this.getIsBackward()?this.getAnchorKey():this.getFocusKey()},t.prototype.getEndOffset=function(){return this.getIsBackward()?this.getAnchorOffset():this.getFocusOffset()},t.createEmpty=function(e){return new t({anchorKey:e,anchorOffset:0,focusKey:e,focusOffset:0,isBackward:!1,hasFocus:!1})},t}(u);e.exports=c},function(e,t,n){"use strict";function r(e){return"object"==typeof e?Object.keys(e).filter(function(t){return e[t]}).map(o).join(" "):Array.prototype.map.call(arguments,o).join(" ")}function o(e){return e.replace(/\//g,"-")}e.exports=r},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){"use strict";function e(e,t){t&&(e.prototype=Object.create(t.prototype)),e.prototype.constructor=e}function t(e){return i(e)?e:N(e)}function n(e){return a(e)?e:P(e)}function r(e){return s(e)?e:M(e)}function o(e){return i(e)&&!l(e)?e:D(e)}function i(e){return!(!e||!e[un])}function a(e){return!(!e||!e[cn])}function s(e){return!(!e||!e[pn])}function l(e){return a(e)||s(e)}function u(e){return!(!e||!e[fn])}function c(e){return e.value=!1,e}function p(e){e&&(e.value=!0)}function f(){}function d(e,t){t=t||0;for(var n=Math.max(0,e.length-t),r=new Array(n),o=0;o<n;o++)r[o]=e[o+t];return r}function h(e){return void 0===e.size&&(e.size=e.__iterate(m)),e.size}function v(e,t){if("number"!=typeof t){var n=t>>>0;if(""+n!==t||4294967295===n)return NaN;t=n}return t<0?h(e)+t:t}function m(){return!0}function y(e,t,n){return(0===e||void 0!==n&&e<=-n)&&(void 0===t||void 0!==n&&t>=n)}function g(e,t){return C(e,t,0)}function b(e,t){return C(e,t,t)}function C(e,t,n){return void 0===e?n:e<0?Math.max(0,t+e):void 0===t?e:Math.min(t,e)}function w(e){this.next=e}function S(e,t,n,r){var o=0===e?t:1===e?n:[t,n];return r?r.value=o:r={value:o,done:!1},r}function x(){return{value:void 0,done:!0}}function _(e){return!!O(e)}function k(e){return e&&"function"==typeof e.next}function E(e){var t=O(e);return t&&t.call(e)}function O(e){var t=e&&(Sn&&e[Sn]||e[xn]);if("function"==typeof t)return t}function T(e){return e&&"number"==typeof e.length}function N(e){return null===e||void 0===e?K():i(e)?e.toSeq():z(e)}function P(e){return null===e||void 0===e?K().toKeyedSeq():i(e)?a(e)?e.toSeq():e.fromEntrySeq():F(e)}function M(e){return null===e||void 0===e?K():i(e)?a(e)?e.entrySeq():e.toIndexedSeq():V(e)}function D(e){return(null===e||void 0===e?K():i(e)?a(e)?e.entrySeq():e:V(e)).toSetSeq()}function I(e){this._array=e,this.size=e.length}function A(e){var t=Object.keys(e);this._object=e,this._keys=t,this.size=t.length}function j(e){this._iterable=e,this.size=e.length||e.size}function R(e){this._iterator=e,this._iteratorCache=[]}function L(e){return!(!e||!e[kn])}function K(){return En||(En=new I([]))}function F(e){var t=Array.isArray(e)?new I(e).fromEntrySeq():k(e)?new R(e).fromEntrySeq():_(e)?new j(e).fromEntrySeq():"object"==typeof e?new A(e):void 0;if(!t)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+e);return t}function V(e){var t=B(e);if(!t)throw new TypeError("Expected Array or iterable object of values: "+e);return t}function z(e){var t=B(e)||"object"==typeof e&&new A(e);if(!t)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+e);return t}function B(e){return T(e)?new I(e):k(e)?new R(e):_(e)?new j(e):void 0}function W(e,t,n,r){var o=e._cache;if(o){for(var i=o.length-1,a=0;a<=i;a++){var s=o[n?i-a:a];if(!1===t(s[1],r?s[0]:a,e))return a+1}return a}return e.__iterateUncached(t,n)}function H(e,t,n,r){var o=e._cache;if(o){var i=o.length-1,a=0;return new w(function(){var e=o[n?i-a:a];return a++>i?x():S(t,r?e[0]:a-1,e[1])})}return e.__iteratorUncached(t,n)}function U(e,t){return t?q(t,e,"",{"":e}):Y(e)}function q(e,t,n,r){return Array.isArray(t)?e.call(r,n,M(t).map(function(n,r){return q(e,n,r,t)})):G(t)?e.call(r,n,P(t).map(function(n,r){return q(e,n,r,t)})):t}function Y(e){return Array.isArray(e)?M(e).map(Y).toList():G(e)?P(e).map(Y).toMap():e}function G(e){return e&&(e.constructor===Object||void 0===e.constructor)}function X(e,t){if(e===t||e!==e&&t!==t)return!0;if(!e||!t)return!1;if("function"==typeof e.valueOf&&"function"==typeof t.valueOf){if(e=e.valueOf(),t=t.valueOf(),e===t||e!==e&&t!==t)return!0;if(!e||!t)return!1}return!("function"!=typeof e.equals||"function"!=typeof t.equals||!e.equals(t))}function $(e,t){if(e===t)return!0;if(!i(t)||void 0!==e.size&&void 0!==t.size&&e.size!==t.size||void 0!==e.__hash&&void 0!==t.__hash&&e.__hash!==t.__hash||a(e)!==a(t)||s(e)!==s(t)||u(e)!==u(t))return!1;if(0===e.size&&0===t.size)return!0;var n=!l(e);if(u(e)){var r=e.entries();return t.every(function(e,t){var o=r.next().value;return o&&X(o[1],e)&&(n||X(o[0],t))})&&r.next().done}var o=!1;if(void 0===e.size)if(void 0===t.size)"function"==typeof e.cacheResult&&e.cacheResult();else{o=!0;var c=e;e=t,t=c}var p=!0,f=t.__iterate(function(t,r){if(n?!e.has(t):o?!X(t,e.get(r,mn)):!X(e.get(r,mn),t))return p=!1,!1});return p&&e.size===f}function J(e,t){if(!(this instanceof J))return new J(e,t);if(this._value=e,this.size=void 0===t?1/0:Math.max(0,t),0===this.size){if(On)return On;On=this}}function Z(e,t){if(!e)throw new Error(t)}function Q(e,t,n){if(!(this instanceof Q))return new Q(e,t,n);if(Z(0!==n,"Cannot step a Range by 0"),e=e||0,void 0===t&&(t=1/0),n=void 0===n?1:Math.abs(n),t<e&&(n=-n),this._start=e,this._end=t,this._step=n,this.size=Math.max(0,Math.ceil((t-e)/n-1)+1),0===this.size){if(Tn)return Tn;Tn=this}}function ee(){throw TypeError("Abstract")}function te(){}function ne(){}function re(){}function oe(e){return e>>>1&1073741824|3221225471&e}function ie(e){if(!1===e||null===e||void 0===e)return 0;if("function"==typeof e.valueOf&&(!1===(e=e.valueOf())||null===e||void 0===e))return 0;if(!0===e)return 1;var t=typeof e;if("number"===t){if(e!==e||e===1/0)return 0;var n=0|e;for(n!==e&&(n^=4294967295*e);e>4294967295;)e/=4294967295,n^=e;return oe(n)}if("string"===t)return e.length>Rn?ae(e):se(e);if("function"==typeof e.hashCode)return e.hashCode();if("object"===t)return le(e);if("function"==typeof e.toString)return se(e.toString());throw new Error("Value type "+t+" cannot be hashed.")}function ae(e){var t=Fn[e];return void 0===t&&(t=se(e),Kn===Ln&&(Kn=0,Fn={}),Kn++,Fn[e]=t),t}function se(e){for(var t=0,n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return oe(t)}function le(e){var t;if(In&&void 0!==(t=Nn.get(e)))return t;if(void 0!==(t=e[jn]))return t;if(!Dn){if(void 0!==(t=e.propertyIsEnumerable&&e.propertyIsEnumerable[jn]))return t;if(void 0!==(t=ue(e)))return t}if(t=++An,1073741824&An&&(An=0),In)Nn.set(e,t);else{if(void 0!==Mn&&!1===Mn(e))throw new Error("Non-extensible objects are not allowed as keys.");if(Dn)Object.defineProperty(e,jn,{enumerable:!1,configurable:!1,writable:!1,value:t});else if(void 0!==e.propertyIsEnumerable&&e.propertyIsEnumerable===e.constructor.prototype.propertyIsEnumerable)e.propertyIsEnumerable=function(){return this.constructor.prototype.propertyIsEnumerable.apply(this,arguments)},e.propertyIsEnumerable[jn]=t;else{if(void 0===e.nodeType)throw new Error("Unable to set a non-enumerable property on object.");e[jn]=t}}return t}function ue(e){if(e&&e.nodeType>0)switch(e.nodeType){case 1:return e.uniqueID;case 9:return e.documentElement&&e.documentElement.uniqueID}}function ce(e){Z(e!==1/0,"Cannot perform this action with an infinite size.")}function pe(e){return null===e||void 0===e?Se():fe(e)&&!u(e)?e:Se().withMutations(function(t){var r=n(e);ce(r.size),r.forEach(function(e,n){return t.set(n,e)})})}function fe(e){return!(!e||!e[Vn])}function de(e,t){this.ownerID=e,this.entries=t}function he(e,t,n){this.ownerID=e,this.bitmap=t,this.nodes=n}function ve(e,t,n){this.ownerID=e,this.count=t,this.nodes=n}function me(e,t,n){this.ownerID=e,this.keyHash=t,this.entries=n}function ye(e,t,n){this.ownerID=e,this.keyHash=t,this.entry=n}function ge(e,t,n){this._type=t,this._reverse=n,this._stack=e._root&&Ce(e._root)}function be(e,t){return S(e,t[0],t[1])}function Ce(e,t){return{node:e,index:0,__prev:t}}function we(e,t,n,r){var o=Object.create(zn);return o.size=e,o._root=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function Se(){return Bn||(Bn=we(0))}function xe(e,t,n){var r,o;if(e._root){var i=c(yn),a=c(gn);if(r=_e(e._root,e.__ownerID,0,void 0,t,n,i,a),!a.value)return e;o=e.size+(i.value?n===mn?-1:1:0)}else{if(n===mn)return e;o=1,r=new de(e.__ownerID,[[t,n]])}return e.__ownerID?(e.size=o,e._root=r,e.__hash=void 0,e.__altered=!0,e):r?we(o,r):Se()}function _e(e,t,n,r,o,i,a,s){return e?e.update(t,n,r,o,i,a,s):i===mn?e:(p(s),p(a),new ye(t,r,[o,i]))}function ke(e){return e.constructor===ye||e.constructor===me}function Ee(e,t,n,r,o){if(e.keyHash===r)return new me(t,r,[e.entry,o]);var i,a=(0===n?e.keyHash:e.keyHash>>>n)&vn,s=(0===n?r:r>>>n)&vn;return new he(t,1<<a|1<<s,a===s?[Ee(e,t,n+dn,r,o)]:(i=new ye(t,r,o),a<s?[e,i]:[i,e]))}function Oe(e,t,n,r){e||(e=new f);for(var o=new ye(e,ie(n),[n,r]),i=0;i<t.length;i++){var a=t[i];o=o.update(e,0,void 0,a[0],a[1])}return o}function Te(e,t,n,r){for(var o=0,i=0,a=new Array(n),s=0,l=1,u=t.length;s<u;s++,l<<=1){var c=t[s];void 0!==c&&s!==r&&(o|=l,a[i++]=c)}return new he(e,o,a)}function Ne(e,t,n,r,o){for(var i=0,a=new Array(hn),s=0;0!==n;s++,n>>>=1)a[s]=1&n?t[i++]:void 0;return a[r]=o,new ve(e,i+1,a)}function Pe(e,t,r){for(var o=[],a=0;a<r.length;a++){var s=r[a],l=n(s);i(s)||(l=l.map(function(e){return U(e)})),o.push(l)}return Ie(e,t,o)}function Me(e,t,n){return e&&e.mergeDeep&&i(t)?e.mergeDeep(t):X(e,t)?e:t}function De(e){return function(t,n,r){if(t&&t.mergeDeepWith&&i(n))return t.mergeDeepWith(e,n);var o=e(t,n,r);return X(t,o)?t:o}}function Ie(e,t,n){return n=n.filter(function(e){return 0!==e.size}),0===n.length?e:0!==e.size||e.__ownerID||1!==n.length?e.withMutations(function(e){for(var r=t?function(n,r){e.update(r,mn,function(e){return e===mn?n:t(e,n,r)})}:function(t,n){e.set(n,t)},o=0;o<n.length;o++)n[o].forEach(r)}):e.constructor(n[0])}function Ae(e,t,n,r){var o=e===mn,i=t.next();if(i.done){var a=o?n:e,s=r(a);return s===a?e:s}Z(o||e&&e.set,"invalid keyPath");var l=i.value,u=o?mn:e.get(l,mn),c=Ae(u,t,n,r);return c===u?e:c===mn?e.remove(l):(o?Se():e).set(l,c)}function je(e){return e-=e>>1&1431655765,e=(858993459&e)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,127&(e+=e>>16)}function Re(e,t,n,r){var o=r?e:d(e);return o[t]=n,o}function Le(e,t,n,r){var o=e.length+1;if(r&&t+1===o)return e[t]=n,e;for(var i=new Array(o),a=0,s=0;s<o;s++)s===t?(i[s]=n,a=-1):i[s]=e[s+a];return i}function Ke(e,t,n){var r=e.length-1;if(n&&t===r)return e.pop(),e;for(var o=new Array(r),i=0,a=0;a<r;a++)a===t&&(i=1),o[a]=e[a+i];return o}function Fe(e){var t=He();if(null===e||void 0===e)return t;if(Ve(e))return e;var n=r(e),o=n.size;return 0===o?t:(ce(o),o>0&&o<hn?We(0,o,dn,null,new ze(n.toArray())):t.withMutations(function(e){e.setSize(o),n.forEach(function(t,n){return e.set(n,t)})}))}function Ve(e){return!(!e||!e[qn])}function ze(e,t){this.array=e,this.ownerID=t}function Be(e,t){function n(e,t,n){return 0===t?r(e,n):o(e,t,n)}function r(e,n){var r=n===s?l&&l.array:e&&e.array,o=n>i?0:i-n,u=a-n;return u>hn&&(u=hn),function(){if(o===u)return Xn;var e=t?--u:o++;return r&&r[e]}}function o(e,r,o){var s,l=e&&e.array,u=o>i?0:i-o>>r,c=1+(a-o>>r);return c>hn&&(c=hn),function(){for(;;){if(s){var e=s();if(e!==Xn)return e;s=null}if(u===c)return Xn;var i=t?--c:u++;s=n(l&&l[i],r-dn,o+(i<<r))}}}var i=e._origin,a=e._capacity,s=Je(a),l=e._tail;return n(e._root,e._level,0)}function We(e,t,n,r,o,i,a){var s=Object.create(Yn);return s.size=t-e,s._origin=e,s._capacity=t,s._level=n,s._root=r,s._tail=o,s.__ownerID=i,s.__hash=a,s.__altered=!1,s}function He(){return Gn||(Gn=We(0,0,dn))}function Ue(e,t,n){if((t=v(e,t))!==t)return e;if(t>=e.size||t<0)return e.withMutations(function(e){t<0?Xe(e,t).set(0,n):Xe(e,0,t+1).set(t,n)});t+=e._origin;var r=e._tail,o=e._root,i=c(gn);return t>=Je(e._capacity)?r=qe(r,e.__ownerID,0,t,n,i):o=qe(o,e.__ownerID,e._level,t,n,i),i.value?e.__ownerID?(e._root=o,e._tail=r,e.__hash=void 0,e.__altered=!0,e):We(e._origin,e._capacity,e._level,o,r):e}function qe(e,t,n,r,o,i){var a=r>>>n&vn,s=e&&a<e.array.length;if(!s&&void 0===o)return e;var l;if(n>0){var u=e&&e.array[a],c=qe(u,t,n-dn,r,o,i);return c===u?e:(l=Ye(e,t),l.array[a]=c,l)}return s&&e.array[a]===o?e:(p(i),l=Ye(e,t),void 0===o&&a===l.array.length-1?l.array.pop():l.array[a]=o,l)}function Ye(e,t){return t&&e&&t===e.ownerID?e:new ze(e?e.array.slice():[],t)}function Ge(e,t){if(t>=Je(e._capacity))return e._tail;if(t<1<<e._level+dn){for(var n=e._root,r=e._level;n&&r>0;)n=n.array[t>>>r&vn],r-=dn;return n}}function Xe(e,t,n){void 0!==t&&(t|=0),void 0!==n&&(n|=0);var r=e.__ownerID||new f,o=e._origin,i=e._capacity,a=o+t,s=void 0===n?i:n<0?i+n:o+n;if(a===o&&s===i)return e;if(a>=s)return e.clear();for(var l=e._level,u=e._root,c=0;a+c<0;)u=new ze(u&&u.array.length?[void 0,u]:[],r),l+=dn,c+=1<<l;c&&(a+=c,o+=c,s+=c,i+=c);for(var p=Je(i),d=Je(s);d>=1<<l+dn;)u=new ze(u&&u.array.length?[u]:[],r),l+=dn;var h=e._tail,v=d<p?Ge(e,s-1):d>p?new ze([],r):h;if(h&&d>p&&a<i&&h.array.length){u=Ye(u,r);for(var m=u,y=l;y>dn;y-=dn){var g=p>>>y&vn;m=m.array[g]=Ye(m.array[g],r)}m.array[p>>>dn&vn]=h}if(s<i&&(v=v&&v.removeAfter(r,0,s)),a>=d)a-=d,s-=d,l=dn,u=null,v=v&&v.removeBefore(r,0,a);else if(a>o||d<p){for(c=0;u;){var b=a>>>l&vn;if(b!==d>>>l&vn)break;b&&(c+=(1<<l)*b),l-=dn,u=u.array[b]}u&&a>o&&(u=u.removeBefore(r,l,a-c)),u&&d<p&&(u=u.removeAfter(r,l,d-c)),c&&(a-=c,s-=c)}return e.__ownerID?(e.size=s-a,e._origin=a,e._capacity=s,e._level=l,e._root=u,e._tail=v,e.__hash=void 0,e.__altered=!0,e):We(a,s,l,u,v)}function $e(e,t,n){for(var o=[],a=0,s=0;s<n.length;s++){var l=n[s],u=r(l);u.size>a&&(a=u.size),i(l)||(u=u.map(function(e){return U(e)})),o.push(u)}return a>e.size&&(e=e.setSize(a)),Ie(e,t,o)}function Je(e){return e<hn?0:e-1>>>dn<<dn}function Ze(e){return null===e||void 0===e?tt():Qe(e)?e:tt().withMutations(function(t){var r=n(e);ce(r.size),r.forEach(function(e,n){return t.set(n,e)})})}function Qe(e){return fe(e)&&u(e)}function et(e,t,n,r){var o=Object.create(Ze.prototype);return o.size=e?e.size:0,o._map=e,o._list=t,o.__ownerID=n,o.__hash=r,o}function tt(){return $n||($n=et(Se(),He()))}function nt(e,t,n){var r,o,i=e._map,a=e._list,s=i.get(t),l=void 0!==s;if(n===mn){if(!l)return e;a.size>=hn&&a.size>=2*i.size?(o=a.filter(function(e,t){return void 0!==e&&s!==t}),r=o.toKeyedSeq().map(function(e){return e[0]}).flip().toMap(),e.__ownerID&&(r.__ownerID=o.__ownerID=e.__ownerID)):(r=i.remove(t),o=s===a.size-1?a.pop():a.set(s,void 0))}else if(l){if(n===a.get(s)[1])return e;r=i,o=a.set(s,[t,n])}else r=i.set(t,a.size),o=a.set(a.size,[t,n]);return e.__ownerID?(e.size=r.size,e._map=r,e._list=o,e.__hash=void 0,e):et(r,o)}function rt(e,t){this._iter=e,this._useKeys=t,this.size=e.size}function ot(e){this._iter=e,this.size=e.size}function it(e){this._iter=e,this.size=e.size}function at(e){this._iter=e,this.size=e.size}function st(e){var t=Tt(e);return t._iter=e,t.size=e.size,t.flip=function(){return e},t.reverse=function(){var t=e.reverse.apply(this);return t.flip=function(){return e.reverse()},t},t.has=function(t){return e.includes(t)},t.includes=function(t){return e.has(t)},t.cacheResult=Nt,t.__iterateUncached=function(t,n){var r=this;return e.__iterate(function(e,n){return!1!==t(n,e,r)},n)},t.__iteratorUncached=function(t,n){if(t===wn){var r=e.__iterator(t,n);return new w(function(){var e=r.next();if(!e.done){var t=e.value[0];e.value[0]=e.value[1],e.value[1]=t}return e})}return e.__iterator(t===Cn?bn:Cn,n)},t}function lt(e,t,n){var r=Tt(e);return r.size=e.size,r.has=function(t){return e.has(t)},r.get=function(r,o){var i=e.get(r,mn);return i===mn?o:t.call(n,i,r,e)},r.__iterateUncached=function(r,o){var i=this;return e.__iterate(function(e,o,a){return!1!==r(t.call(n,e,o,a),o,i)},o)},r.__iteratorUncached=function(r,o){var i=e.__iterator(wn,o);return new w(function(){var o=i.next();if(o.done)return o;var a=o.value,s=a[0];return S(r,s,t.call(n,a[1],s,e),o)})},r}function ut(e,t){var n=Tt(e);return n._iter=e,n.size=e.size,n.reverse=function(){return e},e.flip&&(n.flip=function(){var t=st(e);return t.reverse=function(){return e.flip()},t}),n.get=function(n,r){return e.get(t?n:-1-n,r)},n.has=function(n){return e.has(t?n:-1-n)},n.includes=function(t){return e.includes(t)},n.cacheResult=Nt,n.__iterate=function(t,n){var r=this;return e.__iterate(function(e,n){return t(e,n,r)},!n)},n.__iterator=function(t,n){return e.__iterator(t,!n)},n}function ct(e,t,n,r){var o=Tt(e);return r&&(o.has=function(r){var o=e.get(r,mn);return o!==mn&&!!t.call(n,o,r,e)},o.get=function(r,o){var i=e.get(r,mn);return i!==mn&&t.call(n,i,r,e)?i:o}),o.__iterateUncached=function(o,i){var a=this,s=0;return e.__iterate(function(e,i,l){if(t.call(n,e,i,l))return s++,o(e,r?i:s-1,a)},i),s},o.__iteratorUncached=function(o,i){var a=e.__iterator(wn,i),s=0;return new w(function(){for(;;){var i=a.next();if(i.done)return i;var l=i.value,u=l[0],c=l[1];if(t.call(n,c,u,e))return S(o,r?u:s++,c,i)}})},o}function pt(e,t,n){var r=pe().asMutable();return e.__iterate(function(o,i){r.update(t.call(n,o,i,e),0,function(e){return e+1})}),r.asImmutable()}function ft(e,t,n){var r=a(e),o=(u(e)?Ze():pe()).asMutable();e.__iterate(function(i,a){o.update(t.call(n,i,a,e),function(e){return e=e||[],e.push(r?[a,i]:i),e})});var i=Ot(e);return o.map(function(t){return _t(e,i(t))})}function dt(e,t,n,r){var o=e.size;if(void 0!==t&&(t|=0),void 0!==n&&(n===1/0?n=o:n|=0),y(t,n,o))return e;var i=g(t,o),a=b(n,o);if(i!==i||a!==a)return dt(e.toSeq().cacheResult(),t,n,r);var s,l=a-i;l===l&&(s=l<0?0:l);var u=Tt(e);return u.size=0===s?s:e.size&&s||void 0,!r&&L(e)&&s>=0&&(u.get=function(t,n){return t=v(this,t),t>=0&&t<s?e.get(t+i,n):n}),u.__iterateUncached=function(t,n){var o=this;if(0===s)return 0;if(n)return this.cacheResult().__iterate(t,n);var a=0,l=!0,u=0;return e.__iterate(function(e,n){if(!l||!(l=a++<i))return u++,!1!==t(e,r?n:u-1,o)&&u!==s}),u},u.__iteratorUncached=function(t,n){if(0!==s&&n)return this.cacheResult().__iterator(t,n);var o=0!==s&&e.__iterator(t,n),a=0,l=0;return new w(function(){for(;a++<i;)o.next();if(++l>s)return x();var e=o.next();return r||t===Cn?e:t===bn?S(t,l-1,void 0,e):S(t,l-1,e.value[1],e)})},u}function ht(e,t,n){var r=Tt(e);return r.__iterateUncached=function(r,o){var i=this;if(o)return this.cacheResult().__iterate(r,o);var a=0;return e.__iterate(function(e,o,s){return t.call(n,e,o,s)&&++a&&r(e,o,i)}),a},r.__iteratorUncached=function(r,o){var i=this;if(o)return this.cacheResult().__iterator(r,o);var a=e.__iterator(wn,o),s=!0;return new w(function(){if(!s)return x();var e=a.next();if(e.done)return e;var o=e.value,l=o[0],u=o[1];return t.call(n,u,l,i)?r===wn?e:S(r,l,u,e):(s=!1,x())})},r}function vt(e,t,n,r){var o=Tt(e);return o.__iterateUncached=function(o,i){var a=this;if(i)return this.cacheResult().__iterate(o,i);var s=!0,l=0;return e.__iterate(function(e,i,u){if(!s||!(s=t.call(n,e,i,u)))return l++,o(e,r?i:l-1,a)}),l},o.__iteratorUncached=function(o,i){var a=this;if(i)return this.cacheResult().__iterator(o,i);var s=e.__iterator(wn,i),l=!0,u=0;return new w(function(){var e,i,c;do{if(e=s.next(),e.done)return r||o===Cn?e:o===bn?S(o,u++,void 0,e):S(o,u++,e.value[1],e);var p=e.value;i=p[0],c=p[1],l&&(l=t.call(n,c,i,a))}while(l);return o===wn?e:S(o,i,c,e)})},o}function mt(e,t){var r=a(e),o=[e].concat(t).map(function(e){return i(e)?r&&(e=n(e)):e=r?F(e):V(Array.isArray(e)?e:[e]),e}).filter(function(e){return 0!==e.size});if(0===o.length)return e;if(1===o.length){var l=o[0];if(l===e||r&&a(l)||s(e)&&s(l))return l}var u=new I(o);return r?u=u.toKeyedSeq():s(e)||(u=u.toSetSeq()),u=u.flatten(!0),u.size=o.reduce(function(e,t){if(void 0!==e){var n=t.size;if(void 0!==n)return e+n}},0),u}function yt(e,t,n){var r=Tt(e);return r.__iterateUncached=function(r,o){function a(e,u){var c=this;e.__iterate(function(e,o){return(!t||u<t)&&i(e)?a(e,u+1):!1===r(e,n?o:s++,c)&&(l=!0),!l},o)}var s=0,l=!1;return a(e,0),s},r.__iteratorUncached=function(r,o){var a=e.__iterator(r,o),s=[],l=0;return new w(function(){for(;a;){var e=a.next();if(!1===e.done){var u=e.value;if(r===wn&&(u=u[1]),t&&!(s.length<t)||!i(u))return n?e:S(r,l++,u,e);s.push(a),a=u.__iterator(r,o)}else a=s.pop()}return x()})},r}function gt(e,t,n){var r=Ot(e);return e.toSeq().map(function(o,i){return r(t.call(n,o,i,e))}).flatten(!0)}function bt(e,t){var n=Tt(e);return n.size=e.size&&2*e.size-1,n.__iterateUncached=function(n,r){var o=this,i=0;return e.__iterate(function(e,r){return(!i||!1!==n(t,i++,o))&&!1!==n(e,i++,o)},r),i},n.__iteratorUncached=function(n,r){var o,i=e.__iterator(Cn,r),a=0;return new w(function(){return(!o||a%2)&&(o=i.next(),o.done)?o:a%2?S(n,a++,t):S(n,a++,o.value,o)})},n}function Ct(e,t,n){t||(t=Pt);var r=a(e),o=0,i=e.toSeq().map(function(t,r){return[r,t,o++,n?n(t,r,e):t]}).toArray();return i.sort(function(e,n){return t(e[3],n[3])||e[2]-n[2]}).forEach(r?function(e,t){i[t].length=2}:function(e,t){i[t]=e[1]}),r?P(i):s(e)?M(i):D(i)}function wt(e,t,n){if(t||(t=Pt),n){var r=e.toSeq().map(function(t,r){return[t,n(t,r,e)]}).reduce(function(e,n){return St(t,e[1],n[1])?n:e});return r&&r[0]}return e.reduce(function(e,n){return St(t,e,n)?n:e})}function St(e,t,n){var r=e(n,t);return 0===r&&n!==t&&(void 0===n||null===n||n!==n)||r>0}function xt(e,n,r){var o=Tt(e);return o.size=new I(r).map(function(e){return e.size}).min(),o.__iterate=function(e,t){for(var n,r=this.__iterator(Cn,t),o=0;!(n=r.next()).done&&!1!==e(n.value,o++,this););return o},o.__iteratorUncached=function(e,o){var i=r.map(function(e){return e=t(e),E(o?e.reverse():e)}),a=0,s=!1;return new w(function(){var t;return s||(t=i.map(function(e){return e.next()}),s=t.some(function(e){return e.done})),s?x():S(e,a++,n.apply(null,t.map(function(e){return e.value})))})},o}function _t(e,t){return L(e)?t:e.constructor(t)}function kt(e){if(e!==Object(e))throw new TypeError("Expected [K, V] tuple: "+e)}function Et(e){return ce(e.size),h(e)}function Ot(e){return a(e)?n:s(e)?r:o}function Tt(e){return Object.create((a(e)?P:s(e)?M:D).prototype)}function Nt(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):N.prototype.cacheResult.call(this)}function Pt(e,t){return e>t?1:e<t?-1:0}function Mt(e){var n=E(e);if(!n){if(!T(e))throw new TypeError("Expected iterable or array-like: "+e);n=E(t(e))}return n}function Dt(e,t){var n,r=function(i){if(i instanceof r)return i;if(!(this instanceof r))return new r(i);if(!n){n=!0;var a=Object.keys(e);jt(o,a),o.size=a.length,o._name=t,o._keys=a,o._defaultValues=e}this._map=pe(i)},o=r.prototype=Object.create(Jn);return o.constructor=r,r}function It(e,t,n){var r=Object.create(Object.getPrototypeOf(e));return r._map=t,r.__ownerID=n,r}function At(e){return e._name||e.constructor.name||"Record"}function jt(e,t){try{t.forEach(Rt.bind(void 0,e))}catch(e){}}function Rt(e,t){Object.defineProperty(e,t,{get:function(){return this.get(t)},set:function(e){Z(this.__ownerID,"Cannot set on an immutable record."),this.set(t,e)}})}function Lt(e){return null===e||void 0===e?zt():Kt(e)&&!u(e)?e:zt().withMutations(function(t){var n=o(e);ce(n.size),n.forEach(function(e){return t.add(e)})})}function Kt(e){return!(!e||!e[Zn])}function Ft(e,t){return e.__ownerID?(e.size=t.size,e._map=t,e):t===e._map?e:0===t.size?e.__empty():e.__make(t)}function Vt(e,t){var n=Object.create(Qn);return n.size=e?e.size:0,n._map=e,n.__ownerID=t,n}function zt(){return er||(er=Vt(Se()))}function Bt(e){return null===e||void 0===e?Ut():Wt(e)?e:Ut().withMutations(function(t){var n=o(e);ce(n.size),n.forEach(function(e){return t.add(e)})})}function Wt(e){return Kt(e)&&u(e)}function Ht(e,t){var n=Object.create(tr);return n.size=e?e.size:0,n._map=e,n.__ownerID=t,n}function Ut(){return nr||(nr=Ht(tt()))}function qt(e){return null===e||void 0===e?Xt():Yt(e)?e:Xt().unshiftAll(e)}function Yt(e){return!(!e||!e[rr])}function Gt(e,t,n,r){var o=Object.create(or);return o.size=e,o._head=t,o.__ownerID=n,o.__hash=r,o.__altered=!1,o}function Xt(){return ir||(ir=Gt(0))}function $t(e,t){var n=function(n){e.prototype[n]=t[n]};return Object.keys(t).forEach(n),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(t).forEach(n),e}function Jt(e,t){return t}function Zt(e,t){return[t,e]}function Qt(e){return function(){return!e.apply(this,arguments)}}function en(e){return function(){return-e.apply(this,arguments)}}function tn(e){return"string"==typeof e?JSON.stringify(e):String(e)}function nn(){return d(arguments)}function rn(e,t){return e<t?1:e>t?-1:0}function on(e){if(e.size===1/0)return 0;var t=u(e),n=a(e),r=t?1:0;return an(e.__iterate(n?t?function(e,t){r=31*r+sn(ie(e),ie(t))|0}:function(e,t){r=r+sn(ie(e),ie(t))|0}:t?function(e){r=31*r+ie(e)|0}:function(e){r=r+ie(e)|0}),r)}function an(e,t){return t=Pn(t,3432918353),t=Pn(t<<15|t>>>-15,461845907),t=Pn(t<<13|t>>>-13,5),t=(t+3864292196|0)^e,t=Pn(t^t>>>16,2246822507),t=Pn(t^t>>>13,3266489909),t=oe(t^t>>>16)}function sn(e,t){return e^t+2654435769+(e<<6)+(e>>2)|0}var ln=Array.prototype.slice;e(n,t),e(r,t),e(o,t),t.isIterable=i,t.isKeyed=a,t.isIndexed=s,t.isAssociative=l,t.isOrdered=u,t.Keyed=n,t.Indexed=r,t.Set=o;var un="@@__IMMUTABLE_ITERABLE__@@",cn="@@__IMMUTABLE_KEYED__@@",pn="@@__IMMUTABLE_INDEXED__@@",fn="@@__IMMUTABLE_ORDERED__@@",dn=5,hn=1<<dn,vn=hn-1,mn={},yn={value:!1},gn={value:!1},bn=0,Cn=1,wn=2,Sn="function"==typeof Symbol&&Symbol.iterator,xn="@@iterator",_n=Sn||xn;w.prototype.toString=function(){return"[Iterator]"},w.KEYS=bn,w.VALUES=Cn,w.ENTRIES=wn,w.prototype.inspect=w.prototype.toSource=function(){return this.toString()},w.prototype[_n]=function(){return this},e(N,t),N.of=function(){return N(arguments)},N.prototype.toSeq=function(){return this},N.prototype.toString=function(){return this.__toString("Seq {","}")},N.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},N.prototype.__iterate=function(e,t){return W(this,e,t,!0)},N.prototype.__iterator=function(e,t){return H(this,e,t,!0)},e(P,N),P.prototype.toKeyedSeq=function(){return this},e(M,N),M.of=function(){return M(arguments)},M.prototype.toIndexedSeq=function(){return this},M.prototype.toString=function(){return this.__toString("Seq [","]")},M.prototype.__iterate=function(e,t){return W(this,e,t,!1)},M.prototype.__iterator=function(e,t){return H(this,e,t,!1)},e(D,N),D.of=function(){return D(arguments)},D.prototype.toSetSeq=function(){return this},N.isSeq=L,N.Keyed=P,N.Set=D,N.Indexed=M;var kn="@@__IMMUTABLE_SEQ__@@";N.prototype[kn]=!0,e(I,M),I.prototype.get=function(e,t){return this.has(e)?this._array[v(this,e)]:t},I.prototype.__iterate=function(e,t){for(var n=this._array,r=n.length-1,o=0;o<=r;o++)if(!1===e(n[t?r-o:o],o,this))return o+1;return o},I.prototype.__iterator=function(e,t){var n=this._array,r=n.length-1,o=0;return new w(function(){return o>r?x():S(e,o,n[t?r-o++:o++])})},e(A,P),A.prototype.get=function(e,t){return void 0===t||this.has(e)?this._object[e]:t},A.prototype.has=function(e){return this._object.hasOwnProperty(e)},A.prototype.__iterate=function(e,t){for(var n=this._object,r=this._keys,o=r.length-1,i=0;i<=o;i++){var a=r[t?o-i:i];if(!1===e(n[a],a,this))return i+1}return i},A.prototype.__iterator=function(e,t){var n=this._object,r=this._keys,o=r.length-1,i=0;return new w(function(){var a=r[t?o-i:i];return i++>o?x():S(e,a,n[a])})},A.prototype[fn]=!0,e(j,M),j.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);var n=this._iterable,r=E(n),o=0;if(k(r))for(var i;!(i=r.next()).done&&!1!==e(i.value,o++,this););return o},j.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var n=this._iterable,r=E(n);if(!k(r))return new w(x);var o=0;return new w(function(){var t=r.next();return t.done?t:S(e,o++,t.value)})},e(R,M),R.prototype.__iterateUncached=function(e,t){if(t)return this.cacheResult().__iterate(e,t);for(var n=this._iterator,r=this._iteratorCache,o=0;o<r.length;)if(!1===e(r[o],o++,this))return o;for(var i;!(i=n.next()).done;){var a=i.value;if(r[o]=a,!1===e(a,o++,this))break}return o},R.prototype.__iteratorUncached=function(e,t){if(t)return this.cacheResult().__iterator(e,t);var n=this._iterator,r=this._iteratorCache,o=0;return new w(function(){if(o>=r.length){var t=n.next();if(t.done)return t;r[o]=t.value}return S(e,o,r[o++])})};var En;e(J,M),J.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},J.prototype.get=function(e,t){return this.has(e)?this._value:t},J.prototype.includes=function(e){return X(this._value,e)},J.prototype.slice=function(e,t){var n=this.size;return y(e,t,n)?this:new J(this._value,b(t,n)-g(e,n))},J.prototype.reverse=function(){return this},J.prototype.indexOf=function(e){return X(this._value,e)?0:-1},J.prototype.lastIndexOf=function(e){return X(this._value,e)?this.size:-1},J.prototype.__iterate=function(e,t){for(var n=0;n<this.size;n++)if(!1===e(this._value,n,this))return n+1;return n},J.prototype.__iterator=function(e,t){var n=this,r=0;return new w(function(){return r<n.size?S(e,r++,n._value):x()})},J.prototype.equals=function(e){return e instanceof J?X(this._value,e._value):$(e)};var On;e(Q,M),Q.prototype.toString=function(){return 0===this.size?"Range []":"Range [ "+this._start+"..."+this._end+(1!==this._step?" by "+this._step:"")+" ]"},Q.prototype.get=function(e,t){return this.has(e)?this._start+v(this,e)*this._step:t},Q.prototype.includes=function(e){var t=(e-this._start)/this._step;return t>=0&&t<this.size&&t===Math.floor(t)},Q.prototype.slice=function(e,t){return y(e,t,this.size)?this:(e=g(e,this.size),t=b(t,this.size),t<=e?new Q(0,0):new Q(this.get(e,this._end),this.get(t,this._end),this._step))},Q.prototype.indexOf=function(e){var t=e-this._start;if(t%this._step==0){var n=t/this._step;if(n>=0&&n<this.size)return n}return-1},Q.prototype.lastIndexOf=function(e){return this.indexOf(e)},Q.prototype.__iterate=function(e,t){for(var n=this.size-1,r=this._step,o=t?this._start+n*r:this._start,i=0;i<=n;i++){if(!1===e(o,i,this))return i+1;o+=t?-r:r}return i},Q.prototype.__iterator=function(e,t){var n=this.size-1,r=this._step,o=t?this._start+n*r:this._start,i=0;return new w(function(){var a=o;return o+=t?-r:r,i>n?x():S(e,i++,a)})},Q.prototype.equals=function(e){return e instanceof Q?this._start===e._start&&this._end===e._end&&this._step===e._step:$(this,e)};var Tn;e(ee,t),e(te,ee),e(ne,ee),e(re,ee),ee.Keyed=te,ee.Indexed=ne,ee.Set=re;var Nn,Pn="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function(e,t){e|=0,t|=0;var n=65535&e,r=65535&t;return n*r+((e>>>16)*r+n*(t>>>16)<<16>>>0)|0},Mn=Object.isExtensible,Dn=function(){try{return Object.defineProperty({},"@",{}),!0}catch(e){return!1}}(),In="function"==typeof WeakMap;In&&(Nn=new WeakMap);var An=0,jn="__immutablehash__";"function"==typeof Symbol&&(jn=Symbol(jn));var Rn=16,Ln=255,Kn=0,Fn={};e(pe,te),pe.of=function(){var e=ln.call(arguments,0);return Se().withMutations(function(t){for(var n=0;n<e.length;n+=2){if(n+1>=e.length)throw new Error("Missing value for key: "+e[n]);t.set(e[n],e[n+1])}})},pe.prototype.toString=function(){return this.__toString("Map {","}")},pe.prototype.get=function(e,t){return this._root?this._root.get(0,void 0,e,t):t},pe.prototype.set=function(e,t){return xe(this,e,t)},pe.prototype.setIn=function(e,t){return this.updateIn(e,mn,function(){return t})},pe.prototype.remove=function(e){return xe(this,e,mn)},pe.prototype.deleteIn=function(e){return this.updateIn(e,function(){return mn})},pe.prototype.update=function(e,t,n){return 1===arguments.length?e(this):this.updateIn([e],t,n)},pe.prototype.updateIn=function(e,t,n){n||(n=t,t=void 0);var r=Ae(this,Mt(e),t,n);return r===mn?void 0:r},pe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):Se()},pe.prototype.merge=function(){return Pe(this,void 0,arguments)},pe.prototype.mergeWith=function(e){return Pe(this,e,ln.call(arguments,1))},pe.prototype.mergeIn=function(e){var t=ln.call(arguments,1);return this.updateIn(e,Se(),function(e){return"function"==typeof e.merge?e.merge.apply(e,t):t[t.length-1]})},pe.prototype.mergeDeep=function(){return Pe(this,Me,arguments)},pe.prototype.mergeDeepWith=function(e){var t=ln.call(arguments,1);return Pe(this,De(e),t)},pe.prototype.mergeDeepIn=function(e){var t=ln.call(arguments,1);return this.updateIn(e,Se(),function(e){return"function"==typeof e.mergeDeep?e.mergeDeep.apply(e,t):t[t.length-1]})},pe.prototype.sort=function(e){return Ze(Ct(this,e))},pe.prototype.sortBy=function(e,t){return Ze(Ct(this,t,e))},pe.prototype.withMutations=function(e){var t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this},pe.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new f)},pe.prototype.asImmutable=function(){return this.__ensureOwner()},pe.prototype.wasAltered=function(){return this.__altered},pe.prototype.__iterator=function(e,t){return new ge(this,e,t)},pe.prototype.__iterate=function(e,t){var n=this,r=0;return this._root&&this._root.iterate(function(t){return r++,e(t[1],t[0],n)},t),r},pe.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?we(this.size,this._root,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},pe.isMap=fe;var Vn="@@__IMMUTABLE_MAP__@@",zn=pe.prototype;zn[Vn]=!0,zn.delete=zn.remove,zn.removeIn=zn.deleteIn,de.prototype.get=function(e,t,n,r){for(var o=this.entries,i=0,a=o.length;i<a;i++)if(X(n,o[i][0]))return o[i][1];return r},de.prototype.update=function(e,t,n,r,o,i,a){for(var s=o===mn,l=this.entries,u=0,c=l.length;u<c&&!X(r,l[u][0]);u++);var f=u<c;if(f?l[u][1]===o:s)return this;if(p(a),(s||!f)&&p(i),!s||1!==l.length){if(!f&&!s&&l.length>=Wn)return Oe(e,l,r,o);var h=e&&e===this.ownerID,v=h?l:d(l);return f?s?u===c-1?v.pop():v[u]=v.pop():v[u]=[r,o]:v.push([r,o]),h?(this.entries=v,this):new de(e,v)}},he.prototype.get=function(e,t,n,r){void 0===t&&(t=ie(n));var o=1<<((0===e?t:t>>>e)&vn),i=this.bitmap;return 0==(i&o)?r:this.nodes[je(i&o-1)].get(e+dn,t,n,r)},he.prototype.update=function(e,t,n,r,o,i,a){void 0===n&&(n=ie(r));var s=(0===t?n:n>>>t)&vn,l=1<<s,u=this.bitmap,c=0!=(u&l);if(!c&&o===mn)return this;var p=je(u&l-1),f=this.nodes,d=c?f[p]:void 0,h=_e(d,e,t+dn,n,r,o,i,a);if(h===d)return this;if(!c&&h&&f.length>=Hn)return Ne(e,f,u,s,h);if(c&&!h&&2===f.length&&ke(f[1^p]))return f[1^p];if(c&&h&&1===f.length&&ke(h))return h;var v=e&&e===this.ownerID,m=c?h?u:u^l:u|l,y=c?h?Re(f,p,h,v):Ke(f,p,v):Le(f,p,h,v);return v?(this.bitmap=m,this.nodes=y,this):new he(e,m,y)},ve.prototype.get=function(e,t,n,r){void 0===t&&(t=ie(n));var o=(0===e?t:t>>>e)&vn,i=this.nodes[o];return i?i.get(e+dn,t,n,r):r},ve.prototype.update=function(e,t,n,r,o,i,a){void 0===n&&(n=ie(r));var s=(0===t?n:n>>>t)&vn,l=o===mn,u=this.nodes,c=u[s];if(l&&!c)return this;var p=_e(c,e,t+dn,n,r,o,i,a);if(p===c)return this;var f=this.count;if(c){if(!p&&--f<Un)return Te(e,u,f,s)}else f++;var d=e&&e===this.ownerID,h=Re(u,s,p,d);return d?(this.count=f,this.nodes=h,this):new ve(e,f,h)},me.prototype.get=function(e,t,n,r){for(var o=this.entries,i=0,a=o.length;i<a;i++)if(X(n,o[i][0]))return o[i][1];return r},me.prototype.update=function(e,t,n,r,o,i,a){void 0===n&&(n=ie(r));var s=o===mn;if(n!==this.keyHash)return s?this:(p(a),p(i),Ee(this,e,t,n,[r,o]));for(var l=this.entries,u=0,c=l.length;u<c&&!X(r,l[u][0]);u++);var f=u<c;if(f?l[u][1]===o:s)return this;if(p(a),(s||!f)&&p(i),s&&2===c)return new ye(e,this.keyHash,l[1^u]);var h=e&&e===this.ownerID,v=h?l:d(l);return f?s?u===c-1?v.pop():v[u]=v.pop():v[u]=[r,o]:v.push([r,o]),h?(this.entries=v,this):new me(e,this.keyHash,v)},ye.prototype.get=function(e,t,n,r){return X(n,this.entry[0])?this.entry[1]:r},ye.prototype.update=function(e,t,n,r,o,i,a){var s=o===mn,l=X(r,this.entry[0]);return(l?o===this.entry[1]:s)?this:(p(a),s?void p(i):l?e&&e===this.ownerID?(this.entry[1]=o,this):new ye(e,this.keyHash,[r,o]):(p(i),Ee(this,e,t,ie(r),[r,o])))},de.prototype.iterate=me.prototype.iterate=function(e,t){for(var n=this.entries,r=0,o=n.length-1;r<=o;r++)if(!1===e(n[t?o-r:r]))return!1},he.prototype.iterate=ve.prototype.iterate=function(e,t){for(var n=this.nodes,r=0,o=n.length-1;r<=o;r++){var i=n[t?o-r:r];if(i&&!1===i.iterate(e,t))return!1}},ye.prototype.iterate=function(e,t){return e(this.entry)},e(ge,w),ge.prototype.next=function(){for(var e=this._type,t=this._stack;t;){var n,r=t.node,o=t.index++;if(r.entry){if(0===o)return be(e,r.entry)}else if(r.entries){if(n=r.entries.length-1,o<=n)return be(e,r.entries[this._reverse?n-o:o])}else if(n=r.nodes.length-1,o<=n){var i=r.nodes[this._reverse?n-o:o];if(i){if(i.entry)return be(e,i.entry);t=this._stack=Ce(i,t)}continue}t=this._stack=this._stack.__prev}return x()};var Bn,Wn=hn/4,Hn=hn/2,Un=hn/4;e(Fe,ne),Fe.of=function(){return this(arguments)},Fe.prototype.toString=function(){return this.__toString("List [","]")},Fe.prototype.get=function(e,t){if((e=v(this,e))>=0&&e<this.size){e+=this._origin;var n=Ge(this,e);return n&&n.array[e&vn]}return t},Fe.prototype.set=function(e,t){return Ue(this,e,t)},Fe.prototype.remove=function(e){return this.has(e)?0===e?this.shift():e===this.size-1?this.pop():this.splice(e,1):this},Fe.prototype.insert=function(e,t){return this.splice(e,0,t)},Fe.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=this._origin=this._capacity=0,this._level=dn,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):He()},Fe.prototype.push=function(){var e=arguments,t=this.size;return this.withMutations(function(n){Xe(n,0,t+e.length);for(var r=0;r<e.length;r++)n.set(t+r,e[r])})},Fe.prototype.pop=function(){return Xe(this,0,-1)},Fe.prototype.unshift=function(){var e=arguments;return this.withMutations(function(t){Xe(t,-e.length);for(var n=0;n<e.length;n++)t.set(n,e[n])})},Fe.prototype.shift=function(){return Xe(this,1)},Fe.prototype.merge=function(){return $e(this,void 0,arguments)},Fe.prototype.mergeWith=function(e){return $e(this,e,ln.call(arguments,1))},Fe.prototype.mergeDeep=function(){return $e(this,Me,arguments)},Fe.prototype.mergeDeepWith=function(e){var t=ln.call(arguments,1);return $e(this,De(e),t)},Fe.prototype.setSize=function(e){return Xe(this,0,e)},Fe.prototype.slice=function(e,t){var n=this.size;return y(e,t,n)?this:Xe(this,g(e,n),b(t,n))},Fe.prototype.__iterator=function(e,t){var n=0,r=Be(this,t);return new w(function(){var t=r();return t===Xn?x():S(e,n++,t)})},Fe.prototype.__iterate=function(e,t){for(var n,r=0,o=Be(this,t);(n=o())!==Xn&&!1!==e(n,r++,this););return r},Fe.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?We(this._origin,this._capacity,this._level,this._root,this._tail,e,this.__hash):(this.__ownerID=e,this)},Fe.isList=Ve;var qn="@@__IMMUTABLE_LIST__@@",Yn=Fe.prototype;Yn[qn]=!0,Yn.delete=Yn.remove,Yn.setIn=zn.setIn,Yn.deleteIn=Yn.removeIn=zn.removeIn,Yn.update=zn.update,Yn.updateIn=zn.updateIn,Yn.mergeIn=zn.mergeIn,Yn.mergeDeepIn=zn.mergeDeepIn,Yn.withMutations=zn.withMutations,Yn.asMutable=zn.asMutable,Yn.asImmutable=zn.asImmutable,Yn.wasAltered=zn.wasAltered,ze.prototype.removeBefore=function(e,t,n){if(n===t?1<<t:0===this.array.length)return this;var r=n>>>t&vn;if(r>=this.array.length)return new ze([],e);var o,i=0===r;if(t>0){var a=this.array[r];if((o=a&&a.removeBefore(e,t-dn,n))===a&&i)return this}if(i&&!o)return this;var s=Ye(this,e);if(!i)for(var l=0;l<r;l++)s.array[l]=void 0;return o&&(s.array[r]=o),s},ze.prototype.removeAfter=function(e,t,n){if(n===(t?1<<t:0)||0===this.array.length)return this;var r=n-1>>>t&vn;if(r>=this.array.length)return this;var o;if(t>0){var i=this.array[r];if((o=i&&i.removeAfter(e,t-dn,n))===i&&r===this.array.length-1)return this}var a=Ye(this,e);return a.array.splice(r+1),o&&(a.array[r]=o),a};var Gn,Xn={};e(Ze,pe),Ze.of=function(){return this(arguments)},Ze.prototype.toString=function(){return this.__toString("OrderedMap {","}")},Ze.prototype.get=function(e,t){var n=this._map.get(e);return void 0!==n?this._list.get(n)[1]:t},Ze.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._map.clear(),this._list.clear(),this):tt()},Ze.prototype.set=function(e,t){return nt(this,e,t)},Ze.prototype.remove=function(e){return nt(this,e,mn)},Ze.prototype.wasAltered=function(){return this._map.wasAltered()||this._list.wasAltered()},Ze.prototype.__iterate=function(e,t){var n=this;return this._list.__iterate(function(t){return t&&e(t[1],t[0],n)},t)},Ze.prototype.__iterator=function(e,t){return this._list.fromEntrySeq().__iterator(e,t)},Ze.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e),n=this._list.__ensureOwner(e);return e?et(t,n,e,this.__hash):(this.__ownerID=e,this._map=t,this._list=n,this)},Ze.isOrderedMap=Qe,Ze.prototype[fn]=!0,Ze.prototype.delete=Ze.prototype.remove;var $n;e(rt,P),rt.prototype.get=function(e,t){return this._iter.get(e,t)},rt.prototype.has=function(e){return this._iter.has(e)},rt.prototype.valueSeq=function(){return this._iter.valueSeq()},rt.prototype.reverse=function(){var e=this,t=ut(this,!0);return this._useKeys||(t.valueSeq=function(){return e._iter.toSeq().reverse()}),t},rt.prototype.map=function(e,t){var n=this,r=lt(this,e,t);return this._useKeys||(r.valueSeq=function(){return n._iter.toSeq().map(e,t)}),r},rt.prototype.__iterate=function(e,t){var n,r=this;return this._iter.__iterate(this._useKeys?function(t,n){return e(t,n,r)}:(n=t?Et(this):0,function(o){return e(o,t?--n:n++,r)}),t)},rt.prototype.__iterator=function(e,t){if(this._useKeys)return this._iter.__iterator(e,t);var n=this._iter.__iterator(Cn,t),r=t?Et(this):0;return new w(function(){var o=n.next();return o.done?o:S(e,t?--r:r++,o.value,o)})},rt.prototype[fn]=!0,e(ot,M),ot.prototype.includes=function(e){return this._iter.includes(e)},ot.prototype.__iterate=function(e,t){var n=this,r=0;return this._iter.__iterate(function(t){return e(t,r++,n)},t)},ot.prototype.__iterator=function(e,t){var n=this._iter.__iterator(Cn,t),r=0;return new w(function(){var t=n.next();return t.done?t:S(e,r++,t.value,t)})},e(it,D),it.prototype.has=function(e){return this._iter.includes(e)},it.prototype.__iterate=function(e,t){var n=this;return this._iter.__iterate(function(t){return e(t,t,n)},t)},it.prototype.__iterator=function(e,t){var n=this._iter.__iterator(Cn,t);return new w(function(){var t=n.next();return t.done?t:S(e,t.value,t.value,t)})},e(at,P),at.prototype.entrySeq=function(){return this._iter.toSeq()},at.prototype.__iterate=function(e,t){var n=this;return this._iter.__iterate(function(t){if(t){kt(t);var r=i(t);return e(r?t.get(1):t[1],r?t.get(0):t[0],n)}},t)},at.prototype.__iterator=function(e,t){var n=this._iter.__iterator(Cn,t);return new w(function(){for(;;){var t=n.next();if(t.done)return t;var r=t.value;if(r){kt(r);var o=i(r);return S(e,o?r.get(0):r[0],o?r.get(1):r[1],t)}}})},ot.prototype.cacheResult=rt.prototype.cacheResult=it.prototype.cacheResult=at.prototype.cacheResult=Nt,e(Dt,te),Dt.prototype.toString=function(){return this.__toString(At(this)+" {","}")},Dt.prototype.has=function(e){return this._defaultValues.hasOwnProperty(e)},Dt.prototype.get=function(e,t){if(!this.has(e))return t;var n=this._defaultValues[e];return this._map?this._map.get(e,n):n},Dt.prototype.clear=function(){if(this.__ownerID)return this._map&&this._map.clear(),this;var e=this.constructor;return e._empty||(e._empty=It(this,Se()))},Dt.prototype.set=function(e,t){if(!this.has(e))throw new Error('Cannot set unknown key "'+e+'" on '+At(this));if(this._map&&!this._map.has(e)){if(t===this._defaultValues[e])return this}var n=this._map&&this._map.set(e,t);return this.__ownerID||n===this._map?this:It(this,n)},Dt.prototype.remove=function(e){if(!this.has(e))return this;var t=this._map&&this._map.remove(e);return this.__ownerID||t===this._map?this:It(this,t)},Dt.prototype.wasAltered=function(){return this._map.wasAltered()},Dt.prototype.__iterator=function(e,t){var r=this;return n(this._defaultValues).map(function(e,t){return r.get(t)}).__iterator(e,t)},Dt.prototype.__iterate=function(e,t){var r=this;return n(this._defaultValues).map(function(e,t){return r.get(t)}).__iterate(e,t)},Dt.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map&&this._map.__ensureOwner(e);return e?It(this,t,e):(this.__ownerID=e,this._map=t,this)};var Jn=Dt.prototype;Jn.delete=Jn.remove,Jn.deleteIn=Jn.removeIn=zn.removeIn,Jn.merge=zn.merge,Jn.mergeWith=zn.mergeWith,Jn.mergeIn=zn.mergeIn,Jn.mergeDeep=zn.mergeDeep,Jn.mergeDeepWith=zn.mergeDeepWith,Jn.mergeDeepIn=zn.mergeDeepIn,Jn.setIn=zn.setIn,Jn.update=zn.update,Jn.updateIn=zn.updateIn,Jn.withMutations=zn.withMutations,Jn.asMutable=zn.asMutable,Jn.asImmutable=zn.asImmutable,e(Lt,re),Lt.of=function(){return this(arguments)},Lt.fromKeys=function(e){return this(n(e).keySeq())},Lt.prototype.toString=function(){return this.__toString("Set {","}")},Lt.prototype.has=function(e){return this._map.has(e)},Lt.prototype.add=function(e){return Ft(this,this._map.set(e,!0))},Lt.prototype.remove=function(e){return Ft(this,this._map.remove(e))},Lt.prototype.clear=function(){return Ft(this,this._map.clear())},Lt.prototype.union=function(){var e=ln.call(arguments,0);return e=e.filter(function(e){return 0!==e.size}),0===e.length?this:0!==this.size||this.__ownerID||1!==e.length?this.withMutations(function(t){for(var n=0;n<e.length;n++)o(e[n]).forEach(function(e){return t.add(e)})}):this.constructor(e[0])},Lt.prototype.intersect=function(){var e=ln.call(arguments,0);if(0===e.length)return this;e=e.map(function(e){return o(e)});var t=this;return this.withMutations(function(n){t.forEach(function(t){e.every(function(e){return e.includes(t)})||n.remove(t)})})},Lt.prototype.subtract=function(){var e=ln.call(arguments,0);if(0===e.length)return this;e=e.map(function(e){return o(e)});var t=this;return this.withMutations(function(n){t.forEach(function(t){e.some(function(e){return e.includes(t)})&&n.remove(t)})})},Lt.prototype.merge=function(){return this.union.apply(this,arguments)},Lt.prototype.mergeWith=function(e){var t=ln.call(arguments,1);return this.union.apply(this,t)},Lt.prototype.sort=function(e){return Bt(Ct(this,e))},Lt.prototype.sortBy=function(e,t){return Bt(Ct(this,t,e))},Lt.prototype.wasAltered=function(){return this._map.wasAltered()},Lt.prototype.__iterate=function(e,t){var n=this;return this._map.__iterate(function(t,r){return e(r,r,n)},t)},Lt.prototype.__iterator=function(e,t){return this._map.map(function(e,t){return t}).__iterator(e,t)},Lt.prototype.__ensureOwner=function(e){if(e===this.__ownerID)return this;var t=this._map.__ensureOwner(e);return e?this.__make(t,e):(this.__ownerID=e,this._map=t,this)},Lt.isSet=Kt;var Zn="@@__IMMUTABLE_SET__@@",Qn=Lt.prototype;Qn[Zn]=!0,Qn.delete=Qn.remove,Qn.mergeDeep=Qn.merge,Qn.mergeDeepWith=Qn.mergeWith,Qn.withMutations=zn.withMutations,Qn.asMutable=zn.asMutable,Qn.asImmutable=zn.asImmutable,Qn.__empty=zt,Qn.__make=Vt;var er;e(Bt,Lt),Bt.of=function(){return this(arguments)},Bt.fromKeys=function(e){return this(n(e).keySeq())},Bt.prototype.toString=function(){return this.__toString("OrderedSet {","}")},Bt.isOrderedSet=Wt;var tr=Bt.prototype;tr[fn]=!0,tr.__empty=Ut,tr.__make=Ht;var nr;e(qt,ne),qt.of=function(){return this(arguments)},qt.prototype.toString=function(){return this.__toString("Stack [","]")},qt.prototype.get=function(e,t){var n=this._head;for(e=v(this,e);n&&e--;)n=n.next;return n?n.value:t},qt.prototype.peek=function(){return this._head&&this._head.value},qt.prototype.push=function(){if(0===arguments.length)return this;for(var e=this.size+arguments.length,t=this._head,n=arguments.length-1;n>=0;n--)t={value:arguments[n],next:t};return this.__ownerID?(this.size=e,this._head=t,this.__hash=void 0,this.__altered=!0,this):Gt(e,t)},qt.prototype.pushAll=function(e){if(e=r(e),0===e.size)return this;ce(e.size);var t=this.size,n=this._head;return e.reverse().forEach(function(e){t++,n={value:e,next:n}}),this.__ownerID?(this.size=t,this._head=n,this.__hash=void 0,this.__altered=!0,this):Gt(t,n)},qt.prototype.pop=function(){return this.slice(1)},qt.prototype.unshift=function(){return this.push.apply(this,arguments)},qt.prototype.unshiftAll=function(e){return this.pushAll(e)},qt.prototype.shift=function(){return this.pop.apply(this,arguments)},qt.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):Xt()},qt.prototype.slice=function(e,t){if(y(e,t,this.size))return this;var n=g(e,this.size);if(b(t,this.size)!==this.size)return ne.prototype.slice.call(this,e,t);for(var r=this.size-n,o=this._head;n--;)o=o.next;return this.__ownerID?(this.size=r,this._head=o,this.__hash=void 0,this.__altered=!0,this):Gt(r,o)},qt.prototype.__ensureOwner=function(e){return e===this.__ownerID?this:e?Gt(this.size,this._head,e,this.__hash):(this.__ownerID=e,this.__altered=!1,this)},qt.prototype.__iterate=function(e,t){if(t)return this.reverse().__iterate(e);for(var n=0,r=this._head;r&&!1!==e(r.value,n++,this);)r=r.next;return n},qt.prototype.__iterator=function(e,t){if(t)return this.reverse().__iterator(e);var n=0,r=this._head;return new w(function(){if(r){var t=r.value;return r=r.next,S(e,n++,t)}return x()})},qt.isStack=Yt;var rr="@@__IMMUTABLE_STACK__@@",or=qt.prototype;or[rr]=!0,or.withMutations=zn.withMutations,or.asMutable=zn.asMutable,or.asImmutable=zn.asImmutable,or.wasAltered=zn.wasAltered;var ir;t.Iterator=w,$t(t,{toArray:function(){ce(this.size);var e=new Array(this.size||0);return this.valueSeq().__iterate(function(t,n){e[n]=t}),e},toIndexedSeq:function(){return new ot(this)},toJS:function(){return this.toSeq().map(function(e){return e&&"function"==typeof e.toJS?e.toJS():e}).__toJS()},toJSON:function(){return this.toSeq().map(function(e){return e&&"function"==typeof e.toJSON?e.toJSON():e}).__toJS()},toKeyedSeq:function(){return new rt(this,!0)},toMap:function(){return pe(this.toKeyedSeq())},toObject:function(){ce(this.size);var e={};return this.__iterate(function(t,n){e[n]=t}),e},toOrderedMap:function(){return Ze(this.toKeyedSeq())},toOrderedSet:function(){return Bt(a(this)?this.valueSeq():this)},toSet:function(){return Lt(a(this)?this.valueSeq():this)},toSetSeq:function(){return new it(this)},toSeq:function(){return s(this)?this.toIndexedSeq():a(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return qt(a(this)?this.valueSeq():this)},toList:function(){return Fe(a(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(e,t){return 0===this.size?e+t:e+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+t},concat:function(){return _t(this,mt(this,ln.call(arguments,0)))},includes:function(e){return this.some(function(t){return X(t,e)})},entries:function(){return this.__iterator(wn)},every:function(e,t){ce(this.size);var n=!0;return this.__iterate(function(r,o,i){if(!e.call(t,r,o,i))return n=!1,!1}),n},filter:function(e,t){return _t(this,ct(this,e,t,!0))},find:function(e,t,n){var r=this.findEntry(e,t);return r?r[1]:n},forEach:function(e,t){return ce(this.size),this.__iterate(t?e.bind(t):e)},join:function(e){ce(this.size),e=void 0!==e?""+e:",";var t="",n=!0;return this.__iterate(function(r){n?n=!1:t+=e,t+=null!==r&&void 0!==r?r.toString():""}),t},keys:function(){return this.__iterator(bn)},map:function(e,t){return _t(this,lt(this,e,t))},reduce:function(e,t,n){ce(this.size);var r,o;return arguments.length<2?o=!0:r=t,this.__iterate(function(t,i,a){o?(o=!1,r=t):r=e.call(n,r,t,i,a)}),r},reduceRight:function(e,t,n){var r=this.toKeyedSeq().reverse();return r.reduce.apply(r,arguments)},reverse:function(){return _t(this,ut(this,!0))},slice:function(e,t){return _t(this,dt(this,e,t,!0))},some:function(e,t){return!this.every(Qt(e),t)},sort:function(e){return _t(this,Ct(this,e))},values:function(){return this.__iterator(Cn)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some(function(){return!0})},count:function(e,t){return h(e?this.toSeq().filter(e,t):this)},countBy:function(e,t){return pt(this,e,t)},equals:function(e){return $(this,e)},entrySeq:function(){var e=this;if(e._cache)return new I(e._cache);var t=e.toSeq().map(Zt).toIndexedSeq();return t.fromEntrySeq=function(){return e.toSeq()},t},filterNot:function(e,t){return this.filter(Qt(e),t)},findEntry:function(e,t,n){var r=n;return this.__iterate(function(n,o,i){if(e.call(t,n,o,i))return r=[o,n],!1}),r},findKey:function(e,t){var n=this.findEntry(e,t);return n&&n[0]},findLast:function(e,t,n){return this.toKeyedSeq().reverse().find(e,t,n)},findLastEntry:function(e,t,n){return this.toKeyedSeq().reverse().findEntry(e,t,n)},findLastKey:function(e,t){return this.toKeyedSeq().reverse().findKey(e,t)},first:function(){return this.find(m)},flatMap:function(e,t){return _t(this,gt(this,e,t))},flatten:function(e){return _t(this,yt(this,e,!0))},fromEntrySeq:function(){return new at(this)},get:function(e,t){return this.find(function(t,n){return X(n,e)},void 0,t)},getIn:function(e,t){for(var n,r=this,o=Mt(e);!(n=o.next()).done;){var i=n.value;if((r=r&&r.get?r.get(i,mn):mn)===mn)return t}return r},groupBy:function(e,t){return ft(this,e,t)},has:function(e){return this.get(e,mn)!==mn},hasIn:function(e){return this.getIn(e,mn)!==mn},isSubset:function(e){return e="function"==typeof e.includes?e:t(e),this.every(function(t){return e.includes(t)})},isSuperset:function(e){return e="function"==typeof e.isSubset?e:t(e),e.isSubset(this)},keyOf:function(e){return this.findKey(function(t){return X(t,e)})},keySeq:function(){return this.toSeq().map(Jt).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(e){return this.toKeyedSeq().reverse().keyOf(e)},max:function(e){return wt(this,e)},maxBy:function(e,t){return wt(this,t,e)},min:function(e){return wt(this,e?en(e):rn)},minBy:function(e,t){return wt(this,t?en(t):rn,e)},rest:function(){return this.slice(1)},skip:function(e){return this.slice(Math.max(0,e))},skipLast:function(e){return _t(this,this.toSeq().reverse().skip(e).reverse())},skipWhile:function(e,t){return _t(this,vt(this,e,t,!0))},skipUntil:function(e,t){return this.skipWhile(Qt(e),t)},sortBy:function(e,t){return _t(this,Ct(this,t,e))},take:function(e){return this.slice(0,Math.max(0,e))},takeLast:function(e){return _t(this,this.toSeq().reverse().take(e).reverse())},takeWhile:function(e,t){return _t(this,ht(this,e,t))},takeUntil:function(e,t){return this.takeWhile(Qt(e),t)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=on(this))}});var ar=t.prototype;ar[un]=!0,ar[_n]=ar.values,ar.__toJS=ar.toArray,ar.__toStringMapper=tn,ar.inspect=ar.toSource=function(){return this.toString()},ar.chain=ar.flatMap,ar.contains=ar.includes,$t(n,{flip:function(){return _t(this,st(this))},mapEntries:function(e,t){var n=this,r=0;return _t(this,this.toSeq().map(function(o,i){return e.call(t,[i,o],r++,n)}).fromEntrySeq())},mapKeys:function(e,t){var n=this;return _t(this,this.toSeq().flip().map(function(r,o){return e.call(t,r,o,n)}).flip())}});var sr=n.prototype;return sr[cn]=!0,sr[_n]=ar.entries,sr.__toJS=ar.toObject,sr.__toStringMapper=function(e,t){return JSON.stringify(t)+": "+tn(e)},$t(r,{toKeyedSeq:function(){return new rt(this,!1)},filter:function(e,t){return _t(this,ct(this,e,t,!1))},findIndex:function(e,t){var n=this.findEntry(e,t);return n?n[0]:-1},indexOf:function(e){var t=this.keyOf(e);return void 0===t?-1:t},lastIndexOf:function(e){var t=this.lastKeyOf(e);return void 0===t?-1:t},reverse:function(){return _t(this,ut(this,!1))},slice:function(e,t){return _t(this,dt(this,e,t,!1))},splice:function(e,t){var n=arguments.length;if(t=Math.max(0|t,0),0===n||2===n&&!t)return this;e=g(e,e<0?this.count():this.size);var r=this.slice(0,e);return _t(this,1===n?r:r.concat(d(arguments,2),this.slice(e+t)))},findLastIndex:function(e,t){var n=this.findLastEntry(e,t);return n?n[0]:-1},first:function(){return this.get(0)},flatten:function(e){return _t(this,yt(this,e,!1))},get:function(e,t){return e=v(this,e),e<0||this.size===1/0||void 0!==this.size&&e>this.size?t:this.find(function(t,n){return n===e},void 0,t)},has:function(e){return(e=v(this,e))>=0&&(void 0!==this.size?this.size===1/0||e<this.size:-1!==this.indexOf(e))},interpose:function(e){return _t(this,bt(this,e))},interleave:function(){var e=[this].concat(d(arguments)),t=xt(this.toSeq(),M.of,e),n=t.flatten(!0);return t.size&&(n.size=t.size*e.length),_t(this,n)},keySeq:function(){return Q(0,this.size)},last:function(){return this.get(-1)},skipWhile:function(e,t){return _t(this,vt(this,e,t,!1))},zip:function(){return _t(this,xt(this,nn,[this].concat(d(arguments))))},zipWith:function(e){var t=d(arguments);return t[0]=this,_t(this,xt(this,e,t))}}),r.prototype[pn]=!0,r.prototype[fn]=!0,$t(o,{get:function(e,t){return this.has(e)?e:t},includes:function(e){return this.has(e)},keySeq:function(){return this.valueSeq()}}),o.prototype.has=ar.includes,o.prototype.contains=o.prototype.includes,$t(P,n.prototype),$t(M,r.prototype),$t(D,o.prototype),$t(te,n.prototype),$t(ne,r.prototype),$t(re,o.prototype),{Iterable:t,Seq:N,Collection:ee,Map:pe,OrderedMap:Ze,List:Fe,Stack:qt,Set:Lt,OrderedSet:Bt,Record:Dt,Range:Q,Repeat:J,is:X,fromJS:U}})},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){"use strict";var r=n(1),o=n.n(r),i=n(8),a=n.n(i),s=n(2),l=n.n(s),u=n(7),c=n.n(u),p=n(3),f=n.n(p),d=n(4),h=n.n(d),v=n(0),m=(n.n(v),n(5)),y=n.n(m),g=n(177),b=n(6),C=n.n(b),w=n(26),S=n(46),x=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},_={prefixCls:y.a.string,className:y.a.string,size:y.a.oneOf(["default","large","small"]),combobox:y.a.bool,notFoundContent:y.a.any,showSearch:y.a.bool,optionLabelProp:y.a.string,transitionName:y.a.string,choiceTransitionName:y.a.string},k=function(e){function t(){l()(this,t);var e=f()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveSelect=function(t){e.rcSelect=t},e.renderSelect=function(t){var n,r=e.props,i=r.prefixCls,s=r.className,l=void 0===s?"":s,u=r.size,c=r.mode,p=x(r,["prefixCls","className","size","mode"]),f=C()((n={},a()(n,i+"-lg","large"===u),a()(n,i+"-sm","small"===u),n),l),d=e.props.optionLabelProp,h="combobox"===c;h&&(d=d||"value");var m={multiple:"multiple"===c,tags:"tags"===c,combobox:h};return v.createElement(g.c,o()({},p,m,{prefixCls:i,className:f,optionLabelProp:d||"children",notFoundContent:e.getNotFoundContent(t),ref:e.saveSelect}))},e}return h()(t,e),c()(t,[{key:"focus",value:function(){this.rcSelect.focus()}},{key:"blur",value:function(){this.rcSelect.blur()}},{key:"getNotFoundContent",value:function(e){var t=this.props,n=t.notFoundContent;return"combobox"===t.mode?void 0===n?null:n:void 0===n?e.notFoundContent:n}},{key:"render",value:function(){return v.createElement(w.a,{componentName:"Select",defaultLocale:S.a.Select},this.renderSelect)}}]),t}(v.Component);t.a=k,k.Option=g.b,k.OptGroup=g.a,k.defaultProps={prefixCls:"ant-select",showSearch:!1,transitionName:"slide-up",choiceTransitionName:"zoom"},k.propTypes=_},function(e,t,n){function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(311),i={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=i},function(e,t,n){var r=n(33),o=r.Symbol;e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.initializedState=t.extractObject=t.canGoNext=t.getSwipeDirection=t.getHeight=t.getWidth=t.slidesOnRight=t.slidesOnLeft=t.lazyEndIndex=t.lazyStartIndex=t.getRequiredLazySlides=t.getOnDemandLazySlides=void 0;var o=n(0),i=r(o),a=n(9),s=r(a),l=t.getOnDemandLazySlides=function(e){for(var t=[],n=u(e),r=c(e),o=n;o<r;o++)e.lazyLoadedList.indexOf(o)<0&&t.push(o);return t},u=(t.getRequiredLazySlides=function(e){for(var t=[],n=u(e),r=c(e),o=n;o<r;o++)t.push(o);return t},t.lazyStartIndex=function(e){return e.currentSlide-p(e)}),c=t.lazyEndIndex=function(e){return e.currentSlide+f(e)},p=t.slidesOnLeft=function(e){return e.centerMode?Math.floor(e.slidesToShow/2)+(parseInt(e.centerPadding)>0?1:0):0},f=t.slidesOnRight=function(e){return e.centerMode?Math.floor((e.slidesToShow-1)/2)+1+(parseInt(e.centerPadding)>0?1:0):e.slidesToShow},d=t.getWidth=function(e){return e&&e.offsetWidth||0},h=t.getHeight=function(e){return e&&e.offsetHeight||0};t.getSwipeDirection=function(e){var t,n,r,o,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return t=e.startX-e.curX,n=e.startY-e.curY,r=Math.atan2(n,t),o=Math.round(180*r/Math.PI),o<0&&(o=360-Math.abs(o)),o<=45&&o>=0||o<=360&&o>=315?"left":o>=135&&o<=225?"right":!0===i?o>=35&&o<=135?"up":"down":"vertical"},t.canGoNext=function(e){var t=!0;return e.infinite||(e.centerMode&&e.currentSlide>=e.slideCount-1?t=!1:(e.slideCount<=e.slidesToShow||e.currentSlide>=e.slideCount-e.slidesToShow)&&(t=!1)),t},t.extractObject=function(e,t){var n={};return t.forEach(function(t){return n[t]=e[t]}),n},t.initializedState=function(e){var t=i.default.Children.count(e.children),n=Math.ceil(d(s.default.findDOMNode(e.listRef))),r=Math.ceil(d(s.default.findDOMNode(e.trackRef))),o=void 0;if(e.vertical)o=n;else{var a=e.centerMode&&2*parseInt(e.centerPadding);"string"==typeof e.centerPadding&&"%"===e.centerPadding.slice(-1)&&(a*=n/100),o=Math.ceil((n-a)/e.slidesToShow)}var u=h(s.default.findDOMNode(e.listRef).querySelector('[data-index="0"]')),c=u*e.slidesToShow,p=e.currentSlide||e.initialSlide;e.rtl&&!e.currentSlide&&(p=t-1-e.initialSlide);var f=e.lazyLoadedList||[],v=l({currentSlide:p,lazyLoadedList:f},e);return f.concat(v),{slideCount:t,slideWidth:o,listWidth:n,trackWidth:r,currentSlide:p,slideHeight:u,listHeight:c,lazyLoadedList:f}}},function(e,t){function n(e,t){return e===t||e!==e&&t!==t}e.exports=n},function(e,t,n){function r(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-i?"-0":t}var o=n(91),i=1/0;e.exports=r},function(e,t,n){function r(e){return null!=e&&i(e.length)&&!o(e)}var o=n(133),i=n(136);e.exports=r},function(e,t,n){"use strict";var r=n(11),o=r.OrderedMap,i={createFromArray:function(e){return o(e.map(function(e){return[e.getKey(),e]}))}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n,r){if(e.size){var o=0;e.reduce(function(e,i,a){return t(e,i)||(n(e)&&r(o,a),o=a),i}),n(e.last())&&r(o,e.count())}}e.exports=r},function(e,t,n){"use strict";function r(e){return"handled"===e||!0===e}e.exports=r},function(e,t,n){"use strict";var r={encode:function(e,t,n){return e+"-"+t+"-"+n},decode:function(e){var t=e.split("-"),n=t[0],r=t[1],o=t[2];return{blockKey:n,decoratorKey:parseInt(r,10),leafKey:parseInt(o,10)}}};e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=e.getSelection(),i=e.getCurrentContent(),a=r;if(r.isCollapsed()){if("forward"===n){if(e.isSelectionAtEndOfContent())return i}else if(e.isSelectionAtStartOfContent())return i;if((a=t(e))===r)return i}return o.removeRange(i,a,n)}var o=n(22);e.exports=r},function(e,t,n){var r=n(168),o=n(109);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";var r=n(264)(!0);n(171)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";function r(e){return function(){return e}}var o=function(){};o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,n){"use strict";function r(){var e=0;return function(t){var n=(new Date).getTime(),r=Math.max(0,16-(n-e)),o=window.setTimeout(function(){t(n+r)},r);return e=n+r,o}}function o(){if("undefined"==typeof window)return function(){};if(window.requestAnimationFrame)return window.requestAnimationFrame.bind(window);var e=a.filter(function(e){return e+"RequestAnimationFrame"in window})[0];return e?window[e+"RequestAnimationFrame"]:r()}function i(e){if("undefined"==typeof window)return null;if(window.cancelAnimationFrame)return window.cancelAnimationFrame(e);var t=a.filter(function(e){return e+"CancelAnimationFrame"in window||e+"CancelRequestAnimationFrame"in window})[0];return t?(window[t+"CancelAnimationFrame"]||window[t+"CancelRequestAnimationFrame"]).call(this,e):clearTimeout(e)}t.b=o,t.a=i;var a=["moz","ms","webkit"]},function(e,t,n){"use strict";function r(e){var t=[];return i.a.Children.forEach(e,function(e){t.push(e)}),t}t.a=r;var o=n(0),i=n.n(o)},function(e,t,n){"use strict";e.exports=n(303)},function(e,t,n){"use strict";var r=n(123),o=n(316),i=n(317),a=n(318);n.n(a);n.d(t,"Button",function(){return i.a}),n.d(t,"Group",function(){return o.a}),r.a.Button=i.a,r.a.Group=o.a,t.default=r.a},function(e,t,n){function r(e){return"symbol"==typeof e||i(e)&&o(e)==a}var o=n(52),i=n(43),a="[object Symbol]";e.exports=r},function(e,t,n){var r=n(53),o=r(Object,"create");e.exports=o},function(e,t,n){function r(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(354),i=n(355),a=n(356),s=n(357),l=n(358);r.prototype.clear=o,r.prototype.delete=i,r.prototype.get=a,r.prototype.has=s,r.prototype.set=l,e.exports=r},function(e,t,n){function r(e,t){for(var n=e.length;n--;)if(o(e[n][0],t))return n;return-1}var o=n(74);e.exports=r},function(e,t,n){function r(e,t){var n=e.__data__;return o(t)?n["string"==typeof t?"string":"hash"]:n.map}var o=n(360);e.exports=r},function(e,t){function n(e,t){var n=typeof e;return!!(t=null==t?r:t)&&("number"==n||"symbol"!=n&&o.test(e))&&e>-1&&e%1==0&&e<t}var r=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=n},function(e,t,n){"use strict";var r=n(208),o=n(209),i=function(e,t){var n=t.getStartKey(),i=t.getStartOffset(),a=t.getEndKey(),s=t.getEndOffset(),l=o(e,t),u=l.getBlockMap(),c=u.keySeq(),p=c.indexOf(n),f=c.indexOf(a)+1;return r(u.slice(p,f).map(function(e,t){var r=e.getText(),o=e.getCharacterList();return n===a?e.merge({text:r.slice(i,s),characterList:o.slice(i,s)}):t===n?e.merge({text:r.slice(i),characterList:o.slice(i)}):t===a?e.merge({text:r.slice(0,s),characterList:o.slice(0,s)}):e}))};e.exports=i},function(e,t,n){"use strict";function r(e,t){console.warn("WARNING: "+e+' will be deprecated soon!\nPlease use "'+t+'" instead.')}var o=n(16),i=o||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(213),s=n(11),l=n(10),u=s.Map,c=u(),p=0,f={getLastCreatedEntityKey:function(){return r("DraftEntity.getLastCreatedEntityKey","contentState.getLastCreatedEntityKey"),f.__getLastCreatedEntityKey()},create:function(e,t,n){return r("DraftEntity.create","contentState.createEntity"),f.__create(e,t,n)},add:function(e){return r("DraftEntity.add","contentState.addEntity"),f.__add(e)},get:function(e){return r("DraftEntity.get","contentState.getEntity"),f.__get(e)},mergeData:function(e,t){return r("DraftEntity.mergeData","contentState.mergeEntityData"),f.__mergeData(e,t)},replaceData:function(e,t){return r("DraftEntity.replaceData","contentState.replaceEntityData"),f.__replaceData(e,t)},__getLastCreatedEntityKey:function(){return""+p},__create:function(e,t,n){return f.__add(new a({type:e,mutability:t,data:n||{}}))},__add:function(e){var t=""+ ++p;return c=c.set(t,e),t},__get:function(e){var t=c.get(e);return t||l(!1),t},__mergeData:function(e,t){var n=f.__get(e),r=i({},n.getData(),t),o=n.set("data",r);return c=c.set(e,o),o},__replaceData:function(e,t){var n=f.__get(e),r=n.set("data",t);return c=c.set(e,r),r}};e.exports=f},function(e,t){function n(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}e.exports=n},function(e,t,n){"use strict";var r={placeholder:"Select time"};t.a=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(581));n.n(o),n(161)},function(e,t,n){var r=n(255);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(57);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(108)("keys"),o=n(83);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(40),o=r["__core-js_shared__"]||(r["__core-js_shared__"]={});e.exports=function(e){return o[e]||(o[e]={})}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(105);e.exports=function(e){return Object(r(e))}},function(e,t){e.exports=!0},function(e,t,n){var r=n(48),o=n(266),i=n(109),a=n(107)("IE_PROTO"),s=function(){},l=function(){var e,t=n(167)("iframe"),r=i.length;for(t.style.display="none",n(267).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("<script>document.F=Object<\/script>"),e.close(),l=e.F;r--;)delete l.prototype[i[r]];return l()};e.exports=Object.create||function(e,t){var n;return null!==e?(s.prototype=r(e),n=new s,s.prototype=null,n[a]=e):n=l(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(41).f,o=n(50),i=n(30)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){n(269);for(var r=n(40),o=n(56),i=n(59),a=n(30)("toStringTag"),s="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),l=0;l<s.length;l++){var u=s[l],c=r[u],p=c&&c.prototype;p&&!p[a]&&o(p,a,u),i[u]=i.Array}},function(e,t,n){t.f=n(30)},function(e,t,n){var r=n(40),o=n(29),i=n(112),a=n(116),s=n(41).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:a.f(e)})}},function(e,t,n){"use strict";function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}function i(e,t){for(var n=window.getComputedStyle(e,null),r="",o=0;o<g.length&&!(r=n.getPropertyValue(g[o]+t));o++);return r}function a(e){if(m){var t=parseFloat(i(e,"transition-delay"))||0,n=parseFloat(i(e,"transition-duration"))||0,r=parseFloat(i(e,"animation-delay"))||0,o=parseFloat(i(e,"animation-duration"))||0,a=Math.max(n+t,o+r);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*a+200)}}function s(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}var l=n(19),u=n.n(l),c={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},p=[];"undefined"!=typeof window&&"undefined"!=typeof document&&function(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete c.animationend.animation,"TransitionEvent"in window||delete c.transitionend.transition;for(var n in c)if(c.hasOwnProperty(n)){var r=c[n];for(var o in r)if(o in t){p.push(r[o]);break}}}();var f={addEndEventListener:function(e,t){if(0===p.length)return void window.setTimeout(t,0);p.forEach(function(n){r(e,n,t)})},endEvents:p,removeEndEventListener:function(e,t){0!==p.length&&p.forEach(function(n){o(e,n,t)})}},d=f,h=n(119),v=n.n(h);n.d(t,"b",function(){return m});var m=0!==d.endEvents.length,y=["Webkit","Moz","O","ms"],g=["-webkit-","-moz-","-o-","ms-",""],b=function(e,t,n){var r="object"===(void 0===t?"undefined":u()(t)),o=r?t.name:t,i=r?t.active:t+"-active",l=n,c=void 0,p=void 0,f=v()(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(l=n.end,c=n.start,p=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),s(e),f.remove(o),f.remove(i),d.removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,l&&l())},d.addEndEventListener(e,e.rcEndListener),c&&c(),f.add(o),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,f.add(i),p&&setTimeout(p,0),a(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};b.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),s(e),d.removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},d.addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,a(e)},0)},b.setTransition=function(e,t,n){var r=t,o=n;void 0===n&&(o=r,r=""),r=r||"",y.forEach(function(t){e.style[t+"Transition"+r]=o})},b.isCssAnimationSupported=m;t.a=b},function(e,t,n){function r(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var o=n(178)}catch(e){var o=n(178)}var i=/\s+/,a=Object.prototype.toString;e.exports=function(e){return new r(e)},r.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array();return~o(t,e)||t.push(e),this.el.className=t.join(" "),this},r.prototype.remove=function(e){if("[object RegExp]"==a.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=o(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},r.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},r.prototype.toggle=function(e,t){return this.list?(void 0!==t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):(void 0!==t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},r.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(i);return""===n[0]&&n.shift(),n},r.prototype.has=r.prototype.contains=function(e){return this.list?this.list.contains(e):!!~o(this.array(),e)}},function(e,t,n){"use strict";function r(){var e=[].slice.call(arguments,0);return 1===e.length?e[0]:function(){for(var t=0;t<e.length;t++)e[t]&&e[t].apply&&e[t].apply(this,arguments)}}t.a=r},function(e,t,n){"use strict";var r=n(1),o=n.n(r),i=n(162),a=n(100),s={lang:o()({placeholder:"Select date",rangePlaceholder:["Start date","End date"]},i.a),timePickerLocale:o()({},a.a)};t.a=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(305),i=r(o),a=n(308),s=r(a);t.default=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,l=(0,s.default)(e);!(r=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&l.return&&l.return()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if((0,i.default)(Object(t)))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(e,t,n){"use strict";var r=n(8),o=n.n(r),i=n(1),a=n.n(i),s=n(2),l=n.n(s),u=n(7),c=n.n(u),p=n(3),f=n.n(p),d=n(4),h=n.n(d),v=n(0),m=(n.n(v),n(5)),y=n.n(m),g=n(183),b=n(6),C=n.n(b),w=n(31),S=n.n(w),x=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},_=function(e){function t(){l()(this,t);var e=f()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveCheckbox=function(t){e.rcCheckbox=t},e}return h()(t,e),c()(t,[{key:"shouldComponentUpdate",value:function(e,t,n){return!S()(this.props,e)||!S()(this.state,t)||!S()(this.context.radioGroup,n.radioGroup)}},{key:"focus",value:function(){this.rcCheckbox.focus()}},{key:"blur",value:function(){this.rcCheckbox.blur()}},{key:"render",value:function(){var e,t=this.props,n=this.context,r=t.prefixCls,i=t.className,s=t.children,l=t.style,u=x(t,["prefixCls","className","children","style"]),c=n.radioGroup,p=a()({},u);c&&(p.name=c.name,p.onChange=c.onChange,p.checked=t.value===c.value,p.disabled=t.disabled||c.disabled);var f=C()(i,(e={},o()(e,r+"-wrapper",!0),o()(e,r+"-wrapper-checked",p.checked),o()(e,r+"-wrapper-disabled",p.disabled),e));return v.createElement("label",{className:f,style:l,onMouseEnter:t.onMouseEnter,onMouseLeave:t.onMouseLeave},v.createElement(g.a,a()({},p,{prefixCls:r,ref:this.saveCheckbox})),void 0!==s?v.createElement("span",null,s):null)}}]),t}(v.Component);t.a=_,_.defaultProps={prefixCls:"ant-radio",type:"radio"},_.contextTypes={radioGroup:y.a.any}},function(e,t,n){function r(e,t,n){function r(t){var n=g,r=b;return g=b=void 0,_=t,w=e.apply(r,n)}function c(e){return _=e,S=setTimeout(d,t),k?r(e):w}function p(e){var n=e-x,r=e-_,o=t-n;return E?u(o,C-r):o}function f(e){var n=e-x,r=e-_;return void 0===x||n>=t||n<0||E&&r>=C}function d(){var e=i();if(f(e))return h(e);S=setTimeout(d,p(e))}function h(e){return S=void 0,O&&g?r(e):(g=b=void 0,w)}function v(){void 0!==S&&clearTimeout(S),_=0,g=x=b=S=void 0}function m(){return void 0===S?w:h(i())}function y(){var e=i(),n=f(e);if(g=arguments,b=this,x=e,n){if(void 0===S)return c(x);if(E)return S=setTimeout(d,t),r(x)}return void 0===S&&(S=setTimeout(d,t)),w}var g,b,C,w,S,x,_=0,k=!1,E=!1,O=!0;if("function"!=typeof e)throw new TypeError(s);return t=a(t)||0,o(n)&&(k=!!n.leading,E="maxWait"in n,C=E?l(a(n.maxWait)||0,t):C,O="trailing"in n?!!n.trailing:O),y.cancel=v,y.flush=m,y}var o=n(32),i=n(319),a=n(320),s="Expected a function",l=Math.max,u=Math.min;e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=void 0,s=void 0;return Object(o.a)(e,"ant-motion-collapse",{start:function(){t?(r=e.offsetHeight,e.style.height="0px",e.style.opacity="0"):(e.style.height=e.offsetHeight+"px",e.style.opacity="1")},active:function(){s&&Object(i.a)(s),s=a(function(){e.style.height=(t?r:0)+"px",e.style.opacity=t?"1":"0"})},end:function(){s&&Object(i.a)(s),e.style.height="",e.style.opacity="",n()}})}var o=n(118),i=n(87),a=Object(i.b)(),s={enter:function(e,t){return r(e,!0,t)},leave:function(e,t){return r(e,!1,t)},appear:function(e,t){return r(e,!0,t)}};t.a=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.getTrackLeft=t.getTrackAnimateCSS=t.getTrackCSS=void 0;var o=n(9),i=r(o),a=n(16),s=r(a),l=n(127),u=function(e,t){return t.reduce(function(t,n){return t&&e.hasOwnProperty(n)},!0)?null:console.error("Keys Missing",e)},c=t.getTrackCSS=function(e){u(e,["left","variableWidth","slideCount","slidesToShow","slideWidth"]);var t,n,r=e.slideCount+2*e.slidesToShow;e.vertical?n=r*e.slideHeight:t=(0,l.getTotalSlides)(e)*e.slideWidth;var o={opacity:1,WebkitTransform:e.vertical?"translate3d(0px, "+e.left+"px, 0px)":"translate3d("+e.left+"px, 0px, 0px)",transform:e.vertical?"translate3d(0px, "+e.left+"px, 0px)":"translate3d("+e.left+"px, 0px, 0px)",transition:"",WebkitTransition:"",msTransform:e.vertical?"translateY("+e.left+"px)":"translateX("+e.left+"px)"};return e.fade&&(o={opacity:1}),t&&(0,s.default)(o,{width:t}),n&&(0,s.default)(o,{height:n}),window&&!window.addEventListener&&window.attachEvent&&(e.vertical?o.marginTop=e.left+"px":o.marginLeft=e.left+"px"),o};t.getTrackAnimateCSS=function(e){u(e,["left","variableWidth","slideCount","slidesToShow","slideWidth","speed","cssEase"]);var t=c(e);return t.WebkitTransition="-webkit-transform "+e.speed+"ms "+e.cssEase,t.transition="transform "+e.speed+"ms "+e.cssEase,t},t.getTrackLeft=function(e){if(e.unslick)return 0;u(e,["slideIndex","trackRef","infinite","centerMode","slideCount","slidesToShow","slidesToScroll","slideWidth","listWidth","variableWidth","slideHeight"]);var t,n,r=e.slideIndex,o=e.trackRef,a=e.infinite,s=e.centerMode,c=e.slideCount,p=e.slidesToShow,f=e.slidesToScroll,d=e.slideWidth,h=e.listWidth,v=e.variableWidth,m=e.slideHeight,y=e.fade,g=e.vertical,b=0,C=0;if(y||1===e.slideCount)return 0;var w=0;if(a?(w=-(0,l.getPreClones)(e),c%f!=0&&r+f>c&&(w=-(r>c?p-(r-c):c%f)),s&&(w+=parseInt(p/2))):(c%f!=0&&r+f>c&&(w=p-c%f),s&&(w=parseInt(p/2))),b=w*d,C=w*m,t=g?r*m*-1+C:r*d*-1+b,!0===v){var S;i.default.findDOMNode(o).children[c-1];if(S=r+(0,l.getPreClones)(e),n=i.default.findDOMNode(o).childNodes[S],t=n?-1*n.offsetLeft:0,!0===s){S=a?r+(0,l.getPreClones)(e):r,n=i.default.findDOMNode(o).children[S],t=0;for(var x=0;x<S;x++)t-=i.default.findDOMNode(o).children[x].offsetWidth;t-=parseInt(e.centerPadding),t+=(h-n.offsetWidth)/2}}return t}},function(e,t,n){"use strict";function r(e){var t=e.currentSlide,n=e.targetSlide,r=e.slidesToShow,a=e.centerMode,s=e.rtl;return n>t?n>t+o(r,a,s)?"left":"right":n<t-i(r,a,s)?"right":"left"}function o(e,t,n){if(t){var r=(e-1)/2+1;return n&&e%2==0&&(r+=1),r}return n?0:e-1}function i(e,t,n){if(t){var r=(e-1)/2+1;return n||e%2!=0||(r+=1),r}return n?e-1:0}t.__esModule=!0,t.siblingDirection=r,t.slidesOnRight=o,t.slidesOnLeft=i;var a=t.getPreClones=function(e){return e.unslick||!e.infinite?0:e.variableWidth?e.slideCount:e.slidesToShow+(e.centerMode?1:0)},s=t.getPostClones=function(e){return e.unslick||!e.infinite?0:e.slideCount};t.getTotalSlides=function(e){return 1===e.slideCount?1:a(e)+e.slideCount+s(e)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(0),a=r(i),s=n(9),l=r(s),u=n(126),c=n(16),p=r(c),f=n(73),d={update:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=l.default.findDOMNode(this.list),o=a.default.Children.count(e.children),i=(0,f.getWidth)(r),s=(0,f.getWidth)(l.default.findDOMNode(this.track));if(e.vertical)t=Math.ceil((0,f.getWidth)(r));else{var c=e.centerMode&&2*parseInt(e.centerPadding);"%"===e.centerPadding.slice(-1)&&(c*=i/100),t=Math.ceil(((0,f.getWidth)(r)-c)/e.slidesToShow)}var d=(0,f.getHeight)(r.querySelector('[data-index="0"]')),h=d*e.slidesToShow;e.autoplay?this.autoPlay(e.autoplay):this.pause();var v=(0,f.getOnDemandLazySlides)({},this.props,this.state);v.length>0&&this.props.onLazyLoad&&this.props.onLazyLoad(v);var m=this.state.lazyLoadedList;this.setState({slideCount:o,slideWidth:t,listWidth:i,trackWidth:s,slideHeight:d,listHeight:h,lazyLoadedList:m.concat(v)},function(){t||n<2&&this.update(this.props,n+1);var r=(0,u.getTrackLeft)((0,p.default)({slideIndex:this.state.currentSlide,trackRef:this.track},e,this.state)),o=(0,u.getTrackCSS)((0,p.default)({left:r},e,this.state));this.setState({trackStyle:o})})},adaptHeight:function(){if(this.props.adaptiveHeight){var e='[data-index="'+this.state.currentSlide+'"]';if(this.list){var t=l.default.findDOMNode(this.list),n=t.querySelector(e)||{};t.style.height=(n.offsetHeight||0)+"px"}}},slideHandler:function(e){var t,n,r,o,i,a=this;if(!this.props.waitForAnimate||!this.state.animating){if(this.props.fade){if(n=this.state.currentSlide,!1===this.props.infinite&&(e<0||e>=this.state.slideCount))return;return t=e<0?e+this.state.slideCount:e>=this.state.slideCount?e-this.state.slideCount:e,this.props.lazyLoad&&this.state.lazyLoadedList.indexOf(t)<0&&(this.setState(function(e,n){return{lazyLoadedList:e.lazyLoadedList.concat(t)}}),this.props.onLazyLoad&&this.props.onLazyLoad([t])),i=function(){a.setState({animating:!1}),a.props.afterChange&&a.props.afterChange(t),delete a.animationEndCallback},this.setState({animating:!0,currentSlide:t},function(){a.props.asNavFor&&a.props.asNavFor.innerSlider.state.currentSlide!==a.state.currentSlide&&a.props.asNavFor.innerSlider.slideHandler(e),a.animationEndCallback=setTimeout(i,a.props.speed)}),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,t),void this.autoPlay()}if(t=e,t<0?n=!1===this.props.infinite?0:this.state.slideCount%this.props.slidesToScroll!=0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+t:this.props.centerMode&&t>=this.state.slideCount?!1===this.props.infinite?(t=this.state.slideCount-1,n=this.state.slideCount-1):(t=this.state.slideCount,n=0):n=t>=this.state.slideCount?!1===this.props.infinite?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!=0?0:t-this.state.slideCount:this.state.currentSlide+this.slidesToShow<this.state.slideCount&&t+this.props.slidesToShow>=this.state.slideCount?!1===this.props.infinite?this.state.slideCount-this.props.slidesToShow:(this.state.slideCount-t)%this.props.slidesToScroll!=0?this.state.slideCount-this.props.slidesToShow:t:t,r=(0,u.getTrackLeft)((0,p.default)({slideIndex:t,trackRef:this.track},this.props,this.state)),o=(0,u.getTrackLeft)((0,p.default)({slideIndex:n,trackRef:this.track},this.props,this.state)),!1===this.props.infinite&&(r===o&&(t=n),r=o),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,n),this.props.lazyLoad){var s=(0,f.getOnDemandLazySlides)((0,p.default)({},this.props,this.state,{currentSlide:t}));s.length>0&&(this.setState(function(e,t){return{lazyLoadedList:e.lazyLoadedList.concat(s)}}),this.props.onLazyLoad&&this.props.onLazyLoad(s))}if(!1===this.props.useCSS)this.setState({currentSlide:n,trackStyle:(0,u.getTrackCSS)((0,p.default)({left:o},this.props,this.state))},function(){this.props.afterChange&&this.props.afterChange(n)});else{var l={animating:!1,currentSlide:n,trackStyle:(0,u.getTrackCSS)((0,p.default)({left:o},this.props,this.state)),swipeLeft:null};i=function(){a.setState(l,function(){a.props.afterChange&&a.props.afterChange(n),delete a.animationEndCallback})},this.setState({animating:!0,currentSlide:n,trackStyle:(0,u.getTrackAnimateCSS)((0,p.default)({left:r},this.props,this.state))},function(){a.props.asNavFor&&a.props.asNavFor.innerSlider.state.currentSlide!==a.state.currentSlide&&a.props.asNavFor.innerSlider.slideHandler(e),a.animationEndCallback=setTimeout(i,a.props.speed)})}this.autoPlay()}},play:function(){var e;if(this.props.rtl)e=this.state.currentSlide-this.props.slidesToScroll;else{if(!(0,f.canGoNext)(o({},this.props,this.state)))return!1;e=this.state.currentSlide+this.props.slidesToScroll}this.slideHandler(e)},autoPlay:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.autoplayTimer&&clearTimeout(this.autoplayTimer),(e||this.props.autoplay)&&(this.autoplayTimer=setTimeout(this.play,this.props.autoplaySpeed))},pause:function(){this.autoplayTimer&&(clearTimeout(this.autoplayTimer),this.autoplayTimer=null)}};t.default=d},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=n(1),l=n.n(s),u=n(2),c=n.n(u),p=n(7),f=n.n(p),d=n(3),h=n.n(d),v=n(4),m=n.n(v),y=n(0),g=n.n(y),b=n(5),C=n.n(b),w=n(9),S=n.n(w),x=n(42),_={adjustX:1,adjustY:1},k=[0,0],E={topLeft:{points:["bl","tl"],overflow:_,offset:[0,-4],targetOffset:k},topCenter:{points:["bc","tc"],overflow:_,offset:[0,-4],targetOffset:k},topRight:{points:["br","tr"],overflow:_,offset:[0,-4],targetOffset:k},bottomLeft:{points:["tl","bl"],overflow:_,offset:[0,4],targetOffset:k},bottomCenter:{points:["tc","bc"],overflow:_,offset:[0,4],targetOffset:k},bottomRight:{points:["tr","br"],overflow:_,offset:[0,4],targetOffset:k}},O=E,T=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},N=function(e){function t(n){o(this,t);var r=i(this,e.call(this,n));return P.call(r),r.state="visible"in n?{visible:n.visible}:{visible:n.defaultVisible},r}return a(t,e),t.prototype.componentWillReceiveProps=function(e){var t=e.visible;void 0!==t&&this.setState({visible:t})},t.prototype.getMenuElement=function(){var e=this.props,t=e.overlay,n=e.prefixCls,r={prefixCls:n+"-menu",onClick:this.onClick};return"string"==typeof t.type&&delete r.prefixCls,g.a.cloneElement(t,r)},t.prototype.getPopupDomNode=function(){return this.trigger.getPopupDomNode()},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.children,o=e.transitionName,i=e.animation,a=e.align,s=e.placement,l=e.getPopupContainer,u=e.showAction,c=e.hideAction,p=e.overlayClassName,f=e.overlayStyle,d=e.trigger,h=r(e,["prefixCls","children","transitionName","animation","align","placement","getPopupContainer","showAction","hideAction","overlayClassName","overlayStyle","trigger"]);return g.a.createElement(x.a,T({},h,{prefixCls:t,ref:this.saveTrigger,popupClassName:p,popupStyle:f,builtinPlacements:O,action:d,showAction:u,hideAction:c,popupPlacement:s,popupAlign:a,popupTransitionName:o,popupAnimation:i,popupVisible:this.state.visible,afterPopupVisibleChange:this.afterVisibleChange,popup:this.getMenuElement(),onPopupVisibleChange:this.onVisibleChange,getPopupContainer:l}),n)},t}(y.Component);N.propTypes={minOverlayWidthMatchTrigger:C.a.bool,onVisibleChange:C.a.func,onOverlayClick:C.a.func,prefixCls:C.a.string,children:C.a.any,transitionName:C.a.string,overlayClassName:C.a.string,animation:C.a.any,align:C.a.object,overlayStyle:C.a.object,placement:C.a.string,overlay:C.a.node,trigger:C.a.array,showAction:C.a.array,hideAction:C.a.array,getPopupContainer:C.a.func,visible:C.a.bool,defaultVisible:C.a.bool},N.defaultProps={minOverlayWidthMatchTrigger:!0,prefixCls:"rc-dropdown",trigger:["hover"],showAction:[],hideAction:[],overlayClassName:"",overlayStyle:{},defaultVisible:!1,onVisibleChange:function(){},placement:"bottomLeft"};var P=function(){var e=this;this.onClick=function(t){var n=e.props,r=n.overlay.props;"visible"in n||e.setState({visible:!1}),n.onOverlayClick&&n.onOverlayClick(t),r.onClick&&r.onClick(t)},this.onVisibleChange=function(t){var n=e.props;"visible"in n||e.setState({visible:t}),n.onVisibleChange(t)},this.afterVisibleChange=function(t){if(t&&e.props.minOverlayWidthMatchTrigger){var n=e.getPopupDomNode(),r=S.a.findDOMNode(e);r&&n&&r.offsetWidth>n.offsetWidth&&(n.style.minWidth=r.offsetWidth+"px",e.trigger&&e.trigger._component&&e.trigger._component.alignInstance&&e.trigger._component.alignInstance.forceAlign())}},this.saveTrigger=function(t){e.trigger=t}},M=N,D=M,I=n(6),A=n.n(I),j=n(27),R=function(e){function t(){return c()(this,t),h()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return m()(t,e),f()(t,[{key:"getTransitionName",value:function(){var e=this.props,t=e.placement,n=void 0===t?"":t,r=e.transitionName;return void 0!==r?r:n.indexOf("top")>=0?"slide-down":"slide-up"}},{key:"componentDidMount",value:function(){var e=this.props.overlay,t=e.props;Object(j.a)(!t.mode||"vertical"===t.mode,'mode="'+t.mode+"\" is not supported for Dropdown's Menu.")}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.prefixCls,r=e.overlay,o=e.trigger,i=e.disabled,a=y.Children.only(t),s=y.Children.only(r),u=y.cloneElement(a,{className:A()(a.props.className,n+"-trigger"),disabled:i}),c=s.props.selectable||!1,p=y.cloneElement(s,{mode:"vertical",selectable:c});return y.createElement(D,l()({},this.props,{transitionName:this.getTransitionName(),trigger:i?[]:o,overlay:p}),u)}}]),t}(y.Component),L=R;R.defaultProps={prefixCls:"ant-dropdown",mouseEnterDelay:.15,mouseLeaveDelay:.1,placement:"bottomLeft"};var K=n(51),F=n(14),V=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},z=K.a.Group,B=function(e){function t(){return c()(this,t),h()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return m()(t,e),f()(t,[{key:"render",value:function(){var e=this.props,t=e.type,n=e.disabled,r=e.onClick,o=e.children,i=e.prefixCls,a=e.className,s=e.overlay,u=e.trigger,c=e.align,p=e.visible,f=e.onVisibleChange,d=e.placement,h=e.getPopupContainer,v=V(e,["type","disabled","onClick","children","prefixCls","className","overlay","trigger","align","visible","onVisibleChange","placement","getPopupContainer"]),m={align:c,overlay:s,disabled:n,trigger:n?[]:u,onVisibleChange:f,placement:d,getPopupContainer:h};return"visible"in this.props&&(m.visible=p),y.createElement(z,l()({},v,{className:A()(i,a)}),y.createElement(K.a,{type:t,disabled:n,onClick:r},o),y.createElement(L,m,y.createElement(K.a,{type:t},y.createElement(F.a,{type:"down"}))))}}]),t}(y.Component),W=B;B.defaultProps={placement:"bottomRight",type:"default",prefixCls:"ant-dropdown-button"},n.d(t,!1,function(){}),n.d(t,!1,function(){}),L.Button=W;t.a=L},function(e,t,n){function r(e,t){return o(e)?e:i(e,t)?[e]:a(s(e))}var o=n(37),i=n(131),a=n(340),s=n(364);e.exports=r},function(e,t,n){function r(e,t){if(o(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!i(e))||(s.test(e)||!a.test(e)||null!=t&&e in Object(t))}var o=n(37),i=n(91),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,s=/^\w*$/;e.exports=r},function(e,t,n){function r(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(343),i=n(359),a=n(361),s=n(362),l=n(363);r.prototype.clear=o,r.prototype.delete=i,r.prototype.get=a,r.prototype.has=s,r.prototype.set=l,e.exports=r},function(e,t,n){function r(e){if(!i(e))return!1;var t=o(e);return t==s||t==l||t==a||t==u}var o=n(52),i=n(32),a="[object AsyncFunction]",s="[object Function]",l="[object GeneratorFunction]",u="[object Proxy]";e.exports=r},function(e,t,n){var r=n(53),o=n(33),i=r(o,"Map");e.exports=i},function(e,t,n){var r=n(366),o=n(43),i=Object.prototype,a=i.hasOwnProperty,s=i.propertyIsEnumerable,l=r(function(){return arguments}())?r:function(e){return o(e)&&a.call(e,"callee")&&!s.call(e,"callee")};e.exports=l},function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=r}var r=9007199254740991;e.exports=n},function(e,t,n){function r(e,t,n){var r=null==e?void 0:o(e,t);return void 0===r?n:r}var o=n(193);e.exports=r},function(e,t,n){function r(e,t,n){"__proto__"==t&&o?o(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}var o=n(196);e.exports=r},function(e,t,n){"use strict";function r(){if(void 0!==S)return S;var e="Webkit Moz O ms Khtml".split(" "),t=document.createElement("div");if(void 0!==t.style.animationName&&(S=!0),void 0!==S)for(var n=0;n<e.length;n++)if(void 0!==t.style[e[n]+"AnimationName"]){S=!0;break}return S=S||!1}var o=n(1),i=n.n(o),a=n(8),s=n.n(a),l=n(2),u=n.n(l),c=n(7),p=n.n(c),f=n(3),d=n.n(f),h=n(4),v=n.n(h),m=n(0),y=n(5),g=n.n(y),b=n(6),C=n.n(b),w=n(18),S=void 0,x=r,_=n(20),k=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},E=function(e){function t(e){u()(this,t);var n=d()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e)),r=e.spinning;return n.state={spinning:r},n}return v()(t,e),p()(t,[{key:"isNestedPattern",value:function(){return!(!this.props||!this.props.children)}},{key:"componentDidMount",value:function(){x()||this.setState({notCssAnimationSupported:!0})}},{key:"componentWillUnmount",value:function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.delayTimeout&&clearTimeout(this.delayTimeout)}},{key:"componentWillReceiveProps",value:function(e){var t=this,n=this.props.spinning,r=e.spinning,o=this.props.delay;this.debounceTimeout&&clearTimeout(this.debounceTimeout),n&&!r?(this.debounceTimeout=window.setTimeout(function(){return t.setState({spinning:r})},200),this.delayTimeout&&clearTimeout(this.delayTimeout)):r&&o&&!isNaN(Number(o))?(this.delayTimeout&&clearTimeout(this.delayTimeout),this.delayTimeout=window.setTimeout(function(){return t.setState({spinning:r})},o)):this.setState({spinning:r})}},{key:"renderIndicator",value:function(){var e=this.props,t=e.prefixCls,n=e.indicator,r=t+"-dot";return m.isValidElement(n)?m.cloneElement(n,{className:C()(n.props.className,r)}):m.createElement("span",{className:C()(r,t+"-dot-spin")},m.createElement("i",null),m.createElement("i",null),m.createElement("i",null),m.createElement("i",null))}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=t.size,o=t.prefixCls,a=t.tip,l=t.wrapperClassName,u=k(t,["className","size","prefixCls","tip","wrapperClassName"]),c=this.state,p=c.spinning,f=c.notCssAnimationSupported,d=C()(o,(e={},s()(e,o+"-sm","small"===r),s()(e,o+"-lg","large"===r),s()(e,o+"-spinning",p),s()(e,o+"-show-text",!!a||f),e),n),h=Object(_.a)(u,["spinning","delay","indicator"]),v=m.createElement("div",i()({},h,{className:d}),this.renderIndicator(),a?m.createElement("div",{className:o+"-text"},a):null);if(this.isNestedPattern()){var y,g=o+"-nested-loading";l&&(g+=" "+l);var b=C()((y={},s()(y,o+"-container",!0),s()(y,o+"-blur",p),y));return m.createElement(w.a,i()({},h,{component:"div",className:g,style:null,transitionName:"fade"}),p&&m.createElement("div",{key:"loading"},v),m.createElement("div",{className:b,key:"container"},this.props.children))}return v}}]),t}(m.Component);t.a=E;E.defaultProps={prefixCls:"ant-spin",spinning:!0,size:"default",wrapperClassName:""},E.propTypes={prefixCls:g.a.string,className:g.a.string,spinning:g.a.bool,size:g.a.oneOf(["small","default","large"]),wrapperClassName:g.a.string,indicator:g.a.node}},function(e,t,n){"use strict";function r(){}function o(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e}function i(e,t,n){return n}var a=n(1),s=n.n(a),l=n(2),u=n.n(l),c=n(7),p=n.n(c),f=n(3),d=n.n(f),h=n(4),v=n.n(h),m=n(0),y=n.n(m),g=n(5),b=n.n(g),C=function(e){var t=e.rootPrefixCls+"-item",n=t+" "+t+"-"+e.page;e.active&&(n=n+" "+t+"-active"),e.className&&(n=n+" "+e.className);var r=function(){e.onClick(e.page)},o=function(t){e.onKeyPress(t,e.onClick,e.page)};return y.a.createElement("li",{title:e.showTitle?e.page:null,className:n,onClick:r,onKeyPress:o,tabIndex:"0"},e.itemRender(e.page,"page",y.a.createElement("a",null,e.page)))};C.propTypes={page:b.a.number,active:b.a.bool,last:b.a.bool,locale:b.a.object,className:b.a.string,showTitle:b.a.bool,rootPrefixCls:b.a.string,onClick:b.a.func,onKeyPress:b.a.func,itemRender:b.a.func};var w=C,S={ZERO:48,NINE:57,NUMPAD_ZERO:96,NUMPAD_NINE:105,BACKSPACE:8,DELETE:46,ENTER:13,ARROW_UP:38,ARROW_DOWN:40},x=function(e){function t(e){u()(this,t);var n=d()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.buildOptionText=function(e){return e+" "+n.props.locale.items_per_page},n.changeSize=function(e){n.props.changeSize(Number(e))},n.handleChange=function(e){n.setState({goInputText:e.target.value})},n.go=function(e){var t=n.state.goInputText;""!==t&&(t=Number(t),isNaN(t)&&(t=n.state.current),e.keyCode!==S.ENTER&&"click"!==e.type||n.setState({goInputText:"",current:n.props.quickGo(t)}))},n.state={current:e.current,goInputText:""},n}return v()(t,e),p()(t,[{key:"render",value:function(){var e=this.props,t=this.state,n=e.locale,r=e.rootPrefixCls+"-options",o=e.changeSize,i=e.quickGo,a=e.goButton,s=e.buildOptionText||this.buildOptionText,l=e.selectComponentClass,u=null,c=null,p=null;if(!o&&!i)return null;if(o&&l){var f=l.Option,d=e.pageSize||e.pageSizeOptions[0],h=e.pageSizeOptions.map(function(e,t){return y.a.createElement(f,{key:t,value:e},s(e))});u=y.a.createElement(l,{prefixCls:e.selectPrefixCls,showSearch:!1,className:r+"-size-changer",optionLabelProp:"children",dropdownMatchSelectWidth:!1,value:d.toString(),onChange:this.changeSize,getPopupContainer:function(e){return e.parentNode}},h)}return i&&(a&&(p="boolean"==typeof a?y.a.createElement("button",{type:"button",onClick:this.go,onKeyUp:this.go},n.jump_to_confirm):y.a.createElement("span",{onClick:this.go,onKeyUp:this.go},a)),c=y.a.createElement("div",{className:r+"-quick-jumper"},n.jump_to,y.a.createElement("input",{type:"text",value:t.goInputText,onChange:this.handleChange,onKeyUp:this.go}),n.page,p)),y.a.createElement("li",{className:""+r},u,c)}}]),t}(y.a.Component);x.propTypes={changeSize:b.a.func,quickGo:b.a.func,selectComponentClass:b.a.func,current:b.a.number,pageSizeOptions:b.a.arrayOf(b.a.string),pageSize:b.a.number,buildOptionText:b.a.func,locale:b.a.object},x.defaultProps={pageSizeOptions:["10","20","30","40"]};var _=x,k=n(246),E=function(e){function t(e){u()(this,t);var n=d()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));O.call(n);var o=e.onChange!==r;"current"in e&&!o&&console.warn("Warning: You provided a `current` prop to a Pagination component without an `onChange` handler. This will render a read-only component.");var i=e.defaultCurrent;"current"in e&&(i=e.current);var a=e.defaultPageSize;return"pageSize"in e&&(a=e.pageSize),n.state={current:i,currentInputValue:i,pageSize:a},n}return v()(t,e),p()(t,[{key:"componentWillReceiveProps",value:function(e){if("current"in e&&this.setState({current:e.current,currentInputValue:e.current}),"pageSize"in e){var t={},n=this.state.current,r=this.calculatePage(e.pageSize);n=n>r?r:n,"current"in e||(t.current=n,t.currentInputValue=n),t.pageSize=e.pageSize,this.setState(t)}}},{key:"getJumpPrevPage",value:function(){return Math.max(1,this.state.current-(this.props.showLessItems?3:5))}},{key:"getJumpNextPage",value:function(){return Math.min(this.calculatePage(),this.state.current+(this.props.showLessItems?3:5))}},{key:"getJumpPrevPage",value:function(){return Math.max(1,this.state.current-(this.props.showLessItems?3:5))}},{key:"getJumpNextPage",value:function(){return Math.min(this.calculatePage(),this.state.current+(this.props.showLessItems?3:5))}},{key:"render",value:function(){if(!0===this.props.hideOnSinglePage&&this.props.total<=this.state.pageSize)return null;var e=this.props,t=e.locale,n=e.prefixCls,r=this.calculatePage(),o=[],i=null,a=null,s=null,l=null,u=null,c=e.showQuickJumper&&e.showQuickJumper.goButton,p=e.showLessItems?1:2,f=this.state,d=f.current,h=f.pageSize,v=d-1>0?d-1:0,m=d+1<r?d+1:r;if(e.simple)return c&&(u="boolean"==typeof c?y.a.createElement("button",{type:"button",onClick:this.handleGoTO,onKeyUp:this.handleGoTO},t.jump_to_confirm):y.a.createElement("span",{onClick:this.handleGoTO,onKeyUp:this.handleGoTO},c),u=y.a.createElement("li",{title:e.showTitle?""+t.jump_to+this.state.current+"/"+r:null,className:n+"-simple-pager"},u)),y.a.createElement("ul",{className:n+" "+n+"-simple "+e.className,style:e.style},y.a.createElement("li",{title:e.showTitle?t.prev_page:null,onClick:this.prev,tabIndex:this.hasPrev()?0:null,onKeyPress:this.runIfEnterPrev,className:(this.hasPrev()?"":n+"-disabled")+" "+n+"-prev","aria-disabled":!this.hasPrev()},e.itemRender(v,"prev",y.a.createElement("a",{className:n+"-item-link"}))),y.a.createElement("li",{title:e.showTitle?this.state.current+"/"+r:null,className:n+"-simple-pager"},y.a.createElement("input",{type:"text",value:this.state.currentInputValue,onKeyDown:this.handleKeyDown,onKeyUp:this.handleKeyUp,onChange:this.handleKeyUp,size:"3"}),y.a.createElement("span",{className:n+"-slash"},"\uff0f"),r),y.a.createElement("li",{title:e.showTitle?t.next_page:null,onClick:this.next,tabIndex:this.hasPrev()?0:null,onKeyPress:this.runIfEnterNext,className:(this.hasNext()?"":n+"-disabled")+" "+n+"-next","aria-disabled":!this.hasNext()},e.itemRender(m,"next",y.a.createElement("a",{className:n+"-item-link"}))),u);if(r<=5+2*p)for(var g=1;g<=r;g++){var b=this.state.current===g;o.push(y.a.createElement(w,{locale:t,rootPrefixCls:n,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:g,page:g,active:b,showTitle:e.showTitle,itemRender:e.itemRender}))}else{var C=e.showLessItems?t.prev_3:t.prev_5,S=e.showLessItems?t.next_3:t.next_5;e.showPrevNextJumpers&&(i=y.a.createElement("li",{title:e.showTitle?C:null,key:"prev",onClick:this.jumpPrev,tabIndex:"0",onKeyPress:this.runIfEnterJumpPrev,className:n+"-jump-prev"},e.itemRender(this.getJumpPrevPage(),"jump-prev",y.a.createElement("a",{className:n+"-item-link"}))),a=y.a.createElement("li",{title:e.showTitle?S:null,key:"next",tabIndex:"0",onClick:this.jumpNext,onKeyPress:this.runIfEnterJumpNext,className:n+"-jump-next"},e.itemRender(this.getJumpNextPage(),"jump-next",y.a.createElement("a",{className:n+"-item-link"})))),l=y.a.createElement(w,{locale:e.locale,last:!0,rootPrefixCls:n,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:r,page:r,active:!1,showTitle:e.showTitle,itemRender:e.itemRender}),s=y.a.createElement(w,{locale:e.locale,rootPrefixCls:n,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:1,page:1,active:!1,showTitle:e.showTitle,itemRender:e.itemRender});var x=Math.max(1,d-p),k=Math.min(d+p,r);d-1<=p&&(k=1+2*p),r-d<=p&&(x=r-2*p);for(var E=x;E<=k;E++){var O=d===E;o.push(y.a.createElement(w,{locale:e.locale,rootPrefixCls:n,onClick:this.handleChange,onKeyPress:this.runIfEnter,key:E,page:E,active:O,showTitle:e.showTitle,itemRender:e.itemRender}))}d-1>=2*p&&3!==d&&(o[0]=y.a.cloneElement(o[0],{className:n+"-item-after-jump-prev"}),o.unshift(i)),r-d>=2*p&&d!==r-2&&(o[o.length-1]=y.a.cloneElement(o[o.length-1],{className:n+"-item-before-jump-next"}),o.push(a)),1!==x&&o.unshift(s),k!==r&&o.push(l)}var T=null;e.showTotal&&(T=y.a.createElement("li",{className:n+"-total-text"},e.showTotal(e.total,[(d-1)*h+1,d*h>e.total?e.total:d*h])));var N=!this.hasPrev(),P=!this.hasNext();return y.a.createElement("ul",{className:n+" "+e.className,style:e.style,unselectable:"unselectable"},T,y.a.createElement("li",{title:e.showTitle?t.prev_page:null,onClick:this.prev,tabIndex:N?null:0,onKeyPress:this.runIfEnterPrev,className:(N?n+"-disabled":"")+" "+n+"-prev","aria-disabled":N},e.itemRender(v,"prev",y.a.createElement("a",{className:n+"-item-link"}))),o,y.a.createElement("li",{title:e.showTitle?t.next_page:null,onClick:this.next,tabIndex:P?null:0,onKeyPress:this.runIfEnterNext,className:(P?n+"-disabled":"")+" "+n+"-next","aria-disabled":P},e.itemRender(m,"next",y.a.createElement("a",{className:n+"-item-link"}))),y.a.createElement(_,{locale:e.locale,rootPrefixCls:n,selectComponentClass:e.selectComponentClass,selectPrefixCls:e.selectPrefixCls,changeSize:this.props.showSizeChanger?this.changePageSize:null,current:this.state.current,pageSize:this.state.pageSize,pageSizeOptions:this.props.pageSizeOptions,quickGo:this.props.showQuickJumper?this.handleChange:null,goButton:c}))}}]),t}(y.a.Component);E.propTypes={current:b.a.number,defaultCurrent:b.a.number,total:b.a.number,pageSize:b.a.number,defaultPageSize:b.a.number,onChange:b.a.func,hideOnSinglePage:b.a.bool,showSizeChanger:b.a.bool,showLessItems:b.a.bool,onShowSizeChange:b.a.func,selectComponentClass:b.a.func,showPrevNextJumpers:b.a.bool,showQuickJumper:b.a.oneOfType([b.a.bool,b.a.object]),showTitle:b.a.bool,pageSizeOptions:b.a.arrayOf(b.a.string),showTotal:b.a.func,locale:b.a.object,style:b.a.object,itemRender:b.a.func},E.defaultProps={defaultCurrent:1,total:0,defaultPageSize:10,onChange:r,className:"",selectPrefixCls:"rc-select",prefixCls:"rc-pagination",selectComponentClass:null,hideOnSinglePage:!1,showPrevNextJumpers:!0,showQuickJumper:!1,showSizeChanger:!1,showLessItems:!1,showTitle:!0,onShowSizeChange:r,locale:k.a,style:{},itemRender:i};var O=function(){var e=this;this.calculatePage=function(t){var n=t;return void 0===n&&(n=e.state.pageSize),Math.floor((e.props.total-1)/n)+1},this.isValid=function(t){return o(t)&&t>=1&&t!==e.state.current},this.handleKeyDown=function(e){e.keyCode!==S.ARROW_UP&&e.keyCode!==S.ARROW_DOWN||e.preventDefault()},this.handleKeyUp=function(t){var n=t.target.value,r=e.state.currentInputValue,o=void 0;o=""===n?n:isNaN(Number(n))?r:Number(n),o!==r&&e.setState({currentInputValue:o}),t.keyCode===S.ENTER?e.handleChange(o):t.keyCode===S.ARROW_UP?e.handleChange(o-1):t.keyCode===S.ARROW_DOWN&&e.handleChange(o+1)},this.changePageSize=function(t){var n=e.state.current,r=e.calculatePage(t);n=n>r?r:n,"number"==typeof t&&("pageSize"in e.props||e.setState({pageSize:t}),"current"in e.props||e.setState({current:n,currentInputValue:n})),e.props.onShowSizeChange(n,t)},this.handleChange=function(t){var n=t;if(e.isValid(n)){n>e.calculatePage()&&(n=e.calculatePage()),"current"in e.props||e.setState({current:n,currentInputValue:n});var r=e.state.pageSize;return e.props.onChange(n,r),n}return e.state.current},this.prev=function(){e.hasPrev()&&e.handleChange(e.state.current-1)},this.next=function(){e.hasNext()&&e.handleChange(e.state.current+1)},this.jumpPrev=function(){e.handleChange(e.getJumpPrevPage())},this.jumpNext=function(){e.handleChange(e.getJumpNextPage())},this.hasPrev=function(){return e.state.current>1},this.hasNext=function(){return e.state.current<e.calculatePage()},this.runIfEnter=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];"Enter"!==e.key&&13!==e.charCode||t.apply(void 0,r)},this.runIfEnterPrev=function(t){e.runIfEnter(t,e.prev)},this.runIfEnterNext=function(t){e.runIfEnter(t,e.next)},this.runIfEnterJumpPrev=function(t){e.runIfEnter(t,e.jumpPrev)},this.runIfEnterJumpNext=function(t){e.runIfEnter(t,e.jumpNext)},this.handleGoTO=function(t){t.keyCode!==S.ENTER&&"click"!==t.type||e.handleChange(e.state.currentInputValue)}},T=E,N=n(181),P=n(6),M=n.n(P),D=n(26),I=n(70),A=function(e){function t(){return u()(this,t),d()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return v()(t,e),p()(t,[{key:"render",value:function(){return m.createElement(I.a,s()({size:"small"},this.props))}}]),t}(m.Component),j=A;A.Option=I.a.Option;var R=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},L=function(e){function t(){u()(this,t);var e=d()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.renderPagination=function(t){var n=e.props,r=n.className,o=n.size,i=R(n,["className","size"]),a="small"===o;return m.createElement(T,s()({},i,{className:M()(r,{mini:a}),selectComponentClass:a?j:I.a,locale:t}))},e}return v()(t,e),p()(t,[{key:"render",value:function(){return m.createElement(D.a,{componentName:"Pagination",defaultLocale:N.a},this.renderPagination)}}]),t}(m.Component),K=L;L.defaultProps={prefixCls:"ant-pagination",selectPrefixCls:"ant-select"},n.d(t,!1,function(){});t.a=K},function(e,t,n){function r(e){var t=this.__data__=new o(e);this.size=t.size}var o=n(93),i=n(377),a=n(378),s=n(379),l=n(380),u=n(381);r.prototype.clear=i,r.prototype.delete=a,r.prototype.get=s,r.prototype.has=l,r.prototype.set=u,e.exports=r},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t){function n(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||r)}var r=Object.prototype;e.exports=n},function(e,t,n){(function(e){var r=n(33),o=n(391),i="object"==typeof t&&t&&!t.nodeType&&t,a=i&&"object"==typeof e&&e&&!e.nodeType&&e,s=a&&a.exports===i,l=s?r.Buffer:void 0,u=l?l.isBuffer:void 0,c=u||o;e.exports=c}).call(t,n(142)(e))},function(e,t,n){var r=n(393),o=n(394),i=n(395),a=i&&i.isTypedArray,s=a?o(a):r;e.exports=s},function(e,t){function n(e){return e}e.exports=n},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(77),s=n(25),l=n(54),u=n(28),c=n(98),p=n(45),f=n(11),d=n(65),h=n(39),v=n(148),m=f.List,y=f.Record,g=f.Repeat,b=p.draft_tree_data_support,C={entityMap:null,blockMap:null,selectionBefore:null,selectionAfter:null},w=b?u:l,S=y(C),x=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.getEntityMap=function(){return c},t.prototype.getBlockMap=function(){return this.get("blockMap")},t.prototype.getSelectionBefore=function(){return this.get("selectionBefore")},t.prototype.getSelectionAfter=function(){return this.get("selectionAfter")},t.prototype.getBlockForKey=function(e){return this.getBlockMap().get(e)},t.prototype.getKeyBefore=function(e){return this.getBlockMap().reverse().keySeq().skipUntil(function(t){return t===e}).skip(1).first()},t.prototype.getKeyAfter=function(e){return this.getBlockMap().keySeq().skipUntil(function(t){return t===e}).skip(1).first()},t.prototype.getBlockAfter=function(e){return this.getBlockMap().skipUntil(function(t,n){return n===e}).skip(1).first()},t.prototype.getBlockBefore=function(e){return this.getBlockMap().reverse().skipUntil(function(t,n){return n===e}).skip(1).first()},t.prototype.getBlocksAsArray=function(){return this.getBlockMap().toArray()},t.prototype.getFirstBlock=function(){return this.getBlockMap().first()},t.prototype.getLastBlock=function(){return this.getBlockMap().last()},t.prototype.getPlainText=function(e){return this.getBlockMap().map(function(e){return e?e.getText():""}).join(e||"\n")},t.prototype.getLastCreatedEntityKey=function(){return c.__getLastCreatedEntityKey()},t.prototype.hasText=function(){var e=this.getBlockMap();return e.size>1||e.first().getLength()>0},t.prototype.createEntity=function(e,t,n){return c.__create(e,t,n),this},t.prototype.mergeEntityData=function(e,t){return c.__mergeData(e,t),this},t.prototype.replaceEntityData=function(e,t){return c.__replaceData(e,t),this},t.prototype.addEntity=function(e){return c.__add(e),this},t.prototype.getEntity=function(e){return c.__get(e)},t.createFromBlockArray=function(e,n){var r=Array.isArray(e)?e:e.contentBlocks,o=a.createFromArray(r),i=o.isEmpty()?new d:d.createEmpty(o.first().getKey());return new t({blockMap:o,entityMap:n||c,selectionBefore:i,selectionAfter:i})},t.createFromText=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:/\r\n?|\n/g,r=e.split(n),o=r.map(function(e){return e=v(e),new w({key:h(),text:e,type:"unstyled",characterList:m(g(s.EMPTY,e.length))})});return t.createFromBlockArray(o)},t}(S);e.exports=x},function(e,t,n){"use strict";function r(e){return e.replace(o,"")}var o=new RegExp("\r","g");e.exports=r},function(e,t,n){"use strict";function r(e){return e===c||e===p}function o(e){return r(e)||u(!1),e===c?"ltr":"rtl"}function i(e,t){return r(e)||u(!1),r(t)||u(!1),e===t?null:o(e)}function a(e){f=e}function s(){a(c)}function l(){return f||this.initGlobalDir(),f||u(!1),f}var u=n(10),c="LTR",p="RTL",f=null,d={NEUTRAL:"NEUTRAL",LTR:c,RTL:p,isStrong:r,getHTMLDir:o,getHTMLDirIfDifferent:i,setGlobalDir:a,initGlobalDir:s,getGlobalDir:l};e.exports=d},function(e,t,n){"use strict";var r=n(11),o=r.Map,i=n(0),a=n(66),s=i.createElement("ul",{className:a("public/DraftStyleDefault/ul")}),l=i.createElement("ol",{className:a("public/DraftStyleDefault/ol")}),u=i.createElement("pre",{className:a("public/DraftStyleDefault/pre")}),c=o({"header-one":{element:"h1"},"header-two":{element:"h2"},"header-three":{element:"h3"},"header-four":{element:"h4"},"header-five":{element:"h5"},"header-six":{element:"h6"},"unordered-list-item":{element:"li",wrapper:s},"ordered-list-item":{element:"li",wrapper:l},blockquote:{element:"blockquote"},atomic:{element:"figure"},"code-block":{element:"pre",wrapper:u},unstyled:{element:"div",aliasedElements:["p"]}});e.exports=c},function(e,t,n){"use strict";e.exports={BACKSPACE:8,TAB:9,RETURN:13,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,COMMA:188,PERIOD:190,A:65,Z:90,ZERO:48,NUMPAD_0:96,NUMPAD_9:105}},function(e,t,n){"use strict";function r(e,t){var n;if(t.isCollapsed()){var r=t.getAnchorKey(),i=t.getAnchorOffset();return i>0?(n=e.getBlockForKey(r).getEntityAt(i-1),n!==e.getBlockForKey(r).getEntityAt(i)?null:o(e.getEntityMap(),n)):null}var a=t.getStartKey(),s=t.getStartOffset(),l=e.getBlockForKey(a);return n=s===l.getLength()?null:l.getEntityAt(s),o(e.getEntityMap(),n)}function o(e,t){if(t){return"MUTABLE"===e.__get(t).getMutability()?t:null}return null}e.exports=r},function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!o(e)&&(o(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var o=n(452);e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=i.get(e,t);return"auto"===n||"scroll"===n}var o=n(454),i={get:o,getScrollParent:function(e){if(!e)return null;for(var t=e.ownerDocument;e&&e!==t.body;){if(r(e,"overflow")||r(e,"overflowY")||r(e,"overflowX"))return e;e=e.parentNode}return t.defaultView||t.parentWindow}};e.exports=i},function(e,t,n){"use strict";function r(e){var t=o(e.ownerDocument||e.document);e.Window&&e instanceof e.Window&&(e=t);var n=i(e),r=e===t?e.ownerDocument.documentElement:e,a=e.scrollWidth-r.clientWidth,s=e.scrollHeight-r.clientHeight;return n.x=Math.max(0,Math.min(n.x,a)),n.y=Math.max(0,Math.min(n.y,s)),n}var o=n(459),i=n(460);e.exports=r},function(e,t,n){"use strict";function r(e){for(var t=e;t&&t!==document.documentElement;){var n=o(t);if(null!=n)return n;t=t.parentNode}return null}var o=n(221);e.exports=r},function(e,t,n){(function(e,t){!function(e,n){"use strict";function r(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var r={callback:e,args:t};return u[l]=r,s(l),l++}function o(e){delete u[e]}function i(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(n,r)}}function a(e){if(c)setTimeout(a,0,e);else{var t=u[e];if(t){c=!0;try{i(t)}finally{o(e),c=!1}}}}if(!e.setImmediate){var s,l=1,u={},c=!1,p=e.document,f=Object.getPrototypeOf&&Object.getPrototypeOf(e);f=f&&f.setTimeout?f:e,"[object process]"==={}.toString.call(e.process)?function(){s=function(e){t.nextTick(function(){a(e)})}}():function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?function(){var t="setImmediate$"+Math.random()+"$",n=function(n){n.source===e&&"string"==typeof n.data&&0===n.data.indexOf(t)&&a(+n.data.slice(t.length))};e.addEventListener?e.addEventListener("message",n,!1):e.attachEvent("onmessage",n),s=function(n){e.postMessage(t+n,"*")}}():e.MessageChannel?function(){var e=new MessageChannel;e.port1.onmessage=function(e){a(e.data)},s=function(t){e.port2.postMessage(t)}}():p&&"onreadystatechange"in p.createElement("script")?function(){var e=p.documentElement;s=function(t){var n=p.createElement("script");n.onreadystatechange=function(){a(t),n.onreadystatechange=null,e.removeChild(n),n=null},e.appendChild(n)}}():function(){s=function(e){setTimeout(a,0,e)}}(),f.setImmediate=r,f.clearImmediate=o}}("undefined"==typeof self?void 0===e?this:e:self)}).call(t,n(24),n(469))},function(e,t,n){"use strict";var r=n(38),o=r.isPlatform("Mac OS X"),i={isCtrlKeyCommand:function(e){return!!e.ctrlKey&&!e.altKey},isOptionKeyCommand:function(e){return o&&e.altKey},hasCommandModifier:function(e){return o?!!e.metaKey&&!e.altKey:i.isCtrlKeyCommand(e)}};e.exports=i},function(e,t,n){"use strict";function r(e,t){var n=e.getSelection(),r=e.getCurrentContent(),o=n.getStartKey(),i=n.getStartOffset(),a=o,s=0;if(t>i){var l=r.getKeyBefore(o);if(null==l)a=o;else{a=l;s=r.getBlockForKey(l).getText().length}}else s=i-t;return n.merge({focusKey:a,focusOffset:s,isBackward:!0})}e.exports=r},function(e,t,n){function r(e){return a(e)?o(e):i(e)}var o=n(207),i=n(528),a=n(76);e.exports=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(582));n.n(o)},function(e,t,n){"use strict";t.a={today:"Today",now:"Now",backToToday:"Back to today",ok:"Ok",clear:"Clear",month:"Month",year:"Year",timeSelect:"Select time",dateSelect:"Select date",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",yearFormat:"YYYY",dateFormat:"M/D/YYYY",dayFormat:"D",dateTimeFormat:"M/D/YYYY HH:mm:ss",monthBeforeYear:!0,previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(580));n.n(o),n(101)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(601));n.n(o)},function(e,t,n){e.exports={default:n(253),__esModule:!0}},function(e,t,n){e.exports=!n(49)&&!n(68)(function(){return 7!=Object.defineProperty(n(167)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(57),o=n(40).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(50),o=n(58),i=n(260)(!1),a=n(107)("IE_PROTO");e.exports=function(e,t){var n,s=o(e),l=0,u=[];for(n in s)n!=a&&r(s,n)&&u.push(n);for(;t.length>l;)r(s,n=t[l++])&&(~i(u,n)||u.push(n));return u}},function(e,t,n){var r=n(104);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){var r=n(106),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){"use strict";var r=n(112),o=n(47),i=n(172),a=n(56),s=n(50),l=n(59),u=n(265),c=n(114),p=n(268),f=n(30)("iterator"),d=!([].keys&&"next"in[].keys()),h=function(){return this};e.exports=function(e,t,n,v,m,y,g){u(n,t,v);var b,C,w,S=function(e){if(!d&&e in E)return E[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},x=t+" Iterator",_="values"==m,k=!1,E=e.prototype,O=E[f]||E["@@iterator"]||m&&E[m],T=!d&&O||S(m),N=m?_?S("entries"):T:void 0,P="Array"==t?E.entries||O:O;if(P&&(w=p(P.call(new e)))!==Object.prototype&&w.next&&(c(w,x,!0),r||s(w,f)||a(w,f,h)),_&&O&&"values"!==O.name&&(k=!0,T=function(){return O.call(this)}),r&&!g||!d&&!k&&E[f]||a(E,f,T),l[t]=T,l[x]=h,m)if(b={values:_?T:S("values"),keys:y?T:S("keys"),entries:N},g)for(C in b)C in E||i(E,C,b[C]);else o(o.P+o.F*(d||k),t,b);return b}},function(e,t,n){e.exports=n(56)},function(e,t,n){var r=n(168),o=n(109).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(84),o=n(69),i=n(58),a=n(103),s=n(50),l=n(166),u=Object.getOwnPropertyDescriptor;t.f=n(49)?u:function(e,t){if(e=i(e),t=a(t,!0),l)try{return u(e,t)}catch(e){}if(s(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(176),o=n(30)("iterator"),i=n(59);e.exports=n(29).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){var r=n(104),o=n(30)("toStringTag"),i="Arguments"==r(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,s;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),o))?n:i?r(t):"Object"==(s=r(t))&&"function"==typeof t.callee?"Arguments":s}},function(e,t,n){"use strict";function r(e){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;if(e.type&&e.type.isSelectOptGroup&&t.label)return t.label;throw new Error("Need at least a key or a value or a label (only for OptGroup) for "+e)}function o(e,t){return"value"===t?r(e):e.props[t]}function i(e){return e.multiple}function a(e){return e.combobox}function s(e){return e.multiple||e.tags}function l(e){return s(e)||a(e)}function u(e){return!l(e)}function c(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function p(e){e.preventDefault()}function f(e,t){for(var n=-1,r=0;r<e.length;r++)if(e[r].key===t){n=r;break}return n}function d(e,t){for(var n=-1,r=0;r<e.length;r++)if(c(e[r].label).join("")===t){n=r;break}return n}function h(e,t){if(null===t||void 0===t)return[];var n=[];return I.a.Children.forEach(e,function(e){if(e.type.isMenuItemGroup)n=n.concat(h(e.props.children,t));else{var o=r(e),i=e.key;-1!==f(t,o)&&i&&n.push(i)}}),n}function v(e){for(var t=0;t<e.length;t++){var n=e[t];if(n.type.isMenuItemGroup){var r=v(n.props.children);if(r)return r}else if(!n.props.disabled)return n}return null}function m(e,t){for(var n=0;n<t.length;++n)if(e.lastIndexOf(t[n])>0)return!0;return!1}function y(e,t){var n=new RegExp("["+t.join()+"]");return e.split(n).filter(function(e){return e})}function g(e,t){return!t.props.disabled&&c(o(t,this.props.optionFilterProp)).join("").toLowerCase().indexOf(e.toLowerCase())>-1}function b(e,t){if(!u(t)&&!i(t)&&"string"!=typeof e)throw new Error("Invalid `value` of type `"+typeof e+"` supplied to Option, expected `string` when `tags/combobox` is `true`.")}function C(e,t){return function(n){e[t]=n}}function w(e,t,n){var r=Y.a.oneOfType([Y.a.string,Y.a.number]),o=Y.a.shape({key:r.isRequired,label:Y.a.node});if(!e.labelInValue){if(("multiple"===e.mode||"tags"===e.mode||e.multiple||e.tags)&&""===e[t])return new Error("Invalid prop `"+t+"` of type `string` supplied to `"+n+"`, expected `array` when `multiple` or `tags` is `true`.");return Y.a.oneOfType([Y.a.arrayOf(r),r]).apply(void 0,arguments)}if(Y.a.oneOfType([Y.a.arrayOf(o),o]).apply(void 0,arguments))return new Error("Invalid prop `"+t+"` supplied to `"+n+"`, when you set `labelInValue` to `true`, `"+t+"` should in shape of `{ key: string | number, label?: ReactNode }`.")}function S(){}function x(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];for(var o=0;o<t.length;o++)t[o]&&"function"==typeof t[o]&&t[o].apply(this,n)}}var _=n(1),k=n.n(_),E=n(2),O=n.n(E),T=n(3),N=n.n(T),P=n(4),M=n.n(P),D=n(0),I=n.n(D),A=n(9),j=n.n(A),R=n(23),L=n(88),K=n(6),F=n.n(K),V=n(18),z=n(119),B=n.n(z),W=n(61),H=n(36),U=n.n(H),q=n(5),Y=n.n(q),G=function(e){function t(){return O()(this,t),N()(this,e.apply(this,arguments))}return M()(t,e),t}(I.a.Component);G.propTypes={value:Y.a.oneOfType([Y.a.string,Y.a.number])},G.isSelectOption=!0;var X=G,$={userSelect:"none",WebkitUserSelect:"none"},J={unselectable:"unselectable"},Z=n(17),Q=n.n(Z),ee=n(42),te=n(89),ne=n.n(te),re=function(e){function t(){var n,r,o;O()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=N()(this,e.call.apply(e,[this].concat(a))),r.scrollActiveItemToView=function(){var e=Object(A.findDOMNode)(r.firstActiveItem),t=r.props;if(e){var n={onlyScrollIfNeeded:!0};t.value&&0!==t.value.length||!t.firstActiveValue||(n.alignWithTop=!0),ne()(e,Object(A.findDOMNode)(r.menuRef),n)}},o=n,N()(r,o)}return M()(t,e),t.prototype.componentWillMount=function(){this.lastInputValue=this.props.inputValue},t.prototype.componentDidMount=function(){this.scrollActiveItemToView(),this.lastVisible=this.props.visible},t.prototype.shouldComponentUpdate=function(e){return e.visible||(this.lastVisible=!1),e.visible},t.prototype.componentDidUpdate=function(e){var t=this.props;!e.visible&&t.visible&&this.scrollActiveItemToView(),this.lastVisible=t.visible,this.lastInputValue=t.inputValue},t.prototype.renderMenu=function(){var e=this,t=this.props,n=t.menuItems,r=t.defaultActiveFirstOption,o=t.value,i=t.prefixCls,a=t.multiple,s=t.onMenuSelect,l=t.inputValue,u=t.firstActiveValue;if(n&&n.length){var c={};a?(c.onDeselect=t.onMenuDeselect,c.onSelect=s):c.onClick=s;var p=h(n,o),f={},d=n;if(p.length||u){t.visible&&!this.lastVisible&&(f.activeKey=p[0]||u);var v=!1,m=function(t){return!v&&-1!==p.indexOf(t.key)||!v&&!p.length&&-1!==u.indexOf(t.key)?(v=!0,Object(D.cloneElement)(t,{ref:function(t){e.firstActiveItem=t}})):t};d=n.map(function(e){if(e.type.isMenuItemGroup){var t=Object(L.a)(e.props.children).map(m);return Object(D.cloneElement)(e,{},t)}return m(e)})}var y=o&&o[o.length-1];return l===this.lastInputValue||y&&y.backfill||(f.activeKey=""),I.a.createElement(W.e,k()({ref:C(this,"menuRef"),style:this.props.dropdownMenuStyle,defaultActiveFirst:r},f,{multiple:a},c,{selectedKeys:p,prefixCls:i+"-menu"}),d)}return null},t.prototype.render=function(){var e=this.renderMenu();return e?I.a.createElement("div",{style:{overflow:"auto"},onFocus:this.props.onPopupFocus,onMouseDown:p,onScroll:this.props.onPopupScroll},e):null},t}(I.a.Component);re.propTypes={defaultActiveFirstOption:Y.a.bool,value:Y.a.any,dropdownMenuStyle:Y.a.object,multiple:Y.a.bool,onPopupFocus:Y.a.func,onPopupScroll:Y.a.func,onMenuDeSelect:Y.a.func,onMenuSelect:Y.a.func,prefixCls:Y.a.string,menuItems:Y.a.any,inputValue:Y.a.string,visible:Y.a.bool};var oe=re;re.displayName="DropdownMenu",ee.a.displayName="Trigger";var ie={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},ae=function(e){function t(){var n,r,o;O()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=N()(this,e.call.apply(e,[this].concat(a))),r.state={dropdownWidth:null},r.setDropdownWidth=function(){var e=j.a.findDOMNode(r).offsetWidth;e!==r.state.dropdownWidth&&r.setState({dropdownWidth:e})},r.getInnerMenu=function(){return r.dropdownMenuRef&&r.dropdownMenuRef.menuRef},r.getPopupDOMNode=function(){return r.triggerRef.getPopupDomNode()},r.getDropdownElement=function(e){var t=r.props;return I.a.createElement(oe,k()({ref:C(r,"dropdownMenuRef")},e,{prefixCls:r.getDropdownPrefixCls(),onMenuSelect:t.onMenuSelect,onMenuDeselect:t.onMenuDeselect,onPopupScroll:t.onPopupScroll,value:t.value,firstActiveValue:t.firstActiveValue,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle}))},r.getDropdownTransitionName=function(){var e=r.props,t=e.transitionName;return!t&&e.animation&&(t=r.getDropdownPrefixCls()+"-"+e.animation),t},r.getDropdownPrefixCls=function(){return r.props.prefixCls+"-dropdown"},o=n,N()(r,o)}return M()(t,e),t.prototype.componentDidMount=function(){this.setDropdownWidth()},t.prototype.componentDidUpdate=function(){this.setDropdownWidth()},t.prototype.render=function(){var e,t=this.props,n=t.onPopupFocus,r=Q()(t,["onPopupFocus"]),o=r.multiple,i=r.visible,a=r.inputValue,s=r.dropdownAlign,l=r.disabled,c=r.showSearch,p=r.dropdownClassName,f=r.dropdownStyle,d=r.dropdownMatchSelectWidth,h=this.getDropdownPrefixCls(),v=(e={},e[p]=!!p,e[h+"--"+(o?"multiple":"single")]=1,e),m=this.getDropdownElement({menuItems:r.options,onPopupFocus:n,multiple:o,inputValue:a,visible:i}),y=void 0;y=l?[]:u(r)&&!c?["click"]:["blur"];var g=k()({},f),b=d?"width":"minWidth";return this.state.dropdownWidth&&(g[b]=this.state.dropdownWidth+"px"),I.a.createElement(ee.a,k()({},r,{showAction:l?[]:this.props.showAction,hideAction:y,ref:C(this,"triggerRef"),popupPlacement:"bottomLeft",builtinPlacements:ie,prefixCls:h,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:r.onDropdownVisibleChange,popup:m,popupAlign:s,popupVisible:i,getPopupContainer:r.getPopupContainer,popupClassName:F()(v),popupStyle:g}),r.children)},t}(I.a.Component);ae.propTypes={onPopupFocus:Y.a.func,onPopupScroll:Y.a.func,dropdownMatchSelectWidth:Y.a.bool,dropdownAlign:Y.a.object,visible:Y.a.bool,disabled:Y.a.bool,showSearch:Y.a.bool,dropdownClassName:Y.a.string,multiple:Y.a.bool,inputValue:Y.a.string,filterOption:Y.a.any,options:Y.a.any,prefixCls:Y.a.string,popupClassName:Y.a.string,children:Y.a.any,showAction:Y.a.arrayOf(Y.a.string)};var se=ae;ae.displayName="SelectTrigger";var le={defaultActiveFirstOption:Y.a.bool,multiple:Y.a.bool,filterOption:Y.a.any,children:Y.a.any,showSearch:Y.a.bool,disabled:Y.a.bool,allowClear:Y.a.bool,showArrow:Y.a.bool,tags:Y.a.bool,prefixCls:Y.a.string,className:Y.a.string,transitionName:Y.a.string,optionLabelProp:Y.a.string,optionFilterProp:Y.a.string,animation:Y.a.string,choiceTransitionName:Y.a.string,onChange:Y.a.func,onBlur:Y.a.func,onFocus:Y.a.func,onSelect:Y.a.func,onSearch:Y.a.func,onPopupScroll:Y.a.func,onMouseEnter:Y.a.func,onMouseLeave:Y.a.func,onInputKeyDown:Y.a.func,placeholder:Y.a.any,onDeselect:Y.a.func,labelInValue:Y.a.bool,value:w,defaultValue:w,dropdownStyle:Y.a.object,maxTagTextLength:Y.a.number,maxTagCount:Y.a.number,maxTagPlaceholder:Y.a.oneOfType([Y.a.node,Y.a.func]),tokenSeparators:Y.a.arrayOf(Y.a.string),getInputElement:Y.a.func,showAction:Y.a.arrayOf(Y.a.string)},ue=function(e){function t(n){O()(this,t);var r=N()(this,e.call(this,n));ce.call(r);var o=[];o=c("value"in n?n.value:n.defaultValue),o=r.addLabelToValue(n,o),o=r.addTitleToValue(n,o);var i="";n.combobox&&(i=o.length?r.getLabelFromProps(n,o[0].key):"");var a=n.open;return void 0===a&&(a=n.defaultOpen),r._valueOptions=[],o.length>0&&(r._valueOptions=r.getOptionsByValue(o)),r.state={value:o,inputValue:i,open:a},r.adjustOpenState(),r}return M()(t,e),t.prototype.componentDidMount=function(){this.props.autoFocus&&this.focus()},t.prototype.componentWillUpdate=function(e,t){this.props=e,this.state=t,this.adjustOpenState()},t.prototype.componentDidUpdate=function(){if(s(this.props)){var e=this.getInputDOMNode(),t=this.getInputMirrorDOMNode();e.value?(e.style.width="",e.style.width=t.clientWidth+"px"):e.style.width=""}},t.prototype.componentWillUnmount=function(){this.clearFocusTime(),this.clearBlurTime(),this.clearAdjustTimer(),this.dropdownContainer&&(j.a.unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},t.prototype.focus=function(){u(this.props)?this.selectionRef.focus():this.getInputDOMNode().focus()},t.prototype.blur=function(){u(this.props)?this.selectionRef.blur():this.getInputDOMNode().blur()},t.prototype.renderClear=function(){var e=this.props,t=e.prefixCls,n=e.allowClear,r=this.state,o=r.value,i=r.inputValue,s=I.a.createElement("span",k()({key:"clear",onMouseDown:p,style:$},J,{className:t+"-selection__clear",onClick:this.onClearSelection}));return n?a(this.props)?i?s:null:i||o.length?s:null:null},t.prototype.render=function(){var e,t=this.props,n=s(t),r=this.state,o=t.className,i=t.disabled,u=t.prefixCls,c=this.renderTopControlNode(),p={},f=this.state.open,d=this._options;l(t)||(p={onKeyDown:this.onKeyDown,tabIndex:t.disabled?-1:0});var h=(e={},e[o]=!!o,e[u]=1,e[u+"-open"]=f,e[u+"-focused"]=f||!!this._focused,e[u+"-combobox"]=a(t),e[u+"-disabled"]=i,e[u+"-enabled"]=!i,e[u+"-allow-clear"]=!!t.allowClear,e);return I.a.createElement(se,{onPopupFocus:this.onPopupFocus,onMouseEnter:this.props.onMouseEnter,onMouseLeave:this.props.onMouseLeave,dropdownAlign:t.dropdownAlign,dropdownClassName:t.dropdownClassName,dropdownMatchSelectWidth:t.dropdownMatchSelectWidth,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle,transitionName:t.transitionName,animation:t.animation,prefixCls:t.prefixCls,dropdownStyle:t.dropdownStyle,combobox:t.combobox,showSearch:t.showSearch,options:d,multiple:n,disabled:i,visible:f,inputValue:r.inputValue,value:r.value,firstActiveValue:t.firstActiveValue,onDropdownVisibleChange:this.onDropdownVisibleChange,getPopupContainer:t.getPopupContainer,onMenuSelect:this.onMenuSelect,onMenuDeselect:this.onMenuDeselect,onPopupScroll:t.onPopupScroll,showAction:t.showAction,ref:C(this,"selectTriggerRef")},I.a.createElement("div",{style:t.style,ref:C(this,"rootRef"),onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:F()(h)},I.a.createElement("div",k()({ref:C(this,"selectionRef"),key:"selection",className:u+"-selection\n "+u+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":f},p),c,this.renderClear(),n||!t.showArrow?null:I.a.createElement("span",k()({key:"arrow",className:u+"-arrow",style:$},J,{onClick:this.onArrowClick}),I.a.createElement("b",null)))))},t}(I.a.Component);ue.propTypes=le,ue.defaultProps={prefixCls:"rc-select",defaultOpen:!1,labelInValue:!1,defaultActiveFirstOption:!0,showSearch:!0,allowClear:!1,placeholder:"",onChange:S,onFocus:S,onBlur:S,onSelect:S,onSearch:S,onDeselect:S,onInputKeyDown:S,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},dropdownMenuStyle:{},optionFilterProp:"value",optionLabelProp:"value",notFoundContent:"Not Found",backfill:!1,showAction:["click"],tokenSeparators:[]};var ce=function(){var e=this;this.componentWillReceiveProps=function(t){if("value"in t){var n=c(t.value);n=e.addLabelToValue(t,n),n=e.addTitleToValue(t,n),e.setState({value:n}),t.combobox&&e.setState({inputValue:n.length?e.getLabelFromProps(t,n[0].key):""})}},this.onInputChange=function(t){var n=e.props.tokenSeparators,r=t.target.value;if(s(e.props)&&n.length&&m(r,n)){var o=e.getValueByInput(r);return e.fireChange(o),e.setOpenState(!1,!0),void e.setInputValue("",!1)}e.setInputValue(r),e.setState({open:!0}),a(e.props)&&e.fireChange([{key:r}])},this.onDropdownVisibleChange=function(t){t&&!e._focused&&(e.clearBlurTime(),e.timeoutFocus(),e._focused=!0,e.updateFocusClassName()),e.setOpenState(t)},this.onKeyDown=function(t){if(!e.props.disabled){var n=t.keyCode;e.state.open&&!e.getInputDOMNode()?e.onInputKeyDown(t):n!==R.a.ENTER&&n!==R.a.DOWN||(e.setOpenState(!0),t.preventDefault())}},this.onInputKeyDown=function(t){var n=e.props;if(!n.disabled){var r=e.state,o=t.keyCode;if(s(n)&&!t.target.value&&o===R.a.BACKSPACE){t.preventDefault();var i=r.value;return void(i.length&&e.removeSelected(i[i.length-1].key))}if(o===R.a.DOWN){if(!r.open)return e.openIfHasChildren(),t.preventDefault(),void t.stopPropagation()}else if(o===R.a.ESC)return void(r.open&&(e.setOpenState(!1),t.preventDefault(),t.stopPropagation()));if(r.open){var a=e.selectTriggerRef.getInnerMenu();a&&a.onKeyDown(t,e.handleBackfill)&&(t.preventDefault(),t.stopPropagation())}}},this.onMenuSelect=function(t){var n=t.item,i=e.state.value,l=e.props,u=r(n),c=e.getLabelFromOption(n),p=i[i.length-1];e.fireSelect({key:u,label:c});var d=n.props.title;if(s(l)){if(-1!==f(i,u))return;i=i.concat([{key:u,label:c,title:d}])}else{if(a(l)&&(e.skipAdjustOpen=!0,e.clearAdjustTimer(),e.skipAdjustOpenTimer=setTimeout(function(){e.skipAdjustOpen=!1},0)),p&&p.key===u&&!p.backfill)return void e.setOpenState(!1,!0);i=[{key:u,label:c,title:d}],e.setOpenState(!1,!0)}e.fireChange(i);var h=void 0;h=a(l)?o(n,l.optionLabelProp):"",e.setInputValue(h,!1)},this.onMenuDeselect=function(t){var n=t.item;"click"===t.domEvent.type&&e.removeSelected(r(n)),e.setInputValue("",!1)},this.onArrowClick=function(t){t.stopPropagation(),t.preventDefault(),e.props.disabled||e.setOpenState(!e.state.open,!e.state.open)},this.onPlaceholderClick=function(){e.getInputDOMNode()&&e.getInputDOMNode().focus()},this.onOuterFocus=function(t){if(e.props.disabled)return void t.preventDefault();e.clearBlurTime(),(l(e.props)||t.target!==e.getInputDOMNode())&&(e._focused||(e._focused=!0,e.updateFocusClassName(),e.timeoutFocus()))},this.onPopupFocus=function(){e.maybeFocus(!0,!0)},this.onOuterBlur=function(t){if(e.props.disabled)return void t.preventDefault();e.blurTimer=setTimeout(function(){e._focused=!1,e.updateFocusClassName();var t=e.props,n=e.state.value,r=e.state.inputValue;if(u(t)&&t.showSearch&&r&&t.defaultActiveFirstOption){var o=e._options||[];if(o.length){var i=v(o);i&&(n=[{key:i.key,label:e.getLabelFromOption(i)}],e.fireChange(n))}}else s(t)&&r&&(e.state.inputValue=e.getInputDOMNode().value="",n=e.getValueByInput(r),e.fireChange(n));t.onBlur(e.getVLForOnChange(n)),e.setOpenState(!1)},10)},this.onClearSelection=function(t){var n=e.props,r=e.state;if(!n.disabled){var o=r.inputValue,i=r.value;t.stopPropagation(),(o||i.length)&&(i.length&&e.fireChange([]),e.setOpenState(!1,!0),o&&e.setInputValue(""))}},this.onChoiceAnimationLeave=function(){e.selectTriggerRef.triggerRef.forcePopupAlign()},this.getOptionsFromChildren=function(t,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=t;return Array.isArray(t)||(i=[t]),I.a.Children.forEach(n,function(t){if(t)if(t.type.isSelectOptGroup)e.getOptionsFromChildren(t.props.children,o);else{var n=f(i,r(t));-1!==n&&(o[n]=t)}}),i.forEach(function(t,n){if(!o[n]){for(var i=0;i<e._valueOptions.length;i++){var a=e._valueOptions[i];if(r(a)===t.key){o[n]=a;break}}o[n]||(o[n]=I.a.createElement(X,{value:t.key,key:t.key},t.label))}}),Array.isArray(t)?o:o[0]},this.getSingleOptionByValueKey=function(t){return e.getOptionsFromChildren({key:t,label:t},e.props.children)},this.getOptionsByValue=function(t){if(void 0!==t)return 0===t.length?[]:e.getOptionsFromChildren(t,e.props.children)},this.getLabelBySingleValue=function(t,n){if(void 0===n)return null;var o=null;return I.a.Children.forEach(t,function(t){if(t)if(t.type.isSelectOptGroup){var i=e.getLabelBySingleValue(t.props.children,n);null!==i&&(o=i)}else r(t)===n&&(o=e.getLabelFromOption(t))}),o},this.getValueByLabel=function(t,n){if(void 0===n)return null;var o=null;return I.a.Children.forEach(t,function(t){if(t)if(t.type.isSelectOptGroup){var i=e.getValueByLabel(t.props.children,n);null!==i&&(o=i)}else c(e.getLabelFromOption(t)).join("")===n&&(o=r(t))}),o},this.getLabelFromOption=function(t){return o(t,e.props.optionLabelProp)},this.getLabelFromProps=function(t,n){return e.getLabelByValue(t.children,n)},this.getVLForOnChange=function(t){var n=t;return void 0!==n?(n=e.props.labelInValue?n.map(function(e){return{key:e.key,label:e.label}}):n.map(function(e){return e.key}),s(e.props)?n:n[0]):n},this.getLabelByValue=function(t,n){var r=e.getLabelBySingleValue(t,n);return null===r?n:r},this.getDropdownContainer=function(){return e.dropdownContainer||(e.dropdownContainer=document.createElement("div"),document.body.appendChild(e.dropdownContainer)),e.dropdownContainer},this.getPlaceholderElement=function(){var t=e.props,n=e.state,r=!1;n.inputValue&&(r=!0),n.value.length&&(r=!0),a(t)&&1===n.value.length&&!n.value[0].key&&(r=!1);var o=t.placeholder;return o?I.a.createElement("div",k()({onMouseDown:p,style:k()({display:r?"none":"block"},$)},J,{onClick:e.onPlaceholderClick,className:t.prefixCls+"-selection__placeholder"}),o):null},this.getInputElement=function(){var t,n=e.props,r=n.getInputElement?n.getInputElement():I.a.createElement("input",{id:n.id,autoComplete:"off"}),o=F()(r.props.className,(t={},t[n.prefixCls+"-search__field"]=!0,t));return I.a.createElement("div",{className:n.prefixCls+"-search__field__wrap"},I.a.cloneElement(r,{ref:C(e,"inputRef"),onChange:e.onInputChange,onKeyDown:x(e.onInputKeyDown,r.props.onKeyDown,e.props.onInputKeyDown),value:e.state.inputValue,disabled:n.disabled,className:o}),I.a.createElement("span",{ref:C(e,"inputMirrorRef"),className:n.prefixCls+"-search__field__mirror"},e.state.inputValue,"\xa0"))},this.getInputDOMNode=function(){return e.topCtrlRef?e.topCtrlRef.querySelector("input,textarea,div[contentEditable]"):e.inputRef},this.getInputMirrorDOMNode=function(){return e.inputMirrorRef},this.getPopupDOMNode=function(){return e.selectTriggerRef.getPopupDOMNode()},this.getPopupMenuComponent=function(){return e.selectTriggerRef.getInnerMenu()},this.setOpenState=function(t,n){var r=e.props;if(e.state.open===t)return void e.maybeFocus(t,n);var o={open:t};!t&&u(r)&&r.showSearch&&e.setInputValue(""),t||e.maybeFocus(t,n),e.setState(o,function(){t&&e.maybeFocus(t,n)})},this.setInputValue=function(t){var n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];t!==e.state.inputValue&&(e.setState({inputValue:t}),n&&e.props.onSearch(t))},this.getValueByInput=function(t){var n=e.props,r=n.multiple,o=n.tokenSeparators,i=n.children,a=e.state.value;return y(t,o).forEach(function(t){var n={key:t,label:t};if(-1===d(a,t))if(r){var o=e.getValueByLabel(i,t);o&&(n.key=o,a=a.concat(n))}else a=a.concat(n);e.fireSelect({key:t,label:t})}),a},this.handleBackfill=function(t){if(e.props.backfill&&(u(e.props)||a(e.props))){var n=r(t),o=e.getLabelFromOption(t),i={key:n,label:o,backfill:!0};a(e.props)&&e.setInputValue(n,!1),e.setState({value:[i]})}},this.filterOption=function(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:g,o=e.state.value,i=o[o.length-1];if(!t||i&&i.backfill)return!0;var a=e.props.filterOption;return"filterOption"in e.props?!0===e.props.filterOption&&(a=r):a=r,!a||("function"==typeof a?a.call(e,t,n):!n.props.disabled)},this.timeoutFocus=function(){e.focusTimer&&e.clearFocusTime(),e.focusTimer=setTimeout(function(){e.props.onFocus()},10)},this.clearFocusTime=function(){e.focusTimer&&(clearTimeout(e.focusTimer),e.focusTimer=null)},this.clearBlurTime=function(){e.blurTimer&&(clearTimeout(e.blurTimer),e.blurTimer=null)},this.clearAdjustTimer=function(){e.skipAdjustOpenTimer&&(clearTimeout(e.skipAdjustOpenTimer),e.skipAdjustOpenTimer=null)},this.updateFocusClassName=function(){var t=e.rootRef,n=e.props;e._focused?B()(t).add(n.prefixCls+"-focused"):B()(t).remove(n.prefixCls+"-focused")},this.maybeFocus=function(t,n){if(n||t){var r=e.getInputDOMNode(),o=document,i=o.activeElement;r&&(t||l(e.props))?i!==r&&(r.focus(),e._focused=!0):i!==e.selectionRef&&(e.selectionRef.focus(),e._focused=!0)}},this.addLabelToValue=function(t,n){var r=n;return t.labelInValue?r.forEach(function(n){n.label=n.label||e.getLabelFromProps(t,n.key)}):r=r.map(function(n){return{key:n,label:e.getLabelFromProps(t,n)}}),r},this.addTitleToValue=function(t,n){var o=n,i=n.map(function(e){return e.key});return I.a.Children.forEach(t.children,function(t){if(t)if(t.type.isSelectOptGroup)o=e.addTitleToValue(t.props,o);else{var n=r(t),a=i.indexOf(n);a>-1&&(o[a].title=t.props.title)}}),o},this.removeSelected=function(t){var n=e.props;if(!n.disabled&&!e.isChildDisabled(t)){var r=void 0,o=e.state.value.filter(function(e){return e.key===t&&(r=e.label),e.key!==t});if(s(n)){var i=t;n.labelInValue&&(i={key:t,label:r}),n.onDeselect(i,e.getSingleOptionByValueKey(t))}e.fireChange(o)}},this.openIfHasChildren=function(){var t=e.props;(I.a.Children.count(t.children)||u(t))&&e.setOpenState(!0)},this.fireSelect=function(t){var n=e.props,r=n.labelInValue;(0,n.onSelect)(r?t:t.key,e.getSingleOptionByValueKey(t.key))},this.fireChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=e.getVLForOnChange(t),o=e.getOptionsByValue(t);e._valueOptions=o,n.onChange(r,s(e.props)?o:o[0])},this.isChildDisabled=function(t){return Object(L.a)(e.props.children).some(function(e){return r(e)===t&&e.props&&e.props.disabled})},this.adjustOpenState=function(){if(!e.skipAdjustOpen){var t=e.state.open,n=[];(t||e.hiddenForNoOptions)&&(n=e.renderFilterOptions()),e._options=n,!l(e.props)&&e.props.showSearch||(t&&!n.length&&(t=!1,e.hiddenForNoOptions=!0),e.hiddenForNoOptions&&n.length&&(t=!0,e.hiddenForNoOptions=!1)),e.state.open=t}},this.renderFilterOptions=function(){var t=e.state.inputValue,n=e.props,o=n.children,i=n.tags,a=n.filterOption,s=n.notFoundContent,l=[],u=[],c=e.renderFilterOptionsFromChildren(o,u,l);if(i){var p=e.state.value||[];if(p=p.filter(function(e){return-1===u.indexOf(e.key)&&(!t||String(e.key).indexOf(String(t))>-1)}),p.forEach(function(e){var t=e.key,n=I.a.createElement(W.b,{style:$,attribute:J,value:t,key:t},t);c.push(n),l.push(n)}),t){l.every(function(n){var o=function(){return r(n)===t};return!1!==a?!e.filterOption.call(e,t,n,o):!o()})&&c.unshift(I.a.createElement(W.b,{style:$,attribute:J,value:t,key:t},t))}}return!c.length&&s&&(c=[I.a.createElement(W.b,{style:$,attribute:J,disabled:!0,value:"NOT_FOUND",key:"NOT_FOUND"},s)]),c},this.renderFilterOptionsFromChildren=function(t,n,o){var i=[],a=e.props,s=e.state.inputValue,l=a.tags;return I.a.Children.forEach(t,function(t){if(t)if(t.type.isSelectOptGroup){var a=e.renderFilterOptionsFromChildren(t.props.children,n,o);if(a.length){var u=t.props.label,c=t.key;c||"string"!=typeof u?!u&&c&&(u=c):c=u,i.push(I.a.createElement(W.c,{key:c,title:u},a))}}else{U()(t.type.isSelectOption,"the children of `Select` should be `Select.Option` or `Select.OptGroup`, instead of `"+(t.type.name||t.type.displayName||t.type)+"`.");var p=r(t);if(b(p,e.props),e.filterOption(s,t)){var f=I.a.createElement(W.b,k()({style:$,attribute:J,value:p,key:p},t.props));i.push(f),o.push(f)}l&&!t.props.disabled&&n.push(p)}}),i},this.renderTopControlNode=function(){var t=e.state,n=t.value,r=t.open,o=t.inputValue,i=e.props,a=i.choiceTransitionName,l=i.prefixCls,c=i.maxTagTextLength,f=i.maxTagCount,d=i.maxTagPlaceholder,h=i.showSearch,v=l+"-selection__rendered",m=null;if(u(i)){var y=null;if(n.length){var g=!1,b=1;h&&r?(g=!o)&&(b=.4):g=!0;var w=n[0];y=I.a.createElement("div",{key:"value",className:l+"-selection-selected-value",title:w.title||w.label,style:{display:g?"block":"none",opacity:b}},n[0].label)}m=h?[y,I.a.createElement("div",{className:l+"-search "+l+"-search--inline",key:"input",style:{display:r?"block":"none"}},e.getInputElement())]:[y]}else{var S=[],x=n,_=void 0;if(void 0!==f&&n.length>f){x=x.slice(0,f);var E=e.getVLForOnChange(n.slice(f,n.length)),O="+ "+(n.length-f)+" ...";d&&(O="function"==typeof d?d(E):d),_=I.a.createElement("li",k()({style:$},J,{onMouseDown:p,className:l+"-selection__choice "+l+"-selection__choice__disabled",key:"maxTagPlaceholder",title:O}),I.a.createElement("div",{className:l+"-selection__choice__content"},O))}s(i)&&(S=x.map(function(t){var n=t.label,r=t.title||n;c&&"string"==typeof n&&n.length>c&&(n=n.slice(0,c)+"...");var o=e.isChildDisabled(t.key),i=o?l+"-selection__choice "+l+"-selection__choice__disabled":l+"-selection__choice";return I.a.createElement("li",k()({style:$},J,{onMouseDown:p,className:i,key:t.key,title:r}),I.a.createElement("div",{className:l+"-selection__choice__content"},n),o?null:I.a.createElement("span",{className:l+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.key)}))})),_&&S.push(_),S.push(I.a.createElement("li",{className:l+"-search "+l+"-search--inline",key:"__input"},e.getInputElement())),m=s(i)&&a?I.a.createElement(V.a,{onLeave:e.onChoiceAnimationLeave,component:"ul",transitionName:a},S):I.a.createElement("ul",null,S)}return I.a.createElement("div",{className:v,ref:C(e,"topCtrlRef")},e.getPlaceholderElement(),m)}},pe=ue;ue.displayName="Select";var fe=function(e){function t(){return O()(this,t),N()(this,e.apply(this,arguments))}return M()(t,e),t}(I.a.Component);fe.isSelectOptGroup=!0;var de=fe;n.d(t,"b",function(){return X}),n.d(t,"a",function(){return de}),n.d(t,!1,function(){return le}),pe.Option=X,pe.OptGroup=de;t.c=pe},function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){"use strict";var r=n(2),o=n.n(r),i=n(7),a=n.n(i),s=n(3),l=n.n(s),u=n(4),c=n.n(u),p=n(0),f=n.n(p),d=n(9),h=n.n(d),v=n(5),m=n.n(v),y=function(e){function t(){var e,n,r,i;o()(this,t);for(var a=arguments.length,s=Array(a),u=0;u<a;u++)s[u]=arguments[u];return n=r=l()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),r.removeContainer=function(){r.container&&(h.a.unmountComponentAtNode(r.container),r.container.parentNode.removeChild(r.container),r.container=null)},r.renderComponent=function(e,t){var n=r.props,o=n.visible,i=n.getComponent,a=n.forceRender,s=n.getContainer,l=n.parent;(o||l._component||a)&&(r.container||(r.container=s()),h.a.unstable_renderSubtreeIntoContainer(l,i(e),r.container,function(){t&&t.call(this)}))},i=n,l()(r,i)}return c()(t,e),a()(t,[{key:"componentDidMount",value:function(){this.props.autoMount&&this.renderComponent()}},{key:"componentDidUpdate",value:function(){this.props.autoMount&&this.renderComponent()}},{key:"componentWillUnmount",value:function(){this.props.autoDestroy&&this.removeContainer()}},{key:"render",value:function(){return this.props.children({renderComponent:this.renderComponent,removeContainer:this.removeContainer})}}]),t}(f.a.Component);y.propTypes={autoMount:m.a.bool,autoDestroy:m.a.bool,visible:m.a.bool,forceRender:m.a.bool,parent:m.a.any,getComponent:m.a.func.isRequired,getContainer:m.a.func.isRequired,children:m.a.func.isRequired},y.defaultProps={autoMount:!0,autoDestroy:!0,forceRender:!1},t.a=y},function(e,t,n){"use strict";var r=n(2),o=n.n(r),i=n(7),a=n.n(i),s=n(3),l=n.n(s),u=n(4),c=n.n(u),p=n(0),f=n.n(p),d=n(9),h=n.n(d),v=n(5),m=n.n(v),y=function(e){function t(){return o()(this,t),l()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return c()(t,e),a()(t,[{key:"componentDidMount",value:function(){this.createContainer()}},{key:"componentDidUpdate",value:function(e){var t=this.props.didUpdate;t&&t(e)}},{key:"componentWillUnmount",value:function(){this.removeContainer()}},{key:"createContainer",value:function(){this._container=this.props.getContainer(),this.forceUpdate()}},{key:"removeContainer",value:function(){this._container&&this._container.parentNode.removeChild(this._container)}},{key:"render",value:function(){return this._container?h.a.createPortal(this.props.children,this._container):null}}]),t}(f.a.Component);y.propTypes={getContainer:m.a.func.isRequired,children:m.a.node.isRequired,didUpdate:m.a.func},t.a=y},function(e,t,n){"use strict";t.a={items_per_page:"/ page",jump_to:"Goto",jump_to_confirm:"confirm",page:"",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages"}},function(e,t,n){"use strict";var r=n(121);t.a=r.a},function(e,t,n){"use strict";var r=n(1),o=n.n(r),i=n(17),a=n.n(i),s=n(2),l=n.n(s),u=n(3),c=n.n(u),p=n(4),f=n.n(p),d=n(0),h=n.n(d),v=n(5),m=n.n(v),y=n(71),g=n.n(y),b=n(6),C=n.n(b),w=function(e){function t(n){l()(this,t);var r=c()(this,e.call(this,n));S.call(r);var o="checked"in n?n.checked:n.defaultChecked;return r.state={checked:o},r}return f()(t,e),t.prototype.componentWillReceiveProps=function(e){"checked"in e&&this.setState({checked:e.checked})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return g.a.shouldComponentUpdate.apply(this,t)},t.prototype.focus=function(){this.input.focus()},t.prototype.blur=function(){this.input.blur()},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,i=t.style,s=t.name,l=t.id,u=t.type,c=t.disabled,p=t.readOnly,f=t.tabIndex,d=t.onClick,v=t.onFocus,m=t.onBlur,y=t.autoFocus,g=t.value,b=a()(t,["prefixCls","className","style","name","id","type","disabled","readOnly","tabIndex","onClick","onFocus","onBlur","autoFocus","value"]),w=Object.keys(b).reduce(function(e,t){return"aria-"!==t.substr(0,5)&&"data-"!==t.substr(0,5)&&"role"!==t||(e[t]=b[t]),e},{}),S=this.state.checked,x=C()(n,r,(e={},e[n+"-checked"]=S,e[n+"-disabled"]=c,e));return h.a.createElement("span",{className:x,style:i},h.a.createElement("input",o()({name:s,id:l,type:u,readOnly:p,disabled:c,tabIndex:f,className:n+"-input",checked:!!S,onClick:d,onFocus:v,onBlur:m,onChange:this.handleChange,autoFocus:y,ref:this.saveInput,value:g},w)),h.a.createElement("span",{className:n+"-inner"}))},t}(h.a.Component);w.propTypes={prefixCls:m.a.string,className:m.a.string,style:m.a.object,name:m.a.string,id:m.a.string,type:m.a.string,defaultChecked:m.a.oneOfType([m.a.number,m.a.bool]),checked:m.a.oneOfType([m.a.number,m.a.bool]),disabled:m.a.bool,onFocus:m.a.func,onBlur:m.a.func,onChange:m.a.func,onClick:m.a.func,tabIndex:m.a.string,readOnly:m.a.bool,autoFocus:m.a.bool,value:m.a.any},w.defaultProps={prefixCls:"rc-checkbox",className:"",style:{},type:"checkbox",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}};var S=function(){var e=this;this.handleChange=function(t){var n=e.props;n.disabled||("checked"in n||e.setState({checked:t.target.checked}),n.onChange({target:o()({},n,{checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()},nativeEvent:t.nativeEvent}))},this.saveInput=function(t){e.input=t}},x=w;t.a=x},function(e,t,n){(function(t){var n="object"==typeof t&&t&&t.Object===Object&&t;e.exports=n}).call(t,n(24))},function(e,t,n){"use strict";t.__esModule=!0;var r=n(0),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i={className:"",accessibility:!0,adaptiveHeight:!1,arrows:!0,autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e){return o.default.createElement("button",null,e+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:!1,pauseOnHover:!0,responsive:null,rtl:!1,slide:"div",slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,variableWidth:!1,vertical:!1,waitForAnimate:!0,afterChange:null,beforeChange:null,edgeEvent:null,init:null,swipeEvent:null,nextArrow:null,prevArrow:null,appendDots:function(e){return o.default.createElement("ul",{style:{display:"block"}},e)}};t.default=i},function(e,t,n){var r=n(334);e.exports=new r},function(e,t){function n(e,t){var n=0,r=e.length;for(n;n<r&&!1!==t(e[n],n);n++);}function r(e){return"[object Array]"===Object.prototype.toString.apply(e)}function o(e){return"function"==typeof e}e.exports={isFunction:o,isArray:r,each:n}},function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r,o=e||[],i=[],a=0;do{var r=o.filter(function(e){return t(e,a)})[0];if(!r)break;i.push(r),o=r[n.childrenKeyName]||[],a+=1}while(o.length>0);return i}e.exports=n},function(e,t,n){function r(e,t){return null!=e&&i(e,t,o)}var o=n(339),i=n(190);e.exports=r},function(e,t,n){function r(e,t,n){t=o(t,e);for(var r=-1,c=t.length,p=!1;++r<c;){var f=u(t[r]);if(!(p=null!=e&&n(e,f)))break;e=e[f]}return p||++r!=c?p:!!(c=null==e?0:e.length)&&l(c)&&s(f,c)&&(a(e)||i(e))}var o=n(130),i=n(135),a=n(37),s=n(96),l=n(136),u=n(75);e.exports=r},function(e,t){function n(e){if(null!=e){try{return o.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var r=Function.prototype,o=r.toString;e.exports=n},function(e,t){function n(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=n},function(e,t,n){function r(e,t){t=o(t,e);for(var n=0,r=t.length;null!=e&&n<r;)e=e[i(t[n++])];return n&&n==r?e:void 0}var o=n(130),i=n(75);e.exports=r},function(e,t,n){function r(e,t,n){return null==e?e:o(e,t,n)}var o=n(367);e.exports=r},function(e,t,n){function r(e,t,n){var r=e[t];s.call(e,t)&&i(r,n)&&(void 0!==n||t in e)||o(e,t,n)}var o=n(138),i=n(74),a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){var r=n(53),o=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=o},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){"use strict";var e={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},t={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},n=Object.defineProperty,r=Object.getOwnPropertyNames,o=Object.getOwnPropertySymbols,i=Object.getOwnPropertyDescriptor,a=Object.getPrototypeOf,s=a&&a(Object);return function l(u,c,p){if("string"!=typeof c){if(s){var f=a(c);f&&f!==s&&l(u,f,p)}var d=r(c);o&&(d=d.concat(o(c)));for(var h=0;h<d.length;++h){var v=d[h];if(!(e[v]||t[v]||p&&p[v])){var m=i(c,v);try{n(u,v,m)}catch(e){}}}return u}return u}})},function(e,t,n){"use strict";var r=n(8),o=n.n(r),i=n(1),a=n.n(i),s=n(2),l=n.n(s),u=n(7),c=n.n(u),p=n(3),f=n.n(p),d=n(4),h=n.n(d),v=n(0),m=n(9),y=n(61),g=n(5),b=n.n(g),C=n(6),w=n.n(C),S=n(125),x=n(27),_=function(e){function t(){l()(this,t);var e=f()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onKeyDown=function(t){e.subMenu.onKeyDown(t)},e.saveSubMenu=function(t){e.subMenu=t},e}return h()(t,e),c()(t,[{key:"render",value:function(){var e=this.props,t=e.rootPrefixCls,n=e.className,r=this.context.antdMenuTheme;return v.createElement(y.d,a()({},this.props,{ref:this.saveSubMenu,popupClassName:w()(t+"-"+r,n)}))}}]),t}(v.Component);_.contextTypes={antdMenuTheme:b.a.string};var k=_,E=n(63),O=function(e){function t(){l()(this,t);var e=f()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onKeyDown=function(t){e.menuItem.onKeyDown(t)},e.saveMenuItem=function(t){e.menuItem=t},e}return h()(t,e),c()(t,[{key:"render",value:function(){var e=this.context.inlineCollapsed,t=this.props,n=v.createElement(y.b,a()({},t,{ref:this.saveMenuItem}));return e&&1===t.level?v.createElement(E.a,{title:t.children,placement:"right",overlayClassName:t.rootPrefixCls+"-inline-collapsed-tooltip"},n):n}}]),t}(v.Component);O.contextTypes={inlineCollapsed:b.a.bool},O.isMenuItem=1;var T=O,N=function(e){function t(e){l()(this,t);var n=f()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.inlineOpenKeys=[],n.handleClick=function(e){n.handleOpenChange([]);var t=n.props.onClick;t&&t(e)},n.handleOpenChange=function(e){n.setOpenKeys(e);var t=n.props.onOpenChange;t&&t(e)},Object(x.a)(!("onOpen"in e||"onClose"in e),"`onOpen` and `onClose` are removed, please use `onOpenChange` instead, see: https://u.ant.design/menu-on-open-change."),Object(x.a)(!("inlineCollapsed"in e&&"inline"!==e.mode),"`inlineCollapsed` should only be used when Menu's `mode` is inline.");var r=void 0;return"defaultOpenKeys"in e?r=e.defaultOpenKeys:"openKeys"in e&&(r=e.openKeys),n.state={openKeys:r||[]},n}return h()(t,e),c()(t,[{key:"getChildContext",value:function(){return{inlineCollapsed:this.getInlineCollapsed(),antdMenuTheme:this.props.theme}}},{key:"componentWillReceiveProps",value:function(e,t){var n=this.props.prefixCls;if("inline"===this.props.mode&&"inline"!==e.mode&&(this.switchModeFromInline=!0),"openKeys"in e)return void this.setState({openKeys:e.openKeys});(e.inlineCollapsed&&!this.props.inlineCollapsed||t.siderCollapsed&&!this.context.siderCollapsed)&&(this.switchModeFromInline=!!this.state.openKeys.length&&!!Object(m.findDOMNode)(this).querySelectorAll("."+n+"-submenu-open").length,this.inlineOpenKeys=this.state.openKeys,this.setState({openKeys:[]})),(!e.inlineCollapsed&&this.props.inlineCollapsed||!t.siderCollapsed&&this.context.siderCollapsed)&&(this.setState({openKeys:this.inlineOpenKeys}),this.inlineOpenKeys=[])}},{key:"setOpenKeys",value:function(e){"openKeys"in this.props||this.setState({openKeys:e})}},{key:"getRealMenuMode",value:function(){var e=this.getInlineCollapsed();if(this.switchModeFromInline&&e)return"inline";var t=this.props.mode;return e?"vertical":t}},{key:"getInlineCollapsed",value:function(){var e=this.props.inlineCollapsed;return void 0!==this.context.siderCollapsed?this.context.siderCollapsed:e}},{key:"getMenuOpenAnimation",value:function(e){var t=this,n=this.props,r=n.openAnimation,o=n.openTransitionName,i=r||o;if(void 0===r&&void 0===o)switch(e){case"horizontal":i="slide-up";break;case"vertical":case"vertical-left":case"vertical-right":this.switchModeFromInline?(i="",this.switchModeFromInline=!1):i="zoom-big";break;case"inline":i=a()({},S.a,{leave:function(e,n){return S.a.leave(e,function(){t.switchModeFromInline=!1,t.setState({}),"vertical"!==t.getRealMenuMode()&&n()})}})}return i}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.theme,i=this.getRealMenuMode(),s=this.getMenuOpenAnimation(i),l=w()(n,t+"-"+r,o()({},t+"-inline-collapsed",this.getInlineCollapsed())),u={openKeys:this.state.openKeys,onOpenChange:this.handleOpenChange,className:l,mode:i};"inline"!==i?(u.onClick=this.handleClick,u.openTransitionName=s):u.openAnimation=s;var c=this.context.collapsedWidth;return!this.getInlineCollapsed()||0!==c&&"0"!==c&&"0px"!==c?v.createElement(y.e,a()({},this.props,u)):null}}]),t}(v.Component);t.a=N;N.Divider=y.a,N.Item=T,N.SubMenu=k,N.ItemGroup=y.c,N.defaultProps={prefixCls:"ant-menu",className:"",theme:"light"},N.childContextTypes={inlineCollapsed:b.a.bool,antdMenuTheme:b.a.string},N.contextTypes={siderCollapsed:b.a.bool,collapsedWidth:b.a.oneOfType([b.a.number,b.a.string])}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.storeShape=void 0;var r=n(5),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.storeShape=o.default.shape({subscribe:o.default.func.isRequired,setState:o.default.func.isRequired,getState:o.default.func.isRequired})},function(e,t,n){function r(e,t,n){(void 0===n||i(e[t],n))&&(void 0!==n||t in e)||o(e,t,n)}var o=n(138),i=n(74);e.exports=r},function(e,t,n){var r=n(33),o=r.Uint8Array;e.exports=o},function(e,t){function n(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}e.exports=n},function(e,t,n){var r=n(204),o=r(Object.getPrototypeOf,Object);e.exports=o},function(e,t){function n(e,t){return function(n){return e(t(n))}}e.exports=n},function(e,t){function n(e,t){return"__proto__"==t?void 0:e[t]}e.exports=n},function(e,t,n){function r(e){return a(e)?o(e,!0):i(e)}var o=n(207),i=n(399),a=n(76);e.exports=r},function(e,t,n){function r(e,t){var n=a(e),r=!n&&i(e),c=!n&&!r&&s(e),f=!n&&!r&&!c&&u(e),d=n||r||c||f,h=d?o(e.length,String):[],v=h.length;for(var m in e)!t&&!p.call(e,m)||d&&("length"==m||c&&("offset"==m||"parent"==m)||f&&("buffer"==m||"byteLength"==m||"byteOffset"==m)||l(m,v))||h.push(m);return h}var o=n(398),i=n(135),a=n(37),s=n(144),l=n(96),u=n(145),c=Object.prototype,p=c.hasOwnProperty;e.exports=r},function(e,t,n){"use strict";var r=n(28),o=n(11),i=n(39),a=o.OrderedMap,s=function(e){var t={},n=void 0;return a(e.withMutations(function(e){e.forEach(function(r,o){var a=r.getKey(),s=r.getNextSiblingKey(),l=r.getPrevSiblingKey(),u=r.getChildKeys(),c=r.getParentKey(),p=i();if(t[a]=p,s){e.get(s)?e.setIn([s,"prevSibling"],p):e.setIn([a,"nextSibling"],null)}if(l){e.get(l)?e.setIn([l,"nextSibling"],p):e.setIn([a,"prevSibling"],null)}if(c&&e.get(c)){var f=e.get(c),d=f.getChildKeys();e.setIn([c,"children"],d.set(d.indexOf(r.getKey()),p))}else e.setIn([a,"parent"],null),n&&(e.setIn([n.getKey(),"nextSibling"],p),e.setIn([a,"prevSibling"],t[n.getKey()])),n=e.get(a);u.forEach(function(t){e.get(t)?e.setIn([t,"parent"],p):e.setIn([a,"children"],r.getChildKeys().filter(function(e){return e!==t}))})})}).toArray().map(function(e){return[t[e.getKey()],e.set("key",t[e.getKey()])]}))},l=function(e){return a(e.toArray().map(function(e){var t=i();return[t,e.set("key",t)]}))},u=function(e){return e.first()instanceof r?s(e):l(e)};e.exports=u},function(e,t,n){"use strict";function r(e,t){var n=e.getBlockMap(),r=e.getEntityMap(),o={},a=t.getStartKey(),s=t.getStartOffset(),l=n.get(a),u=i(r,l,s);u!==l&&(o[a]=u);var c=t.getEndKey(),p=t.getEndOffset(),f=n.get(c);a===c&&(f=u);var d=i(r,f,p);return d!==f&&(o[c]=d),Object.keys(o).length?e.merge({blockMap:n.merge(o),selectionAfter:t}):e.set("selectionAfter",t)}function o(e,t,n){var r;return s(e,function(e,t){return e.getEntity()===t.getEntity()},function(e){return e.getEntity()===t},function(e,t){e<=n&&t>=n&&(r={start:e,end:t})}),"object"!=typeof r&&l(!1),r}function i(e,t,n){var r=t.getCharacterList(),i=n>0?r.get(n-1):void 0,s=n<r.count()?r.get(n):void 0,l=i?i.getEntity():void 0,u=s?s.getEntity():void 0;if(u&&u===l){if("MUTABLE"!==e.__get(u).getMutability()){for(var c,p=o(r,u,n),f=p.start,d=p.end;f<d;)c=r.get(f),r=r.set(f,a.applyEntity(c,null)),f++;return t.set("characterList",r)}}return t}var a=n(25),s=n(78),l=n(10);e.exports=r},function(e,t,n){"use strict";function r(e,t,n){if(n===e.count())t.forEach(function(t){e=e.push(t)});else if(0===n)t.reverse().forEach(function(t){e=e.unshift(t)});else{var r=e.slice(0,n),o=e.slice(n);e=r.concat(t,o).toList()}return e}e.exports=r},function(e,t,n){"use strict";var r=n(28),o=function(e,t){if(!(e instanceof r))return null;var n=e.getNextSiblingKey();if(n)return n;var o=e.getParentKey();if(!o)return null;for(var i=t.get(o);i&&!i.getNextSiblingKey();){var a=i.getParentKey();i=a?t.get(a):null}return i?i.getNextSiblingKey():null};e.exports=o},function(e,t,n){"use strict";function r(e,t){var n=[],r=e.map(function(e){return e.getStyle()}).toList();return s(r,o,p,function(e,r){n.push(new d({start:e+t,end:r+t}))}),l(n)}function o(e,t){return e===t}var i=n(11),a=n(86),s=n(78),l=i.List,u=i.Repeat,c=i.Record,p=a.thatReturnsTrue,f={start:null,end:null},d=c(f),h={start:null,end:null,decoratorKey:null,leaves:null},v=c(h),m={generate:function(e,t,n){var i=t.getLength();if(!i)return l.of(new v({start:0,end:0,decoratorKey:null,leaves:l.of(new d({start:0,end:0}))}));var a=[],c=n?n.getDecorations(t,e):l(u(null,i)),f=t.getCharacterList();return s(c,o,p,function(e,t){a.push(new v({start:e,end:t,decoratorKey:c.get(e),leaves:r(f.slice(e,t).toList(),e)}))}),l(a)},getFingerprint:function(e){return e.map(function(e){var t=e.get("decoratorKey");return(null!==t?t+"."+(e.get("end")-e.get("start")):"")+"."+e.get("leaves").size}).join("-")}};e.exports=m},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(11),s=a.Record,l=s({type:"TOKEN",mutability:"IMMUTABLE",data:Object}),u=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.getType=function(){return this.get("type")},t.prototype.getMutability=function(){return this.get("mutability")},t.prototype.getData=function(){return this.get("data")},t}(l);e.exports=u},function(e,t,n){"use strict";function r(e){var t=f.exec(e);return null==t?null:t[0]}function o(e){var t=r(e);return null==t?u.NEUTRAL:d.exec(t)?u.RTL:u.LTR}function i(e,t){if(t=t||u.NEUTRAL,!e.length)return t;var n=o(e);return n===u.NEUTRAL?t:n}function a(e,t){return t||(t=u.getGlobalDir()),u.isStrong(t)||c(!1),i(e,t)}function s(e,t){return a(e,t)===u.LTR}function l(e,t){return a(e,t)===u.RTL}var u=n(149),c=n(10),p={L:"A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u01ba\u01bb\u01bc-\u01bf\u01c0-\u01c3\u01c4-\u0293\u0294\u0295-\u02af\u02b0-\u02b8\u02bb-\u02c1\u02d0-\u02d1\u02e0-\u02e4\u02ee\u0370-\u0373\u0376-\u0377\u037a\u037b-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0482\u048a-\u052f\u0531-\u0556\u0559\u055a-\u055f\u0561-\u0587\u0589\u0903\u0904-\u0939\u093b\u093d\u093e-\u0940\u0949-\u094c\u094e-\u094f\u0950\u0958-\u0961\u0964-\u0965\u0966-\u096f\u0970\u0971\u0972-\u0980\u0982-\u0983\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09be-\u09c0\u09c7-\u09c8\u09cb-\u09cc\u09ce\u09d7\u09dc-\u09dd\u09df-\u09e1\u09e6-\u09ef\u09f0-\u09f1\u09f4-\u09f9\u09fa\u0a03\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a3e-\u0a40\u0a59-\u0a5c\u0a5e\u0a66-\u0a6f\u0a72-\u0a74\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0abe-\u0ac0\u0ac9\u0acb-\u0acc\u0ad0\u0ae0-\u0ae1\u0ae6-\u0aef\u0af0\u0b02-\u0b03\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b3e\u0b40\u0b47-\u0b48\u0b4b-\u0b4c\u0b57\u0b5c-\u0b5d\u0b5f-\u0b61\u0b66-\u0b6f\u0b70\u0b71\u0b72-\u0b77\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bbf\u0bc1-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcc\u0bd0\u0bd7\u0be6-\u0bef\u0bf0-\u0bf2\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c41-\u0c44\u0c58-\u0c59\u0c60-\u0c61\u0c66-\u0c6f\u0c7f\u0c82-\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cbe\u0cbf\u0cc0-\u0cc4\u0cc6\u0cc7-\u0cc8\u0cca-\u0ccb\u0cd5-\u0cd6\u0cde\u0ce0-\u0ce1\u0ce6-\u0cef\u0cf1-\u0cf2\u0d02-\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d3e-\u0d40\u0d46-\u0d48\u0d4a-\u0d4c\u0d4e\u0d57\u0d60-\u0d61\u0d66-\u0d6f\u0d70-\u0d75\u0d79\u0d7a-\u0d7f\u0d82-\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dcf-\u0dd1\u0dd8-\u0ddf\u0de6-\u0def\u0df2-\u0df3\u0df4\u0e01-\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e46\u0e4f\u0e50-\u0e59\u0e5a-\u0e5b\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\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f01-\u0f03\u0f04-\u0f12\u0f13\u0f14\u0f15-\u0f17\u0f1a-\u0f1f\u0f20-\u0f29\u0f2a-\u0f33\u0f34\u0f36\u0f38\u0f3e-\u0f3f\u0f40-\u0f47\u0f49-\u0f6c\u0f7f\u0f85\u0f88-\u0f8c\u0fbe-\u0fc5\u0fc7-\u0fcc\u0fce-\u0fcf\u0fd0-\u0fd4\u0fd5-\u0fd8\u0fd9-\u0fda\u1000-\u102a\u102b-\u102c\u1031\u1038\u103b-\u103c\u103f\u1040-\u1049\u104a-\u104f\u1050-\u1055\u1056-\u1057\u105a-\u105d\u1061\u1062-\u1064\u1065-\u1066\u1067-\u106d\u106e-\u1070\u1075-\u1081\u1083-\u1084\u1087-\u108c\u108e\u108f\u1090-\u1099\u109a-\u109c\u109e-\u109f\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fb\u10fc\u10fd-\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\u1360-\u1368\u1369-\u137c\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166d-\u166e\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16eb-\u16ed\u16ee-\u16f0\u16f1-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1735-\u1736\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17b6\u17be-\u17c5\u17c7-\u17c8\u17d4-\u17d6\u17d7\u17d8-\u17da\u17dc\u17e0-\u17e9\u1810-\u1819\u1820-\u1842\u1843\u1844-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1923-\u1926\u1929-\u192b\u1930-\u1931\u1933-\u1938\u1946-\u194f\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c0\u19c1-\u19c7\u19c8-\u19c9\u19d0-\u19d9\u19da\u1a00-\u1a16\u1a19-\u1a1a\u1a1e-\u1a1f\u1a20-\u1a54\u1a55\u1a57\u1a61\u1a63-\u1a64\u1a6d-\u1a72\u1a80-\u1a89\u1a90-\u1a99\u1aa0-\u1aa6\u1aa7\u1aa8-\u1aad\u1b04\u1b05-\u1b33\u1b35\u1b3b\u1b3d-\u1b41\u1b43-\u1b44\u1b45-\u1b4b\u1b50-\u1b59\u1b5a-\u1b60\u1b61-\u1b6a\u1b74-\u1b7c\u1b82\u1b83-\u1ba0\u1ba1\u1ba6-\u1ba7\u1baa\u1bae-\u1baf\u1bb0-\u1bb9\u1bba-\u1be5\u1be7\u1bea-\u1bec\u1bee\u1bf2-\u1bf3\u1bfc-\u1bff\u1c00-\u1c23\u1c24-\u1c2b\u1c34-\u1c35\u1c3b-\u1c3f\u1c40-\u1c49\u1c4d-\u1c4f\u1c50-\u1c59\u1c5a-\u1c77\u1c78-\u1c7d\u1c7e-\u1c7f\u1cc0-\u1cc7\u1cd3\u1ce1\u1ce9-\u1cec\u1cee-\u1cf1\u1cf2-\u1cf3\u1cf5-\u1cf6\u1d00-\u1d2b\u1d2c-\u1d6a\u1d6b-\u1d77\u1d78\u1d79-\u1d9a\u1d9b-\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\u200e\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2134\u2135-\u2138\u2139\u213c-\u213f\u2145-\u2149\u214e\u214f\u2160-\u2182\u2183-\u2184\u2185-\u2188\u2336-\u237a\u2395\u249c-\u24e9\u26ac\u2800-\u28ff\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2c7b\u2c7c-\u2c7d\u2c7e-\u2ce4\u2ceb-\u2cee\u2cf2-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d70\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005\u3006\u3007\u3021-\u3029\u302e-\u302f\u3031-\u3035\u3038-\u303a\u303b\u303c\u3041-\u3096\u309d-\u309e\u309f\u30a1-\u30fa\u30fc-\u30fe\u30ff\u3105-\u312d\u3131-\u318e\u3190-\u3191\u3192-\u3195\u3196-\u319f\u31a0-\u31ba\u31f0-\u31ff\u3200-\u321c\u3220-\u3229\u322a-\u3247\u3248-\u324f\u3260-\u327b\u327f\u3280-\u3289\u328a-\u32b0\u32c0-\u32cb\u32d0-\u32fe\u3300-\u3376\u337b-\u33dd\u33e0-\u33fe\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua014\ua015\ua016-\ua48c\ua4d0-\ua4f7\ua4f8-\ua4fd\ua4fe-\ua4ff\ua500-\ua60b\ua60c\ua610-\ua61f\ua620-\ua629\ua62a-\ua62b\ua640-\ua66d\ua66e\ua680-\ua69b\ua69c-\ua69d\ua6a0-\ua6e5\ua6e6-\ua6ef\ua6f2-\ua6f7\ua722-\ua76f\ua770\ua771-\ua787\ua789-\ua78a\ua78b-\ua78e\ua790-\ua7ad\ua7b0-\ua7b1\ua7f7\ua7f8-\ua7f9\ua7fa\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua823-\ua824\ua827\ua830-\ua835\ua836-\ua837\ua840-\ua873\ua880-\ua881\ua882-\ua8b3\ua8b4-\ua8c3\ua8ce-\ua8cf\ua8d0-\ua8d9\ua8f2-\ua8f7\ua8f8-\ua8fa\ua8fb\ua900-\ua909\ua90a-\ua925\ua92e-\ua92f\ua930-\ua946\ua952-\ua953\ua95f\ua960-\ua97c\ua983\ua984-\ua9b2\ua9b4-\ua9b5\ua9ba-\ua9bb\ua9bd-\ua9c0\ua9c1-\ua9cd\ua9cf\ua9d0-\ua9d9\ua9de-\ua9df\ua9e0-\ua9e4\ua9e6\ua9e7-\ua9ef\ua9f0-\ua9f9\ua9fa-\ua9fe\uaa00-\uaa28\uaa2f-\uaa30\uaa33-\uaa34\uaa40-\uaa42\uaa44-\uaa4b\uaa4d\uaa50-\uaa59\uaa5c-\uaa5f\uaa60-\uaa6f\uaa70\uaa71-\uaa76\uaa77-\uaa79\uaa7a\uaa7b\uaa7d\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadc\uaadd\uaade-\uaadf\uaae0-\uaaea\uaaeb\uaaee-\uaaef\uaaf0-\uaaf1\uaaf2\uaaf3-\uaaf4\uaaf5\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5b\uab5c-\uab5f\uab64-\uab65\uabc0-\uabe2\uabe3-\uabe4\uabe6-\uabe7\uabe9-\uabea\uabeb\uabec\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\ue000-\uf8ff\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\uff21-\uff3a\uff41-\uff5a\uff66-\uff6f\uff70\uff71-\uff9d\uff9e-\uff9f\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",R:"\u0590\u05be\u05c0\u05c3\u05c6\u05c8-\u05cf\u05d0-\u05ea\u05eb-\u05ef\u05f0-\u05f2\u05f3-\u05f4\u05f5-\u05ff\u07c0-\u07c9\u07ca-\u07ea\u07f4-\u07f5\u07fa\u07fb-\u07ff\u0800-\u0815\u081a\u0824\u0828\u082e-\u082f\u0830-\u083e\u083f\u0840-\u0858\u085c-\u085d\u085e\u085f-\u089f\u200f\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb37\ufb38-\ufb3c\ufb3d\ufb3e\ufb3f\ufb40-\ufb41\ufb42\ufb43-\ufb44\ufb45\ufb46-\ufb4f",AL:"\u0608\u060b\u060d\u061b\u061c\u061d\u061e-\u061f\u0620-\u063f\u0640\u0641-\u064a\u066d\u066e-\u066f\u0671-\u06d3\u06d4\u06d5\u06e5-\u06e6\u06ee-\u06ef\u06fa-\u06fc\u06fd-\u06fe\u06ff\u0700-\u070d\u070e\u070f\u0710\u0712-\u072f\u074b-\u074c\u074d-\u07a5\u07b1\u07b2-\u07bf\u08a0-\u08b2\u08b3-\u08e3\ufb50-\ufbb1\ufbb2-\ufbc1\ufbc2-\ufbd2\ufbd3-\ufd3d\ufd40-\ufd4f\ufd50-\ufd8f\ufd90-\ufd91\ufd92-\ufdc7\ufdc8-\ufdcf\ufdf0-\ufdfb\ufdfc\ufdfe-\ufdff\ufe70-\ufe74\ufe75\ufe76-\ufefc\ufefd-\ufefe"},f=new RegExp("["+p.L+p.R+p.AL+"]"),d=new RegExp("["+p.R+p.AL+"]"),h={firstStrongChar:r,firstStrongCharDir:o,resolveBlockDir:i,getDirection:a,isDirectionLTR:s,isDirectionRTL:l};e.exports=h},function(e,t,n){"use strict";e.exports={BOLD:{fontWeight:"bold"},CODE:{fontFamily:"monospace",wordWrap:"break-word"},ITALIC:{fontStyle:"italic"},STRIKETHROUGH:{textDecoration:"line-through"},UNDERLINE:{textDecoration:"underline"}}},function(e,t,n){"use strict";function r(e){var t=e.getSelection(),n=t.getAnchorKey(),r=e.getBlockTree(n),o=t.getStartOffset(),i=!1;return r.some(function(e){return o===e.get("start")?(i=!0,!0):o<e.get("end")&&e.get("leaves").some(function(e){var t=e.get("start");return o===t&&(i=!0,!0)})}),i}e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(16),s=a||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(442),u=n(80),c=n(0),p=n(9),f=n(219),d=n(154),h=n(214),v=n(149),m=n(66),y=n(457),g=n(155),b=n(461),C=n(10),w=n(34),S=function(e,t){return e.getAnchorKey()===t||e.getFocusKey()===t},x=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.shouldComponentUpdate=function(e){return this.props.block!==e.block||this.props.tree!==e.tree||this.props.direction!==e.direction||S(e.selection,e.block.getKey())&&e.forceSelection},t.prototype.componentDidMount=function(){var e=this.props.selection,t=e.getEndKey();if(e.getHasFocus()&&t===this.props.block.getKey()){var n=p.findDOMNode(this),r=d.getScrollParent(n),o=g(r),i=void 0;if(r===window){var a=y(n);i=a.y+a.height-b().height,i>0&&window.scrollTo(o.x,o.y+i+10)}else{n instanceof HTMLElement||C(!1);i=n.offsetHeight+n.offsetTop-(r.offsetHeight+o.y),i>0&&f.setTop(r,f.getTop(r)+i+10)}}},t.prototype._renderChildren=function(){var e=this,t=this.props.block,n=t.getKey(),r=t.getText(),o=this.props.tree.size-1,i=S(this.props.selection,n);return this.props.tree.map(function(a,p){var f=a.get("leaves"),d=f.size-1,m=f.map(function(a,s){var f=u.encode(n,p,s),h=a.get("start"),v=a.get("end");return c.createElement(l,{key:f,offsetKey:f,block:t,start:h,selection:i?e.props.selection:null,forceSelection:e.props.forceSelection,text:r.slice(h,v),styleSet:t.getInlineStyleAt(h),customStyleMap:e.props.customStyleMap,customStyleFn:e.props.customStyleFn,isLast:p===o&&s===d})}).toArray(),y=a.get("decoratorKey");if(null==y)return m;if(!e.props.decorator)return m;var g=w(e.props.decorator),b=g.getComponentForKey(y);if(!b)return m;var C=g.getPropsForKey(y),S=u.encode(n,p,0),x=r.slice(f.first().get("start"),f.last().get("end")),_=v.getHTMLDirIfDifferent(h.getDirection(x),e.props.direction);return c.createElement(b,s({},C,{contentState:e.props.contentState,decoratedText:x,dir:_,key:S,entityKey:t.getEntityAt(a.get("start")),offsetKey:S}),m)}).toArray()},t.prototype.render=function(){var e=this.props,t=e.direction,n=e.offsetKey,r=m({"public/DraftStyleDefault/block":!0,"public/DraftStyleDefault/ltr":"LTR"===t,"public/DraftStyleDefault/rtl":"RTL"===t});return c.createElement("div",{"data-offset-key":n,className:r},this._renderChildren())},t}(c.Component);e.exports=x},function(e,t,n){"use strict";function r(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}e.exports=r},function(e,t,n){"use strict";function r(e,t){return!!t&&(e===t.documentElement||e===t.body)}var o={getTop:function(e){var t=e.ownerDocument;return r(e,t)?t.body.scrollTop||t.documentElement.scrollTop:e.scrollTop},setTop:function(e,t){var n=e.ownerDocument;r(e,n)?n.body.scrollTop=n.documentElement.scrollTop=t:e.scrollTop=t},getLeft:function(e){var t=e.ownerDocument;return r(e,t)?t.body.scrollLeft||t.documentElement.scrollLeft:e.scrollLeft},setLeft:function(e,t){var n=e.ownerDocument;r(e,n)?n.body.scrollLeft=n.documentElement.scrollLeft=t:e.scrollLeft=t}};e.exports=o},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e){if("file"==e.kind)return e.getAsFile()}var i=n(464),a=n(465),s=n(86),l=new RegExp("\r\n","g"),u={"text/rtf":1,"text/html":1},c=function(){function e(t){r(this,e),this.data=t,this.types=t.types?a(t.types):[]}return e.prototype.isRichText=function(){return!(!this.getHTML()||!this.getText())||!this.isImage()&&this.types.some(function(e){return u[e]})},e.prototype.getText=function(){var e;return this.data.getData&&(this.types.length?-1!=this.types.indexOf("text/plain")&&(e=this.data.getData("text/plain")):e=this.data.getData("Text")),e?e.replace(l,"\n"):null},e.prototype.getHTML=function(){if(this.data.getData){if(!this.types.length)return this.data.getData("Text");if(-1!=this.types.indexOf("text/html"))return this.data.getData("text/html")}},e.prototype.isLink=function(){return this.types.some(function(e){return-1!=e.indexOf("Url")||-1!=e.indexOf("text/uri-list")||e.indexOf("text/x-moz-url")})},e.prototype.getLink=function(){if(this.data.getData){if(-1!=this.types.indexOf("text/x-moz-url")){return this.data.getData("text/x-moz-url").split("\n")[0]}return-1!=this.types.indexOf("text/uri-list")?this.data.getData("text/uri-list"):this.data.getData("url")}return null},e.prototype.isImage=function(){if(this.types.some(function(e){return-1!=e.indexOf("application/x-moz-file")}))return!0;for(var e=this.getFiles(),t=0;t<e.length;t++){var n=e[t].type;if(!i.isImage(n))return!1}return!0},e.prototype.getCount=function(){return this.data.hasOwnProperty("items")?this.data.items.length:this.data.hasOwnProperty("mozItemCount")?this.data.mozItemCount:this.data.files?this.data.files.length:null},e.prototype.getFiles=function(){return this.data.items?Array.prototype.slice.call(this.data.items).map(o).filter(s.thatReturnsArgument):this.data.files?Array.prototype.slice.call(this.data.files):[]},e.prototype.hasFiles=function(){return this.getFiles().length>0},e}();e.exports=c},function(e,t,n){"use strict";function r(e){if(e instanceof Element){var t=e.getAttribute("data-offset-key");if(t)return t;for(var n=0;n<e.childNodes.length;n++){var o=r(e.childNodes[n]);if(o)return o}}return null}e.exports=r},function(e,t,n){"use strict";(function(t){function r(e,t){var n=0,r=[];e.forEach(function(i){o(i,function(o){n++,o&&r.push(o.slice(0,l)),n==e.length&&t(r.join("\r"))})})}function o(e,n){if(!t.FileReader||e.type&&!(e.type in s))return void n("");if(""===e.type){var r="";return a.test(e.name)&&(r=e.name.replace(a,"")),void n(r)}var o=new FileReader;o.onload=function(){var e=o.result;"string"!=typeof e&&i(!1),n(e)},o.onerror=function(){n("")},o.readAsText(e)}var i=n(10),a=/\.textClipping$/,s={"text/plain":!0,"text/html":!0,"text/rtf":!0},l=5e3;e.exports=r}).call(t,n(24))},function(e,t,n){"use strict";function r(e,t,n,r,a){var s=i(e.getSelection()),l=o.decode(t),u=l.blockKey,c=e.getBlockTree(u).getIn([l.decoratorKey,"leaves",l.leafKey]),p=o.decode(r),f=p.blockKey,d=e.getBlockTree(f).getIn([p.decoratorKey,"leaves",p.leafKey]),h=c.get("start"),v=d.get("start"),m=c?h+n:null,y=d?v+a:null;if(s.getAnchorKey()===u&&s.getAnchorOffset()===m&&s.getFocusKey()===f&&s.getFocusOffset()===y)return s;var g=!1;if(u===f){var b=c.get("end"),C=d.get("end");g=v===h&&C===b?a<n:v<h}else{g=e.getCurrentContent().getBlockMap().keySeq().skipUntil(function(e){return e===u||e===f}).first()===f}return s.merge({anchorKey:u,anchorOffset:m,focusKey:f,focusOffset:y,isBackward:g})}var o=n(80),i=n(34);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.getSelection();return t.isCollapsed()?null:o(e.getCurrentContent(),t)}var o=n(97);e.exports=r},function(e,t,n){"use strict";function r(e){for(var t=e.cloneRange(),n=[],r=e.endContainer;null!=r;r=r.parentNode){var o=r===e.commonAncestorContainer;o?t.setStart(e.startContainer,e.startOffset):t.setStart(t.endContainer,0);var a=Array.from(t.getClientRects());if(n.push(a),o){var s;return n.reverse(),(s=[]).concat.apply(s,n)}t.setEndBefore(r)}i(!1)}var o=n(38),i=n(10),a=o.isBrowser("Chrome"),s=a?r:function(e){return Array.from(e.getClientRects())};e.exports=s},function(e,t,n){"use strict";function r(e,t,n,r,o,i){var s=n.nodeType===Node.TEXT_NODE,u=o.nodeType===Node.TEXT_NODE;if(s&&u)return{selectionState:c(e,f(l(n)),r,f(l(o)),i),needsRecovery:!1};var p=null,d=null,h=!0;return s?(p={key:f(l(n)),offset:r},d=a(t,o,i)):u?(d={key:f(l(o)),offset:i},p=a(t,n,r)):(p=a(t,n,r),d=a(t,o,i),n===o&&r===i&&(h=!!n.firstChild&&"BR"!==n.firstChild.nodeName)),{selectionState:c(e,p.key,p.offset,d.key,d.offset),needsRecovery:h}}function o(e){for(;e.firstChild&&(e.firstChild instanceof Element&&"true"===e.firstChild.getAttribute("data-blocks")||u(e.firstChild));)e=e.firstChild;return e}function i(e){for(;e.lastChild&&(e.lastChild instanceof Element&&"true"===e.lastChild.getAttribute("data-blocks")||u(e.lastChild));)e=e.lastChild;return e}function a(e,t,n){var r=t,a=l(r);if(null!=a||e&&(e===r||e.firstChild===r)||p(!1),e===r&&(r=r.firstChild,r instanceof Element&&"true"===r.getAttribute("data-contents")||p(!1),n>0&&(n=r.childNodes.length)),0===n){var c=null;if(null!=a)c=a;else{var d=o(r);c=f(u(d))}return{key:c,offset:0}}var h=r.childNodes[n-1],v=null,m=null;if(u(h)){var y=i(h);v=f(u(y)),m=s(y)}else v=f(a),m=s(h);return{key:v,offset:m}}function s(e){var t=e.textContent;return"\n"===t?0:t.length}var l=n(156),u=n(221),c=n(223),p=n(10),f=n(34);e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=t?c.exec(e):l.exec(e);return n?n[0]:e}var o=n(483),i=o.getPunctuation(),a="\\s|(?![_])"+i,s="^(?:"+a+")*(?:['\u2018\u2019]|(?!"+a+").)*(?:(?!"+a+").)",l=new RegExp(s),u="(?:(?!"+a+").)(?:['\u2018\u2019]|(?!"+a+").)*(?:"+a+")*$",c=new RegExp(u),p={getBackward:function(e){return r(e,!0)},getForward:function(e){return r(e,!1)}};e.exports=p},function(e,t,n){"use strict";function r(e,t){var n,r=e.getSelection(),o=r.getStartKey(),i=r.getStartOffset(),a=e.getCurrentContent(),s=o;return t>a.getBlockForKey(o).getText().length-i?(s=a.getKeyAfter(o),n=0):n=i+t,r.merge({focusKey:s,focusOffset:n})}e.exports=r},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var o,i=a||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(16),s=n(25),l=n(54),u=n(28),c=n(150),p=n(98),f=n(45),d=n(11),h=n(11),v=h.Set,m=n(494),y=n(66),g=n(39),b=n(230),C=n(10),w=n(148),S=f.draft_tree_data_support,x=d.List,_=d.OrderedSet,k=new RegExp("\r","g"),E=new RegExp("\n","g"),O=new RegExp("&nbsp;","g"),T=new RegExp("&#13;?","g"),N=new RegExp("&#8203;?","g"),P=["bold","bolder","500","600","700","800","900"],M=["light","lighter","100","200","300","400"],D={b:"BOLD",code:"CODE",del:"STRIKETHROUGH",em:"ITALIC",i:"ITALIC",s:"STRIKETHROUGH",strike:"STRIKETHROUGH",strong:"BOLD",u:"UNDERLINE"},I=(o={},r(o,y("public/DraftStyleDefault/depth0"),0),r(o,y("public/DraftStyleDefault/depth1"),1),r(o,y("public/DraftStyleDefault/depth2"),2),r(o,y("public/DraftStyleDefault/depth3"),3),r(o,y("public/DraftStyleDefault/depth4"),4),o),A=["className","href","rel","target","title"],j=["alt","className","height","src","width"],R=void 0,L={text:"",inlines:[],entities:[],blocks:[]},K={children:x(),depth:0,key:"",type:""},F=function(e,t){return"li"===e?"ol"===t?"ordered-list-item":"unordered-list-item":null},V=function(e){var t=e.get("unstyled").element,n=v([]);return e.forEach(function(e){e.aliasedElements&&e.aliasedElements.forEach(function(e){n=n.add(e)}),n=n.add(e.element)}),n.filter(function(e){return e&&e!==t}).toArray().sort()},z=function(e,t,n){for(var r=0;r<n.length;r++){var o=n[r](e,t);if(o)return o}return null},B=function(e,t,n){var r=n.filter(function(t){return t.element===e||t.wrapper===e||t.aliasedElements&&t.aliasedElements.some(function(t){return t===e})}).keySeq().toSet().toArray().sort();switch(r.length){case 0:return"unstyled";case 1:return r[0];default:return z(e,t,[F])||"unstyled"}},W=function(e,t,n){var r=D[e];if(r)n=n.add(r).toOrderedSet();else if(t instanceof HTMLElement){var o=t;n=n.withMutations(function(e){var t=o.style.fontWeight,n=o.style.fontStyle,r=o.style.textDecoration;P.indexOf(t)>=0?e.add("BOLD"):M.indexOf(t)>=0&&e.remove("BOLD"),"italic"===n?e.add("ITALIC"):"normal"===n&&e.remove("ITALIC"),"underline"===r&&e.add("UNDERLINE"),"line-through"===r&&e.add("STRIKETHROUGH"),"none"===r&&(e.remove("UNDERLINE"),e.remove("STRIKETHROUGH"))}).toOrderedSet()}return n},H=function(e,t,n){var r=e.text.slice(-1),o=t.text.slice(0,1);if("\r"!==r||"\r"!==o||n||(e.text=e.text.slice(0,-1),e.inlines.pop(),e.entities.pop(),e.blocks.pop()),"\r"===r){if(" "===t.text||"\n"===t.text)return e;" "!==o&&"\n"!==o||(t.text=t.text.slice(1),t.inlines.shift(),t.entities.shift())}return{text:e.text+t.text,inlines:e.inlines.concat(t.inlines),entities:e.entities.concat(t.entities),blocks:e.blocks.concat(t.blocks)}},U=function(e,t){return t.some(function(t){return-1!==e.indexOf("<"+t)})},q=function(e){e instanceof HTMLAnchorElement||C(!1);var t=e.protocol;return"http:"===t||"https:"===t||"mailto:"===t},Y=function(e){var t=new Array(1);return e&&(t[0]=e),i({},L,{text:" ",inlines:[_()],entities:t})},G=function(){return i({},L,{text:"\n",inlines:[_()],entities:new Array(1)})},X=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return i({},K,e)},$=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return{text:"\r",inlines:[_()],entities:new Array(1),blocks:[X({parent:n,key:g(),type:e,depth:Math.max(0,Math.min(4,t))})]}},J=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return Object.keys(I).some(function(n){e.classList.contains(n)&&(t=I[n])}),t},Z=function e(t,n,r,o,a,s,l,u,c,f){var d=R,h=n.nodeName.toLowerCase(),v=t,y="unstyled",g=!1,b=a&&B(a,o,u),C=i({},L),w=null,x=void 0;if("#text"===h){var _=n.textContent,k=_.trim();if(o&&""===k&&n.parentElement){var O=n.parentElement.nodeName.toLowerCase();if("ol"===O||"ul"===O)return{chunk:i({},L),entityMap:t}}return""===k&&"pre"!==a?{chunk:Y(c),entityMap:t}:("pre"!==a&&(_=_.replace(E," ")),R=h,{chunk:{text:_,inlines:Array(_.length).fill(r),entities:Array(_.length).fill(c),blocks:[]},entityMap:t})}if(R=h,"br"===h)return"br"!==d||a&&"unstyled"!==b?{chunk:G(),entityMap:t}:{chunk:$("unstyled",l,f),entityMap:t};if("img"===h&&n instanceof HTMLImageElement&&n.attributes.getNamedItem("src")&&n.attributes.getNamedItem("src").value){var T=n,N={};j.forEach(function(e){var t=T.getAttribute(e);t&&(N[e]=t)}),n.textContent="\ud83d\udcf7",c=p.__create("IMAGE","MUTABLE",N||{})}r=W(h,n,r),"ul"!==h&&"ol"!==h||(o&&(l+=1),o=h),!S&&"li"===h&&n instanceof HTMLElement&&(l=J(n,l));var P=B(h,o,u),M=o&&"li"===a&&"li"===h,D=(!a||S)&&-1!==s.indexOf(h);(M||D)&&(C=$(P,l,f),x=C.blocks[0].key,a=h,g=!S),M&&(y="ul"===o?"unordered-list-item":"ordered-list-item");var I=n.firstChild;null!=I&&(h=I.nodeName.toLowerCase());for(var K=null;I;){I instanceof HTMLAnchorElement&&I.href&&q(I)?function(){var e=I,t={};A.forEach(function(n){var r=e.getAttribute(n);r&&(t[n]=r)}),t.url=new m(e.href).toString(),K=p.__create("LINK","MUTABLE",t||{})}():K=void 0;var F=e(v,I,r,o,a,s,l,u,K||c,S?x:null),V=F.chunk,z=F.entityMap;w=V,v=z,C=H(C,w,S);var U=I.nextSibling;!f&&U&&s.indexOf(h)>=0&&a&&(C=H(C,G())),U&&(h=U.nodeName.toLowerCase()),I=U}return g&&(C=H(C,$(y,l,f))),{chunk:C,entityMap:v}},Q=function(e,t,n,r){e=e.trim().replace(k,"").replace(O," ").replace(T,"").replace(N,"");var o=V(n),a=t(e);if(!a)return null;R=null;var s=U(e,o)?o:["div"],l=Z(r,a,_(),"ul",null,s,-1,n),u=l.chunk,c=l.entityMap;return 0===u.text.indexOf("\r")&&(u={text:u.text.slice(1),inlines:u.inlines.slice(1),entities:u.entities.slice(1),blocks:u.blocks}),"\r"===u.text.slice(-1)&&(u.text=u.text.slice(0,-1),u.inlines=u.inlines.slice(0,-1),u.entities=u.entities.slice(0,-1),u.blocks.pop()),0===u.blocks.length&&u.blocks.push(i({},L,{type:"unstyled",depth:0})),u.text.split("\r").length===u.blocks.length+1&&u.blocks.unshift({type:"unstyled",depth:0}),{chunk:u,entityMap:c}},ee=function(e){if(!e||!e.text||!Array.isArray(e.blocks))return null;var t={cacheRef:{},contentBlocks:[]},n=0,r=e.blocks,o=e.inlines,i=e.entities,a=S?u:l;return e.text.split("\r").reduce(function(e,t,l){t=w(t);var c=r[l],p=n+t.length,f=o.slice(n,p),d=i.slice(n,p),h=x(f.map(function(e,t){var n={style:e,entity:null};return d[t]&&(n.entity=d[t]),s.create(n)}));n=p+1;var v=c.depth,m=c.type,y=c.parent,b=c.key||g(),C=null;if(y){var S=e.cacheRef[y],_=e.contentBlocks[S];if(_.getChildKeys().isEmpty()&&_.getText()){var k=_.getCharacterList(),E=_.getText();C=g();var O=new u({key:C,text:E,characterList:k,parent:y,nextSibling:b});e.contentBlocks.push(O),_=_.withMutations(function(e){e.set("characterList",x()).set("text","").set("children",_.children.push(O.getKey()))})}e.contentBlocks[S]=_.set("children",_.children.push(b))}var T=new a({key:b,parent:y,type:m,depth:v,text:t,characterList:h,prevSibling:C||(0===l||r[l-1].parent!==y?null:r[l-1].key),nextSibling:l===r.length-1||r[l+1].parent!==y?null:r[l+1].key});return e.contentBlocks.push(T),e.cacheRef[T.key]=l,e},t).contentBlocks},te=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:b,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:c,r=Q(e,t,n,p);if(null==r)return null;var o=r.chunk,i=r.entityMap;return{contentBlocks:ee(o),entityMap:i}};e.exports=te},function(e,t,n){"use strict";function r(e){var t,n=null;return!a&&document.implementation&&document.implementation.createHTMLDocument&&(t=document.implementation.createHTMLDocument("foo"),t.documentElement||i(!1),t.documentElement.innerHTML=e,n=t.getElementsByTagName("body")[0]),n}var o=n(38),i=n(10),a=o.isBrowser("IE <= 9");e.exports=r},function(e,t,n){"use strict";var r=n(22),o=n(12),i=(n(65),n(495)),a=n(34),s={currentBlockContainsLink:function(e){var t=e.getSelection(),n=e.getCurrentContent(),r=n.getEntityMap();return n.getBlockForKey(t.getAnchorKey()).getCharacterList().slice(t.getStartOffset(),t.getEndOffset()).some(function(e){var t=e.getEntity();return!!t&&"LINK"===r.__get(t).getType()})},getCurrentBlockType:function(e){var t=e.getSelection();return e.getCurrentContent().getBlockForKey(t.getStartKey()).getType()},getDataObjectForLinkURL:function(e){return{url:e.toString()}},handleKeyCommand:function(e,t){switch(t){case"bold":return s.toggleInlineStyle(e,"BOLD");case"italic":return s.toggleInlineStyle(e,"ITALIC");case"underline":return s.toggleInlineStyle(e,"UNDERLINE");case"code":return s.toggleCode(e);case"backspace":case"backspace-word":case"backspace-to-start-of-line":return s.onBackspace(e);case"delete":case"delete-word":case"delete-to-end-of-block":return s.onDelete(e);default:return null}},insertSoftNewline:function(e){var t=r.insertText(e.getCurrentContent(),e.getSelection(),"\n",e.getCurrentInlineStyle(),null),n=o.push(e,t,"insert-characters");return o.forceSelection(n,t.getSelectionAfter())},onBackspace:function(e){var t=e.getSelection();if(!t.isCollapsed()||t.getAnchorOffset()||t.getFocusOffset())return null;var n=e.getCurrentContent(),r=t.getStartKey(),i=n.getBlockBefore(r);if(i&&"atomic"===i.getType()){var a=n.getBlockMap().delete(i.getKey()),l=n.merge({blockMap:a,selectionAfter:t});if(l!==n)return o.push(e,l,"remove-range")}var u=s.tryToRemoveBlockStyle(e);return u?o.push(e,u,"change-block-type"):null},onDelete:function(e){var t=e.getSelection();if(!t.isCollapsed())return null;var n=e.getCurrentContent(),i=t.getStartKey(),a=n.getBlockForKey(i),s=a.getLength();if(t.getStartOffset()<s)return null;var l=n.getBlockAfter(i);if(!l||"atomic"!==l.getType())return null;var u=t.merge({focusKey:l.getKey(),focusOffset:l.getLength()}),c=r.removeRange(n,u,"forward");return c!==n?o.push(e,c,"remove-range"):null},onTab:function(e,t,n){var r=t.getSelection(),a=r.getAnchorKey();if(a!==r.getFocusKey())return t;var s=t.getCurrentContent(),l=s.getBlockForKey(a),u=l.getType();if("unordered-list-item"!==u&&"ordered-list-item"!==u)return t;e.preventDefault();var c=s.getBlockBefore(a);if(!c)return t;var p=c.getType();if("unordered-list-item"!==p&&"ordered-list-item"!==p)return t;var f=l.getDepth();if(!e.shiftKey&&f===n)return t;n=Math.min(c.getDepth()+1,n);var d=i(s,r,e.shiftKey?-1:1,n);return o.push(t,d,"adjust-depth")},toggleBlockType:function(e,t){var n=e.getSelection(),i=n.getStartKey(),s=n.getEndKey(),l=e.getCurrentContent(),u=n;if(i!==s&&0===n.getEndOffset()){var c=a(l.getBlockBefore(s));s=c.getKey(),u=u.merge({anchorKey:i,anchorOffset:n.getStartOffset(),focusKey:s,focusOffset:c.getLength(),isBackward:!1})}if(l.getBlockMap().skipWhile(function(e,t){return t!==i}).reverse().skipWhile(function(e,t){return t!==s}).some(function(e){return"atomic"===e.getType()}))return e;var p=l.getBlockForKey(i).getType()===t?"unstyled":t;return o.push(e,r.setBlockType(l,u,p),"change-block-type")},toggleCode:function(e){var t=e.getSelection(),n=t.getAnchorKey(),r=t.getFocusKey();return t.isCollapsed()||n!==r?s.toggleBlockType(e,"code-block"):s.toggleInlineStyle(e,"CODE")},toggleInlineStyle:function(e,t){var n=e.getSelection(),i=e.getCurrentInlineStyle();if(n.isCollapsed())return o.setInlineStyleOverride(e,i.has(t)?i.remove(t):i.add(t));var a,s=e.getCurrentContent();return a=i.has(t)?r.removeInlineStyle(s,n,t):r.applyInlineStyle(s,n,t),o.push(e,a,"change-inline-style")},toggleLink:function(e,t,n){var i=r.applyEntity(e.getCurrentContent(),t,n);return o.push(e,i,"apply-entity")},tryToRemoveBlockStyle:function(e){var t=e.getSelection(),n=t.getAnchorOffset();if(t.isCollapsed()&&0===n){var o=t.getAnchorKey(),i=e.getCurrentContent(),a=i.getBlockForKey(o),s=i.getFirstBlock();if(a.getLength()>0&&a!==s)return null;var l=a.getType(),u=i.getBlockBefore(o);if("code-block"===l&&u&&"code-block"===u.getType()&&0!==u.getLength())return null;if("unstyled"!==l)return r.setBlockType(i,t,"unstyled")}return null}};e.exports=s},function(e,t,n){"use strict";function r(e){return p&&e.altKey||v(e)}function o(e){return h(e)?e.shiftKey?"redo":"undo":null}function i(e){return f&&e.shiftKey?null:r(e)?"delete-word":"delete"}function a(e){return h(e)&&p?"backspace-to-start-of-line":r(e)?"backspace-word":"backspace"}function s(e){switch(e.keyCode){case 66:return h(e)?"bold":null;case 68:return v(e)?"delete":null;case 72:return v(e)?"backspace":null;case 73:return h(e)?"italic":null;case 74:return h(e)?"code":null;case 75:return!f&&v(e)?"secondary-cut":null;case 77:case 79:return v(e)?"split-block":null;case 84:return p&&v(e)?"transpose-characters":null;case 85:return h(e)?"underline":null;case 87:return p&&v(e)?"backspace-word":null;case 89:return v(e)?f?"redo":"secondary-paste":null;case 90:return o(e)||null;case u.RETURN:return"split-block";case u.DELETE:return i(e);case u.BACKSPACE:return a(e);case u.LEFT:return d&&h(e)?"move-selection-to-start-of-block":null;case u.RIGHT:return d&&h(e)?"move-selection-to-end-of-block":null;default:return null}}var l=n(158),u=n(151),c=n(38),p=c.isPlatform("Mac OS X"),f=c.isPlatform("Windows"),d=p&&c.isBrowser("Firefox < 29"),h=l.hasCommandModifier,v=l.isCtrlKeyCommand;e.exports=s},function(e,t,n){"use strict";var r={stringify:function(e){return"_"+String(e)},unstringify:function(e){return e.slice(1)}};e.exports=r},function(e,t,n){(function(e){function r(e,t){this._id=e,this._clearFn=t}var o=Function.prototype.apply;t.setTimeout=function(){return new r(o.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new r(o.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(157),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(t,n(24))},function(e,t,n){var r=n(517),o=n(134),i=n(518),a=n(236),s=n(519),l=n(52),u=n(191),c=u(r),p=u(o),f=u(i),d=u(a),h=u(s),v=l;(r&&"[object DataView]"!=v(new r(new ArrayBuffer(1)))||o&&"[object Map]"!=v(new o)||i&&"[object Promise]"!=v(i.resolve())||a&&"[object Set]"!=v(new a)||s&&"[object WeakMap]"!=v(new s))&&(v=function(e){var t=l(e),n="[object Object]"==t?e.constructor:void 0,r=n?u(n):"";if(r)switch(r){case c:return"[object DataView]";case p:return"[object Map]";case f:return"[object Promise]";case d:return"[object Set]";case h:return"[object WeakMap]"}return t}),e.exports=v},function(e,t,n){var r=n(53),o=n(33),i=r(o,"Set");e.exports=i},function(e,t){function n(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}e.exports=n},function(e,t,n){function r(e,t,n,a,s){return e===t||(null==e||null==t||!i(e)&&!i(t)?e!==e&&t!==t:o(e,t,n,a,r,s))}var o=n(535),i=n(43);e.exports=r},function(e,t,n){function r(e,t,n,r,u,c){var p=n&s,f=e.length,d=t.length;if(f!=d&&!(p&&d>f))return!1;var h=c.get(e);if(h&&c.get(t))return h==t;var v=-1,m=!0,y=n&l?new o:void 0;for(c.set(e,t),c.set(t,e);++v<f;){var g=e[v],b=t[v];if(r)var C=p?r(b,g,v,t,e,c):r(g,b,v,e,t,c);if(void 0!==C){if(C)continue;m=!1;break}if(y){if(!i(t,function(e,t){if(!a(y,t)&&(g===e||u(g,e,n,r,c)))return y.push(t)})){m=!1;break}}else if(g!==b&&!u(g,b,n,r,c)){m=!1;break}}return c.delete(e),c.delete(t),m}var o=n(240),i=n(538),a=n(241),s=1,l=2;e.exports=r},function(e,t,n){function r(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new o;++t<n;)this.add(e[t])}var o=n(132),i=n(536),a=n(537);r.prototype.add=r.prototype.push=i,r.prototype.has=a,e.exports=r},function(e,t){function n(e,t){return e.has(t)}e.exports=n},function(e,t,n){function r(e){return e===e&&!o(e)}var o=n(32);e.exports=r},function(e,t){function n(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}e.exports=n},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(628));n.n(o)},function(e,t,n){"use strict";t.a={items_per_page:"\u6761/\u9875",jump_to:"\u8df3\u81f3",jump_to_confirm:"\u786e\u5b9a",page:"\u9875",prev_page:"\u4e0a\u4e00\u9875",next_page:"\u4e0b\u4e00\u9875",prev_5:"\u5411\u524d 5 \u9875",next_5:"\u5411\u540e 5 \u9875",prev_3:"\u5411\u524d 3 \u9875",next_3:"\u5411\u540e 3 \u9875"}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(593));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(248));n.n(o)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(620));n.n(o)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(621));n.n(o),n(163),n(101)},function(e,t,n){"use strict";function r(e,t){if("undefined"==typeof window)return 0;var n=t?"pageYOffset":"pageXOffset",r=t?"scrollTop":"scrollLeft",o=e===window,i=o?e[n]:e[r];return o&&"number"!=typeof i&&(i=window.document.documentElement[r]),i}function o(e){var t=void 0,n=function(n){return function(){t=null,e.apply(void 0,ci()(n))}},r=function(){for(var e=arguments.length,r=Array(e),o=0;o<e;o++)r[o]=arguments[o];null==t&&(t=fi(n(r)))};return r.cancel=function(){return Object(pi.a)(t)},r}function i(){return function(e,t,n){var r=n.value,i=!1;return{configurable:!0,get:function(){if(i||this===e.prototype||this.hasOwnProperty(t))return r;var n=o(r.bind(this));return i=!0,Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),i=!1,n}}}}function a(e){return e!==window?e.getBoundingClientRect():{top:0,left:0,bottom:0}}function s(e,t){var n=e.getBoundingClientRect(),o=a(t),i=r(t,!0),s=r(t,!1),l=window.document.body,u=l.clientTop||0,c=l.clientLeft||0;return{top:n.top-o.top+i-u,left:n.left-o.left+s-c,width:n.width,height:n.height}}function l(){}function u(){return"undefined"!=typeof window?window:null}function c(){return window}function p(e){if(!e)return 0;if(!e.getClientRects().length)return 0;var t=e.getBoundingClientRect();if(t.width||t.height){var n=e.ownerDocument,r=n.documentElement;return t.top-r.clientTop}return t.top}function f(e,t,n,r){var o=n-t;return e/=r/2,e<1?o/2*e*e*e+t:o/2*((e-=2)*e*e+2)+t}function d(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},i=r(n(),!0),a=yi.exec(e);if(a){var s=document.getElementById(a[1]);if(s){var l=p(s),u=i+l-t,c=Date.now();mi(function e(){var t=Date.now(),n=t-c;window.scrollTo(window.pageXOffset,f(n,i,u,450)),n<450?mi(e):o()}),history.pushState(null,"",e)}}}function h(e){return void 0===e||null===e?"":e}function v(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e.getAttribute("id")||e.getAttribute("data-reactid")||e.getAttribute("name");if(t&&Ri[n])return Ri[n];var r=window.getComputedStyle(e),o=r.getPropertyValue("box-sizing")||r.getPropertyValue("-moz-box-sizing")||r.getPropertyValue("-webkit-box-sizing"),i=parseFloat(r.getPropertyValue("padding-bottom"))+parseFloat(r.getPropertyValue("padding-top")),a=parseFloat(r.getPropertyValue("border-bottom-width"))+parseFloat(r.getPropertyValue("border-top-width")),s=ji.map(function(e){return e+":"+r.getPropertyValue(e)}).join(";"),l={sizingStyle:s,paddingSize:i,borderSize:a,boxSizing:o};return t&&n&&(Ri[n]=l),l}function m(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;Li||(Li=document.createElement("textarea"),document.body.appendChild(Li)),e.getAttribute("wrap")?Li.setAttribute("wrap",e.getAttribute("wrap")):Li.removeAttribute("wrap");var o=v(e,t),i=o.paddingSize,a=o.borderSize,s=o.boxSizing,l=o.sizingStyle;Li.setAttribute("style",l+";"+Ai),Li.value=e.value||e.placeholder||"";var u=Number.MIN_SAFE_INTEGER,c=Number.MAX_SAFE_INTEGER,p=Li.scrollHeight,f=void 0;if("border-box"===s?p+=a:"content-box"===s&&(p-=i),null!==n||null!==r){Li.value=" ";var d=Li.scrollHeight-i;null!==n&&(u=d*n,"border-box"===s&&(u=u+i+a),p=Math.max(u,p)),null!==r&&(c=d*r,"border-box"===s&&(c=c+i+a),f=p>c?"":"hidden",p=Math.min(c,p))}return r||(f="hidden"),{height:p,minHeight:u,maxHeight:c,overflowY:f}}function y(e){return window.requestAnimationFrame?window.requestAnimationFrame(e):window.setTimeout(e,1)}function g(e){window.cancelAnimationFrame?window.cancelAnimationFrame(e):window.clearTimeout(e)}function b(e){return e&&e.type&&(e.type.isSelectOption||e.type.isSelectOptGroup)}function C(){}function w(){}function S(){return window}function x(e){return e?e.toString().split("").reverse().map(function(e){return Number(e)}):[]}function _(e,t){if(!e.breadcrumbName)return null;var n=Object.keys(t).join("|");return e.breadcrumbName.replace(new RegExp(":("+n+")","g"),function(e,n){return t[n]||e})}function k(e,t,n,r){var o=n.indexOf(e)===n.length-1,i=_(e,t);return o?Jo.createElement("span",null,i):Jo.createElement("a",{href:"#/"+r.join("/")},i)}function E(e){var t=ma()();return t.locale(e.locale()).utcOffset(e.utcOffset()),t}function O(e){return e.format("LL")}function T(e){return O(E(e))}function N(e){var t=e.locale();return e.localeData()["zh-cn"===t?"months":"monthsShort"](e)}function P(e,t){ma.a.isMoment(e)&&ma.a.isMoment(t)&&(t.hour(e.hour()),t.minute(e.minute()),t.second(e.second()))}function M(e,t){var n=t?t(e):{};return n=Vo()({},Sa,n)}function D(e,t){var n=!1;if(e){var r=e.hour(),o=e.minute(),i=e.second();if(-1===t.disabledHours().indexOf(r)){if(-1===t.disabledMinutes(r).indexOf(o)){n=-1!==t.disabledSeconds(r,o).indexOf(i)}else n=!0}else n=!0}return!n}function I(e,t){return D(e,M(e,t))}function A(e,t,n){return(!t||!t(e))&&!(n&&!I(e,n))}function j(e,t){return e&&t&&e.isSame(t,"day")}function R(e,t){return e.year()<t.year()?1:e.year()===t.year()&&e.month()<t.month()}function L(e,t){return e.year()>t.year()?1:e.year()===t.year()&&e.month()>t.month()}function K(e){return"rc-calendar-"+e.year()+"-"+e.month()+"-"+e.date()}function F(e){var t=this.state.value.clone();t.month(e),this.setAndSelectValue(t)}function V(){}function z(){}function B(){return ma()()}function W(e){return e?E(e):B()}function H(){}function U(){}function q(e){return e.default||e}function Y(){return null}function G(e){return e<10?"0"+e:""+e}function X(e){var t=[];return Zo.a.Children.forEach(e,function(e){e&&t.push(e)}),t}function $(e,t){for(var n=X(e),r=0;r<n.length;r++)if(n[r].key===t)return r;return-1}function J(e,t){e.transform=t,e.webkitTransform=t,e.mozTransform=t}function Z(e){return"transform"in e||"webkitTransform"in e||"MozTransform"in e}function Q(e){return{transform:e,WebkitTransform:e,MozTransform:e}}function ee(e){return"left"===e||"right"===e}function te(e,t){return(ee(t)?"translateY":"translateX")+"("+100*-e+"%) translateZ(0)"}function ne(e,t){var n=ee(t)?"marginTop":"marginLeft";return Ko()({},n,100*-e+"%")}function re(e){return Object.keys(e).reduce(function(t,n){return"aria-"!==n.substr(0,5)&&"data-"!==n.substr(0,5)&&"role"!==n||(t[n]=e[n]),t},{})}function oe(){}function ie(e){var t=void 0;return Zo.a.Children.forEach(e.children,function(e){!e||t||e.props.disabled||(t=e.key)}),t}function ae(e,t){return Zo.a.Children.map(e.children,function(e){return e&&e.key}).indexOf(t)>=0}function se(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function le(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0;var s=o.defaultView||o.parentWindow;return n+=se(s),r+=se(s,!0),{left:n,top:r}}function ue(e,t){var n=e.props.styles,r=e.nav||e.root,o=le(r),i=e.inkBar,a=e.activeTab,s=i.style,l=e.props.tabBarPosition;if(t&&(s.display="none"),a){var u=a,c=le(u),p=Z(s);if("top"===l||"bottom"===l){var f=c.left-o.left,d=u.offsetWidth;d===r.offsetWidth?d=0:n.inkBar&&void 0!==n.inkBar.width&&(d=parseFloat(n.inkBar.width,10))&&(f+=(u.offsetWidth-d)/2),p?(J(s,"translate3d("+f+"px,0,0)"),s.width=d+"px",s.height=""):(s.left=f+"px",s.top="",s.bottom="",s.right=r.offsetWidth-f-d+"px")}else{var h=c.top-o.top,v=u.offsetHeight;n.inkBar&&void 0!==n.inkBar.height&&(v=parseFloat(n.inkBar.height,10))&&(h+=(u.offsetHeight-v)/2),p?(J(s,"translate3d(0,"+h+"px,0)"),s.height=v+"px",s.width=""):(s.left="",s.right="",s.top=h+"px",s.bottom=r.offsetHeight-h-v+"px")}}s.display=a?"block":"none"}function ce(){if("undefined"!=typeof window&&window.document&&window.document.documentElement){var e=window.document.documentElement;return"flex"in e.style||"webkitFlex"in e.style||"Flex"in e.style||"msFlex"in e.style}return!1}function pe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function de(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function he(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function ve(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function me(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ye(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function ge(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function be(e,t,n,r){var o=void 0;return Object(Ts.a)(e,n,{start:function(){t?(o=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?o:0)+"px"},end:function(){e.style.height="",r()}})}function Ce(e){return{enter:function(t,n){return be(t,!0,e+"-anim",n)},leave:function(t,n){return be(t,!1,e+"-anim",n)}}}function we(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Se(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function xe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _e(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function ke(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function Ee(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}function Oe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Te(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function Ne(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function Pe(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function Me(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function De(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function Ie(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function Ae(e,t,n){return e.split(t).map(function(e,r){return 0===r?e:[Jo.createElement("span",{className:n+"-menu-item-keyword",key:"seperator"},t),e]})}function je(e,t){return t.some(function(t){return t.label.indexOf(e)>-1})}function Re(e,t,n){return t.map(function(t,r){var o=t.label,i=o.indexOf(e)>-1?Ae(o,e,n):o;return 0===r?i:[" / ",i]})}function Le(e,t,n){function r(e){return e.label.indexOf(n)>-1}return e.findIndex(r)-t.findIndex(r)}function Ke(e){return e}function Fe(e){return Zo.a.Children.map(e,Ke)}function Ve(e){var t=this.state.value.clone();t.add(e,"year"),this.setAndChangeValue(t)}function ze(){}function Be(e){var t=this.state.value.clone();t.add(e,"year"),this.setState({value:t})}function We(e){var t=this.state.value.clone();t.year(e),t.month(this.state.value.month()),this.props.onSelect(t)}function He(e){var t=this.state.value.clone();t.add(e,"years"),this.setState({value:t})}function Ue(e,t){var n=this.state.value.clone();n.year(e),n.month(this.state.value.month()),this.props.onSelect(n),t.preventDefault()}function qe(e){var t=this.props.value.clone();t.add(e,"months"),this.props.onValueChange(t)}function Ye(e){var t=this.props.value.clone();t.add(e,"years"),this.props.onValueChange(t)}function Ge(e,t){return e?t:null}function Xe(e){var t=e.prefixCls,n=e.locale,r=e.value,o=e.timePicker,i=e.disabled,a=e.disabledDate,s=e.onToday,l=e.text,u=(!l&&o?n.now:l)||n.today,c=a&&!A(E(r),a),p=c||i,f=p?t+"-today-btn-disabled":"";return Zo.a.createElement("a",{className:t+"-today-btn "+f,role:"button",onClick:p?null:s,title:T(r)},u)}function $e(e){var t=e.prefixCls,n=e.locale,r=e.okDisabled,o=e.onOk,i=t+"-ok-btn";return r&&(i+=" "+t+"-ok-btn-disabled"),Zo.a.createElement("a",{className:i,role:"button",onClick:r?null:o},n.ok)}function Je(e){var t,n=e.prefixCls,r=e.locale,o=e.showTimePicker,i=e.onOpenTimePicker,a=e.onCloseTimePicker,s=e.timePickerDisabled,l=ii()((t={},t[n+"-time-picker-btn"]=!0,t[n+"-time-picker-btn-disabled"]=s,t)),u=null;return s||(u=o?a:i),Zo.a.createElement("a",{className:l,role:"button",onClick:u},o?r.dateSelect:r.timeSelect)}function Ze(){}function Qe(){var e=this.state.value.clone();e.startOf("month"),this.setValue(e)}function et(){var e=this.state.value.clone();e.endOf("month"),this.setValue(e)}function tt(e,t){var n=this.state.value.clone();n.add(e,t),this.setValue(n)}function nt(e){return tt.call(this,e,"months")}function rt(e){return tt.call(this,e,"years")}function ot(e){return tt.call(this,e,"weeks")}function it(e){return tt.call(this,e,"days")}function at(){}function st(e,t){this[e]=t}function lt(e){return t=function(t){function n(e){Bo()(this,n);var t=qo()(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));t.renderFooter=function(){var e=t.props,n=e.prefixCls,r=e.renderExtraFooter;return r?Jo.createElement("div",{className:n+"-footer-extra"},r.apply(void 0,arguments)):null},t.clearSelection=function(e){e.preventDefault(),e.stopPropagation(),t.handleChange(null)},t.handleChange=function(e){var n=t.props;"value"in n||t.setState({value:e,showDate:e}),n.onChange(e,e&&e.format(n.format)||"")},t.handleCalendarChange=function(e){t.setState({showDate:e})},t.saveInput=function(e){t.input=e};var r=e.value||e.defaultValue;if(r&&!q(va).isMoment(r))throw new Error("The value/defaultValue of DatePicker or MonthPicker must be a moment object after `[email protected]`, see: https://u.ant.design/date-picker-value");return t.state={value:r,showDate:r},t}return Go()(n,t),Ho()(n,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value,showDate:e.value})}},{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"render",value:function(){var t,n=this,r=this.state,o=r.value,i=r.showDate,a=Object(li.a)(this.props,["onChange"]),s=a.prefixCls,l=a.locale,u=a.localeCode,c="placeholder"in a?a.placeholder:l.lang.placeholder,p=a.showTime?a.disabledTime:null,f=ii()((t={},Ko()(t,s+"-time",a.showTime),Ko()(t,s+"-month",Vl===e),t));o&&u&&o.locale(u);var d={},h={};a.showTime?h={onSelect:this.handleChange}:d={onChange:this.handleChange},"mode"in a&&(h.mode=a.mode),Object(aa.a)(!("onOK"in a),"It should be `DatePicker[onOk]` or `MonthPicker[onOk]`, instead of `onOK`!");var v=Jo.createElement(e,Vo()({},h,{disabledDate:a.disabledDate,disabledTime:p,locale:l.lang,timePicker:a.timePicker,defaultValue:a.defaultPickerValue||q(va)(),dateInputPlaceholder:c,prefixCls:s,className:f,onOk:a.onOk,dateRender:a.dateRender,format:a.format,showToday:a.showToday,monthCellContentRender:a.monthCellContentRender,renderFooter:this.renderFooter,onPanelChange:a.onPanelChange,onChange:this.handleCalendarChange,value:i})),m=!a.disabled&&a.allowClear&&o?Jo.createElement(Ni.a,{type:"cross-circle",className:s+"-picker-clear",onClick:this.clearSelection}):null,y=function(e){var t=e.value;return Jo.createElement("div",null,Jo.createElement("input",{ref:n.saveInput,disabled:a.disabled,readOnly:!0,value:t&&t.format(a.format)||"",placeholder:c,className:a.pickerInputClass}),m,Jo.createElement("span",{className:s+"-picker-icon"}))};return Jo.createElement("span",{id:a.id,className:ii()(a.className,a.pickerClass),style:a.style,onFocus:a.onFocus,onBlur:a.onBlur},Jo.createElement(Yl,Vo()({},a,d,{calendar:v,value:o,prefixCls:s+"-picker-container",style:a.popupStyle}),y))}}]),n}(Jo.Component),t.defaultProps={prefixCls:"ant-calendar",allowClear:!0,showToday:!0},t;var t}function ut(){}function ct(e,t,n){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,o=[],i=0;i<e;i+=r)(!t||t.indexOf(i)<0||!n)&&o.push(i);return o}function pt(){}function ft(e,t){this[e]=t}function dt(e){return{showHour:e.indexOf("H")>-1||e.indexOf("h")>-1||e.indexOf("k")>-1,showMinute:e.indexOf("m")>-1,showSecond:e.indexOf("s")>-1}}function ht(e){var t=e.showHour,n=e.showMinute,r=e.showSecond,o=e.use12Hours,i=0;return t&&(i+=1),n&&(i+=1),r&&(i+=1),o&&(i+=1),i}function vt(e,t){return n=function(t){function n(){Bo()(this,n);var t=qo()(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments));return t.handleOpenChange=function(e){(0,t.props.onOpenChange)(e)},t.handleFocus=function(e){var n=t.props.onFocus;n&&n(e)},t.handleBlur=function(e){var n=t.props.onBlur;n&&n(e)},t.savePicker=function(e){t.picker=e},t.getDefaultLocale=function(){var e=Vo()({},vu.a,t.props.locale);return e.lang=Vo()({},e.lang,(t.props.locale||{}).lang),e},t.renderPicker=function(n,r){var o,i=t.props,a=i.prefixCls,s=i.inputPrefixCls,l=ii()(a+"-picker",Ko()({},a+"-picker-"+i.size,!!i.size)),u=ii()(a+"-picker-input",s,(o={},Ko()(o,s+"-lg","large"===i.size),Ko()(o,s+"-sm","small"===i.size),Ko()(o,s+"-disabled",i.disabled),o)),c=i.showTime&&i.showTime.format||"HH:mm:ss",p=Vo()({},dt(c),{format:c,use12Hours:i.showTime&&i.showTime.use12Hours}),f=ht(p),d=a+"-time-picker-column-"+f,h=i.showTime?Jo.createElement(ou,Vo()({},p,i.showTime,{prefixCls:a+"-time-picker",className:d,placeholder:n.timePickerLocale.placeholder,transitionName:"slide-up"})):null;return Jo.createElement(e,Vo()({},i,{ref:t.savePicker,pickerClass:l,pickerInputClass:u,locale:n,localeCode:r,timePicker:h,onOpenChange:t.handleOpenChange,onFocus:t.handleFocus,onBlur:t.handleBlur}))},t}return Go()(n,t),Ho()(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.autoFocus,n=e.disabled;t&&!n&&this.focus()}},{key:"focus",value:function(){this.picker.focus()}},{key:"blur",value:function(){this.picker.blur()}},{key:"render",value:function(){return Jo.createElement(La.a,{componentName:"DatePicker",defaultLocale:this.getDefaultLocale},this.renderPicker)}}]),n}(Jo.Component),n.defaultProps={format:t||"YYYY-MM-DD",transitionName:"slide-up",popupStyle:{},onChange:function(){},onOk:function(){},onOpenChange:function(){},locale:{},prefixCls:"ant-calendar",inputPrefixCls:"ant-input"},n;var n}function mt(){}function yt(e){return Array.isArray(e)&&(0===e.length||e.every(function(e){return!e}))}function gt(e,t){if(e===t)return!0;if(null===e||void 0===e||null===t||void 0===t)return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}function bt(e){var t=e[0],n=e[1];return[t,n&&n.isSame(t,"month")?n.clone().add(1,"month"):n]}function Ct(e,t){var n=e.selectedValue||t&&e.defaultSelectedValue,r=e.value||t&&e.defaultValue,o=bt(r?r:n);return yt(o)?t&&[ma()(),ma()().add(1,"months")]:o}function wt(e,t){for(var n=t?t().concat():[],r=0;r<e;r++)-1===n.indexOf(r)&&n.push(r);return n}function St(e,t){if(t){var n=this.state.selectedValue,r=n.concat(),o="left"===e?0:1;r[o]=t,r[0]&&this.compare(r[0],r[1])>0&&(r[1-o]=this.state.showTimePicker?r[o]:void 0),this.props.onInputSelect(r),this.fireSelectValueChange(r)}}function xt(e){var t=ha()(e,2),n=t[0],r=t[1];if(n||r){return[n,r&&r.isSame(n,"month")?r.clone().add(1,"month"):r]}}function _t(e,t){return e&&e.format(t)||""}function kt(e){if(e)return Array.isArray(e)?e:[e,e.clone().add(1,"month")]}function Et(e){return!!Array.isArray(e)&&(0===e.length||e.every(function(e){return!e}))}function Ot(e,t){t&&e&&0!==e.length&&(e[0]&&e[0].locale(t),e[1]&&e[1].locale(t))}function Tt(e,t){return e&&e.format(t)||""}function Nt(e){var t,n=e.prefixCls,r=void 0===n?"ant":n,o=e.type,i=void 0===o?"horizontal":o,a=e.orientation,s=void 0===a?"":a,l=e.className,u=e.children,c=e.dashed,p=Ou(e,["prefixCls","type","orientation","className","children","dashed"]),f=s.length>0?"-"+s:s,d=ii()(l,r+"-divider",r+"-divider-"+i,(t={},Ko()(t,r+"-divider-with-text"+f,u),Ko()(t,r+"-divider-dashed",!!c),t));return Jo.createElement("div",Vo()({className:d},p),u&&Jo.createElement("span",{className:r+"-divider-inner-text"},u))}function Pt(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=1,o=t[0],i=t.length;if("function"==typeof o)return o.apply(null,t.slice(1));if("string"==typeof o){for(var a=String(o).replace(Iu,function(e){if("%%"===e)return"%";if(r>=i)return e;switch(e){case"%s":return String(t[r++]);case"%d":return Number(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch(e){return"[Circular]"}break;default:return e}}),s=t[r];r<i;s=t[++r])a+=" "+s;return a}return o}function Mt(e){return"string"===e||"url"===e||"hex"===e||"email"===e||"pattern"===e}function Dt(e,t){return void 0===e||null===e||(!("array"!==t||!Array.isArray(e)||e.length)||!(!Mt(t)||"string"!=typeof e||e))}function It(e,t,n){function r(e){o.push.apply(o,e),++i===a&&n(o)}var o=[],i=0,a=e.length;e.forEach(function(e){t(e,r)})}function At(e,t,n){function r(a){if(a&&a.length)return void n(a);var s=o;o+=1,s<i?t(e[s],r):n([])}var o=0,i=e.length;r([])}function jt(e){var t=[];return Object.keys(e).forEach(function(n){t.push.apply(t,e[n])}),t}function Rt(e,t,n,r){if(t.first){return At(jt(e),n,r)}var o=t.firstFields||[];!0===o&&(o=Object.keys(e));var i=Object.keys(e),a=i.length,s=0,l=[],u=function(e){l.push.apply(l,e),++s===a&&r(l)};i.forEach(function(t){var r=e[t];-1!==o.indexOf(t)?At(r,n,u):It(r,n,u)})}function Lt(e){return function(t){return t&&t.message?(t.field=t.field||e.fullField,t):{message:t,field:t.field||e.fullField}}}function Kt(e,t){if(t)for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];"object"===(void 0===r?"undefined":$o()(r))&&"object"===$o()(e[n])?e[n]=Vo()({},e[n],r):e[n]=r}return e}function Ft(e,t,n,r,o,i){!e.required||n.hasOwnProperty(e.field)&&!Dt(t,i||e.type)||r.push(Pt(o.messages.required,e.fullField))}function Vt(e,t,n,r,o){(/^\s+$/.test(t)||""===t)&&r.push(Pt(o.messages.whitespace,e.fullField))}function zt(e,t,n,r,o){if(e.required&&void 0===t)return void ju(e,t,n,r,o);var i=["integer","float","array","regexp","object","method","email","number","date","url","hex"],a=e.type;i.indexOf(a)>-1?Ku[a](t)||r.push(Pt(o.messages.types[a],e.fullField,e.type)):a&&(void 0===t?"undefined":$o()(t))!==e.type&&r.push(Pt(o.messages.types[a],e.fullField,e.type))}function Bt(e,t,n,r,o){var i="number"==typeof e.len,a="number"==typeof e.min,s="number"==typeof e.max,l=t,u=null,c="number"==typeof t,p="string"==typeof t,f=Array.isArray(t);if(c?u="number":p?u="string":f&&(u="array"),!u)return!1;(p||f)&&(l=t.length),i?l!==e.len&&r.push(Pt(o.messages[u].len,e.fullField,e.len)):a&&!s&&l<e.min?r.push(Pt(o.messages[u].min,e.fullField,e.min)):s&&!a&&l>e.max?r.push(Pt(o.messages[u].max,e.fullField,e.max)):a&&s&&(l<e.min||l>e.max)&&r.push(Pt(o.messages[u].range,e.fullField,e.min,e.max))}function Wt(e,t,n,r,o){e[zu]=Array.isArray(e[zu])?e[zu]:[],-1===e[zu].indexOf(t)&&r.push(Pt(o.messages[zu],e.fullField,e[zu].join(", ")))}function Ht(e,t,n,r,o){if(e.pattern)if(e.pattern instanceof RegExp)e.pattern.lastIndex=0,e.pattern.test(t)||r.push(Pt(o.messages.pattern.mismatch,e.fullField,t,e.pattern));else if("string"==typeof e.pattern){var i=new RegExp(e.pattern);i.test(t)||r.push(Pt(o.messages.pattern.mismatch,e.fullField,t,e.pattern))}}function Ut(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t,"string")&&!e.required)return n();Hu.required(e,t,r,i,o,"string"),Dt(t,"string")||(Hu.type(e,t,r,i,o),Hu.range(e,t,r,i,o),Hu.pattern(e,t,r,i,o),!0===e.whitespace&&Hu.whitespace(e,t,r,i,o))}n(i)}function qt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),void 0!==t&&Hu.type(e,t,r,i,o)}n(i)}function Yt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),void 0!==t&&(Hu.type(e,t,r,i,o),Hu.range(e,t,r,i,o))}n(i)}function Gt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),void 0!==t&&Hu.type(e,t,r,i,o)}n(i)}function Xt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),Dt(t)||Hu.type(e,t,r,i,o)}n(i)}function $t(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),void 0!==t&&(Hu.type(e,t,r,i,o),Hu.range(e,t,r,i,o))}n(i)}function Jt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),void 0!==t&&(Hu.type(e,t,r,i,o),Hu.range(e,t,r,i,o))}n(i)}function Zt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t,"array")&&!e.required)return n();Hu.required(e,t,r,i,o,"array"),Dt(t,"array")||(Hu.type(e,t,r,i,o),Hu.range(e,t,r,i,o))}n(i)}function Qt(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),void 0!==t&&Hu.type(e,t,r,i,o)}n(i)}function en(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),t&&Hu[ec](e,t,r,i,o)}n(i)}function tn(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t,"string")&&!e.required)return n();Hu.required(e,t,r,i,o),Dt(t,"string")||Hu.pattern(e,t,r,i,o)}n(i)}function nn(e,t,n,r,o){var i=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t)&&!e.required)return n();Hu.required(e,t,r,i,o),Dt(t)||(Hu.type(e,t,r,i,o),t&&Hu.range(e,t.getTime(),r,i,o))}n(i)}function rn(e,t,n,r,o){var i=[],a=Array.isArray(t)?"array":void 0===t?"undefined":$o()(t);Hu.required(e,t,r,i,o,a),n(i)}function on(e,t,n,r,o){var i=e.type,a=[];if(e.required||!e.required&&r.hasOwnProperty(e.field)){if(Dt(t,i)&&!e.required)return n();Hu.required(e,t,r,a,o,i),Dt(t,i)||Hu.type(e,t,r,a,o)}n(a)}function an(){return{default:"Validation error on field %s",required:"%s is required",enum:"%s must be one of %s",whitespace:"%s cannot be empty",date:{format:"%s date %s is invalid for format %s",parse:"%s date could not be parsed, %s is invalid ",invalid:"%s date %s is invalid"},types:{string:"%s is not a %s",method:"%s is not a %s (function)",array:"%s is not an %s",object:"%s is not an %s",number:"%s is not a %s",date:"%s is not a %s",boolean:"%s is not a %s",integer:"%s is not an %s",float:"%s is not a %s",regexp:"%s is not a valid %s",email:"%s is not a valid %s",url:"%s is not a valid %s",hex:"%s is not a valid %s"},string:{len:"%s must be exactly %s characters",min:"%s must be at least %s characters",max:"%s cannot be longer than %s characters",range:"%s must be between %s and %s characters"},number:{len:"%s must equal %s",min:"%s cannot be less than %s",max:"%s cannot be greater than %s",range:"%s must be between %s and %s"},array:{len:"%s must be exactly %s in length",min:"%s cannot be less than %s in length",max:"%s cannot be greater than %s in length",range:"%s must be between %s and %s in length"},pattern:{mismatch:"%s value %s does not match pattern %s"},clone:function(){var e=JSON.parse(JSON.stringify(this));return e.clone=this.clone,e}}}function sn(e){this.rules=null,this._messages=sc,this.define(e)}function ln(e){return e instanceof dc}function un(e){return ln(e)?e:new dc(e)}function cn(e){return e.displayName||e.name||"WrappedComponent"}function pn(e,t){return e.displayName="Form("+cn(t)+")",e.WrappedComponent=t,vc()(e,t)}function fn(e){return e}function dn(e){return Array.prototype.concat.apply([],e)}function hn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments[1],n=arguments[2],r=arguments[3],o=arguments[4];if(n(e,t))o(e,t);else{if(void 0===t)return;if(Array.isArray(t))t.forEach(function(t,i){return hn(e+"["+i+"]",t,n,r,o)});else{if("object"!==(void 0===t?"undefined":$o()(t)))return void console.error(r);Object.keys(t).forEach(function(i){var a=t[i];hn(e+(e?".":"")+i,a,n,r,o)})}}}function vn(e,t,n){var r={};return hn(void 0,e,t,n,function(e,t){r[e]=t}),r}function mn(e,t,n){var r=e.map(function(e){var t=Vo()({},e,{trigger:e.trigger||[]});return"string"==typeof t.trigger&&(t.trigger=[t.trigger]),t});return t&&r.push({trigger:n?[].concat(n):[],rules:t}),r}function yn(e){return e.filter(function(e){return!!e.rules&&e.rules.length}).map(function(e){return e.trigger}).reduce(function(e,t){return e.concat(t)},[])}function gn(e){if(!e||!e.target)return e;var t=e.target;return"checkbox"===t.type?t.checked:t.value}function bn(e){return e?e.map(function(e){return e&&e.message?e.message:e}):e}function Cn(e,t,n){var r=e,o=t,i=n;return void 0===n&&("function"==typeof r?(i=r,o={},r=void 0):Array.isArray(r)?"function"==typeof o?(i=o,o={}):o=o||{}:(i=o,o=r||{},r=void 0)),{names:r,options:o,callback:i}}function wn(e){return 0===Object.keys(e).length}function Sn(e){return!!e&&e.some(function(e){return e.rules&&e.rules.length})}function xn(e,t){return 0===e.lastIndexOf(t,0)}function _n(e,t){return 0===t.indexOf(e)&&-1!==[".","["].indexOf(t[e.length])}function kn(e){return new mc(e)}function En(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=e.validateMessages,r=e.onFieldsChange,o=e.onValuesChange,i=e.mapProps,a=void 0===i?fn:i,s=e.mapPropsToFields,l=e.fieldNameProp,u=e.fieldMetaProp,c=e.fieldDataProp,p=e.formPropName,f=void 0===p?"form":p,d=e.withRef;return function(e){return pn(ga()({displayName:"Form",mixins:t,getInitialState:function(){var e=this,t=s&&s(this.props);return this.fieldsStore=kn(t||{}),this.instances={},this.cachedBind={},this.clearedFieldMetaCache={},["getFieldsValue","getFieldValue","setFieldsInitialValue","getFieldsError","getFieldError","isFieldValidating","isFieldsValidating","isFieldsTouched","isFieldTouched"].forEach(function(t){return e[t]=function(){var n;return(n=e.fieldsStore)[t].apply(n,arguments)}}),{submitting:!1}},componentWillReceiveProps:function(e){s&&this.fieldsStore.updateFields(s(e))},onCollectCommon:function(e,t,n){var r=this.fieldsStore.getFieldMeta(e);if(r[t])r[t].apply(r,ci()(n));else if(r.originalProps&&r.originalProps[t]){var i;(i=r.originalProps)[t].apply(i,ci()(n))}var a=r.getValueFromEvent?r.getValueFromEvent.apply(r,ci()(n)):gn.apply(void 0,ci()(n));if(o&&a!==this.fieldsStore.getFieldValue(e)){var s=this.fieldsStore.getAllValues(),l={};s[e]=a,Object.keys(s).forEach(function(e){return fc()(l,e,s[e])}),o(this.props,fc()({},e,a),l)}var u=this.fieldsStore.getField(e);return{name:e,field:Vo()({},u,{value:a,touched:!0}),fieldMeta:r}},onCollect:function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];var i=this.onCollectCommon(e,t,r),a=i.name,s=i.field,l=i.fieldMeta,u=l.validate,c=Vo()({},s,{dirty:Sn(u)});this.setFields(Ko()({},a,c))},onCollectValidate:function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];var i=this.onCollectCommon(e,t,r),a=i.field,s=i.fieldMeta,l=Vo()({},a,{dirty:!0});this.validateFieldsInternal([l],{action:t,options:{firstFields:!!s.validateFirst}})},getCacheBind:function(e,t,n){this.cachedBind[e]||(this.cachedBind[e]={});var r=this.cachedBind[e];return r[t]||(r[t]=n.bind(this,e,t)),r[t]},recoverClearedField:function(e){this.clearedFieldMetaCache[e]&&(this.fieldsStore.setFields(Ko()({},e,this.clearedFieldMetaCache[e].field)),this.fieldsStore.setFieldMeta(e,this.clearedFieldMetaCache[e].meta),delete this.clearedFieldMetaCache[e])},getFieldDecorator:function(e,t){var n=this,r=this.getFieldProps(e,t);return function(t){var o=n.fieldsStore.getFieldMeta(e),i=t.props;return o.originalProps=i,o.ref=t.ref,Zo.a.cloneElement(t,Vo()({},r,n.fieldsStore.getFieldValuePropValue(o)))}},getFieldProps:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)throw new Error("Must call `getFieldProps` with valid name string!");delete this.clearedFieldMetaCache[e];var r=Vo()({name:e,trigger:gc,valuePropName:"value",validate:[]},n),o=r.rules,i=r.trigger,a=r.validateTrigger,s=void 0===a?i:a,p=r.validate,f=this.fieldsStore.getFieldMeta(e);"initialValue"in r&&(f.initialValue=r.initialValue);var d=Vo()({},this.fieldsStore.getFieldValuePropValue(r),{ref:this.getCacheBind(e,e+"__ref",this.saveRef)});l&&(d[l]=e);var h=mn(p,o,s),v=yn(h);v.forEach(function(n){d[n]||(d[n]=t.getCacheBind(e,n,t.onCollectValidate))}),i&&-1===v.indexOf(i)&&(d[i]=this.getCacheBind(e,i,this.onCollect));var m=Vo()({},f,r,{validate:h});return this.fieldsStore.setFieldMeta(e,m),u&&(d[u]=m),c&&(d[c]=this.fieldsStore.getField(e)),d},getFieldInstance:function(e){return this.instances[e]},getRules:function(e,t){return dn(e.validate.filter(function(e){return!t||e.trigger.indexOf(t)>=0}).map(function(e){return e.rules}))},setFields:function(e){var t=this,n=this.fieldsStore.flattenRegisteredFields(e);if(this.fieldsStore.setFields(n),r){var o=Object.keys(n).reduce(function(e,n){return fc()(e,n,t.fieldsStore.getField(n))},{});r(this.props,o,this.fieldsStore.getNestedAllFields())}this.forceUpdate()},resetFields:function(e){var t=this,n=this.fieldsStore.resetFields(e);if(Object.keys(n).length>0&&this.setFields(n),e){(Array.isArray(e)?e:[e]).forEach(function(e){return delete t.clearedFieldMetaCache[e]})}else this.clearedFieldMetaCache={}},setFieldsValue:function(e){var t=this.fieldsStore.fieldsMeta,n=this.fieldsStore.flattenRegisteredFields(e),r=Object.keys(n).reduce(function(e,r){var o=t[r];if(o){var i=n[r];e[r]={value:i}}return e},{});if(this.setFields(r),o){var i=this.fieldsStore.getAllValues();o(this.props,e,i)}},saveRef:function(e,t,n){if(!n)return this.clearedFieldMetaCache[e]={field:this.fieldsStore.getField(e),meta:this.fieldsStore.getFieldMeta(e)},this.fieldsStore.clearField(e),delete this.instances[e],void delete this.cachedBind[e];this.recoverClearedField(e);var r=this.fieldsStore.getFieldMeta(e);if(r){var o=r.ref;if(o){if("string"==typeof o)throw new Error("can not set ref string for "+e);o(n)}}this.instances[e]=n},validateFieldsInternal:function(e,t,r){var o=this,i=t.fieldNames,a=t.action,s=t.options,l=void 0===s?{}:s,u={},c={},p={},f={};if(e.forEach(function(e){var t=e.name;if(!0!==l.force&&!1===e.dirty)return void(e.errors&&fc()(f,t,{errors:e.errors}));var n=o.fieldsStore.getFieldMeta(t),r=Vo()({},e);r.errors=void 0,r.validating=!0,r.dirty=!0,u[t]=o.getRules(n,a),c[t]=r.value,p[t]=r}),this.setFields(p),Object.keys(c).forEach(function(e){c[e]=o.fieldsStore.getFieldValue(e)}),r&&wn(p))return void r(wn(f)?null:f,this.fieldsStore.getFieldsValue(i));var d=new lc(u);n&&d.messages(n),d.validate(c,l,function(e){var t=Vo()({},f);e&&e.length&&e.forEach(function(e){var n=e.field;Du()(t,n)||fc()(t,n,{errors:[]}),cc()(t,n.concat(".errors")).push(e)});var n=[],a={};Object.keys(u).forEach(function(e){var r=cc()(t,e),i=o.fieldsStore.getField(e);i.value!==c[e]?n.push({name:e}):(i.errors=r&&r.errors,i.value=c[e],i.validating=!1,i.dirty=!1,a[e]=i)}),o.setFields(a),r&&(n.length&&n.forEach(function(e){var n=e.name,r=[{message:n+" need to revalidate",field:n}];fc()(t,n,{expired:!0,errors:r})}),r(wn(t)?null:t,o.fieldsStore.getFieldsValue(i)))})},validateFields:function(e,t,n){var r=this,o=Cn(e,t,n),i=o.names,a=o.callback,s=o.options,l=i?this.fieldsStore.getValidFieldsFullName(i):this.fieldsStore.getValidFieldsName(),u=l.filter(function(e){return Sn(r.fieldsStore.getFieldMeta(e).validate)}).map(function(e){var t=r.fieldsStore.getField(e);return t.value=r.fieldsStore.getFieldValue(e),t});if(!u.length)return void(a&&a(null,this.fieldsStore.getFieldsValue(l)));"firstFields"in s||(s.firstFields=l.filter(function(e){return!!r.fieldsStore.getFieldMeta(e).validateFirst})),this.validateFieldsInternal(u,{fieldNames:l,options:s},a)},isSubmitting:function(){return this.state.submitting},submit:function(e){var t=this,n=function(){t.setState({submitting:!1})};this.setState({submitting:!0}),e(n)},render:function(){var t=this.props,n=t.wrappedComponentRef,r=$a()(t,["wrappedComponentRef"]),o=Ko()({},f,this.getForm());d?o.ref="wrappedComponent":n&&(o.ref=n);var i=a.call(this,Vo()({},o,r));return Zo.a.createElement(e,i)}}),e)}}function On(e,t){var n=window.getComputedStyle,r=n?n(e):e.currentStyle;if(r)return r[t.replace(/-(\w)/gi,function(e,t){return t.toUpperCase()})]}function Tn(e){for(var t=e,n=void 0;"body"!==(n=t.nodeName.toLowerCase());){var r=On(t,"overflowY");if(t!==e&&("auto"===r||"scroll"===r)&&t.scrollHeight>t.clientHeight)return t;t=t.parentNode}return"body"===n?t.ownerDocument:t}function Nn(e){return bc(Vo()({},e),[wc])}function Pn(){}function Mn(e){e.preventDefault()}function Dn(e){return e.replace(/[^\w\.-]+/g,"")}function In(e){return function(t){return function(n){function r(){return Bo()(this,r),qo()(this,(r.__proto__||Object.getPrototypeOf(r)).apply(this,arguments))}return Go()(r,n),Ho()(r,[{key:"render",value:function(){var n=e.prefixCls;return Jo.createElement(t,Vo()({prefixCls:n},this.props))}}]),r}(Jo.Component)}}function An(e,t){return e[t]&&Math.floor(24/e[t])}function jn(e){dp=e?Vo()({},dp,e):Vo()({},np.a.Modal)}function Rn(){return dp}function Ln(e){e&&e.locale?va.locale(e.locale):va.locale("en")}function Kn(){return"rcNotification_"+bp+"_"+gp++}function Fn(e){if(kp)return void e(kp);Sp.newInstance({prefixCls:Op,transitionName:Tp,style:{top:_p},getContainer:Np},function(t){if(kp)return void e(kp);kp=t,e(t)})}function Vn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:xp,n=arguments[2],r=arguments[3],o={info:"info-circle",success:"check-circle",error:"cross-circle",warning:"exclamation-circle",loading:"loading"}[n];"function"==typeof t&&(r=t,t=xp);var i=Ep++;return Fn(function(a){a.notice({key:i,duration:t,style:{},content:Jo.createElement("div",{className:Op+"-custom-content "+Op+"-"+n},Jo.createElement(Ni.a,{type:o}),Jo.createElement("span",null,e)),onClose:r})}),function(){kp&&kp.removeNotice(i)}}function zn(e){if(e||void 0===Ap){var t=document.createElement("div");t.style.width="100%",t.style.height="200px";var n=document.createElement("div"),r=n.style;r.position="absolute",r.top=0,r.left=0,r.pointerEvents="none",r.visibility="hidden",r.width="200px",r.height="150px",r.overflow="hidden",n.appendChild(t),document.body.appendChild(n);var o=t.offsetWidth;n.style.overflow="scroll";var i=t.offsetWidth;o===i&&(i=n.clientWidth),document.body.removeChild(n),Ap=o-i}return Ap}function Bn(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function Wn(e,t){var n=e.style;["Webkit","Moz","Ms","ms"].forEach(function(e){n[e+"TransformOrigin"]=t}),n.transformOrigin=t}function Hn(e){var t=e.getBoundingClientRect(),n={left:t.left,top:t.top},r=e.ownerDocument,o=r.defaultView||r.parentWindow;return n.left+=Bn(o),n.top+=Bn(o,!0),n}function Un(e){function t(){for(var o=arguments.length,i=Array(o),a=0;a<o;a++)i[a]=arguments[a];Jp?r(Vo()({},e,{close:t,visible:!1,afterClose:n.bind.apply(n,[this].concat(i))})):n.apply(void 0,i)}function n(){Qo.unmountComponentAtNode(o)&&o.parentNode&&o.parentNode.removeChild(o);for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=n&&n.length&&n.some(function(e){return e&&e.triggerCancel});e.onCancel&&i&&e.onCancel.apply(e,n)}function r(e){Qo.render(Jo.createElement(Zp,e),o)}var o=document.createElement("div");return document.body.appendChild(o),r(Vo()({},e,{visible:!0,close:t})),{destroy:t}}function qn(e){var t=e.duration,n=e.placement,r=e.bottom,o=e.top,i=e.getContainer;void 0!==t&&(tf=t),void 0!==n&&(of=n),void 0!==r&&(rf=r),void 0!==o&&(nf=o),void 0!==i&&(af=i)}function Yn(e){var t=void 0;switch(e){case"topLeft":t={left:0,top:nf,bottom:"auto"};break;case"topRight":t={right:0,top:nf,bottom:"auto"};break;case"bottomLeft":t={left:0,top:"auto",bottom:rf};break;default:t={right:0,top:"auto",bottom:rf}}return t}function Gn(e,t,n){var r=e+"-"+t;if(ef[r])return void n(ef[r]);Sp.newInstance({prefixCls:e,className:e+"-"+t,style:Yn(t),getContainer:af},function(e){ef[r]=e,n(e)})}function Xn(e){var t=e.prefixCls||"ant-notification",n=t+"-notice",r=void 0===e.duration?tf:e.duration,o=null;if(e.icon)o=Jo.createElement("span",{className:n+"-icon"},e.icon);else if(e.type){var i=sf[e.type];o=Jo.createElement(Ni.a,{className:n+"-icon "+n+"-icon-"+e.type,type:i})}var a=!e.description&&o?Jo.createElement("span",{className:n+"-message-single-line-auto-margin"}):null;Gn(t,e.placement||of,function(t){t.notice({content:Jo.createElement("div",{className:o?n+"-with-icon":""},o,Jo.createElement("div",{className:n+"-message"},a,e.message),Jo.createElement("div",{className:n+"-description"},e.description),e.btn?Jo.createElement("span",{className:n+"-btn"},e.btn):null),duration:r,closable:!0,onClose:e.onClose,key:e.key,style:e.style||{},className:e.className})})}function $n(e,t){var n=t?e.pageYOffset:e.pageXOffset,r=t?"scrollTop":"scrollLeft";if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function Jn(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function Zn(e){var t=Jn(e),n=e.ownerDocument,r=n.defaultView||n.parentWindow;return t.left+=$n(r),t.left}function Qn(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function er(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function tr(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function nr(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rr(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function or(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function ir(){}function ar(e,t){return Object.keys(t).some(function(n){return e.target===Object(Qo.findDOMNode)(t[n])})}function sr(e,t){var n=t.min,r=t.max;return e<n||e>r}function lr(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function ur(e,t){var n=t.marks,r=t.step,o=t.min,i=Object.keys(n).map(parseFloat);if(null!==r){var a=Math.round((e-o)/r)*r+o;i.push(a)}var s=i.map(function(t){return Math.abs(e-t)});return i[s.indexOf(Math.min.apply(Math,s))]}function cr(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n}function pr(e,t){return e?t.clientY:t.pageX}function fr(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function dr(e,t){var n=t.getBoundingClientRect();return e?n.top+.5*n.height:n.left+.5*n.width}function hr(e,t){var n=t.max,r=t.min;return e<=r?r:e>=n?n:e}function vr(e,t){var n=t.step,r=ur(e,t);return null===n?r:parseFloat(r.toFixed(cr(n)))}function mr(e){e.stopPropagation(),e.preventDefault()}function yr(e){switch(e.keyCode){case $s.a.UP:case $s.a.RIGHT:return function(e,t){return e+t.step};case $s.a.DOWN:case $s.a.LEFT:return function(e,t){return e-t.step};case $s.a.END:return function(e,t){return t.max};case $s.a.HOME:return function(e,t){return t.min};case $s.a.PAGE_UP:return function(e,t){return e+2*t.step};case $s.a.PAGE_DOWN:return function(e,t){return e-2*t.step};default:return}}function gr(){}function br(e){var t,n;return n=t=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));r.onMouseDown=function(e){if(0===e.button){var t=r.props.vertical,n=pr(t,e);if(ar(e,r.handlesRefs)){var o=dr(t,e.target);r.dragOffset=n-o,n=o}else r.dragOffset=0;r.removeDocumentEvents(),r.onStart(n),r.addDocumentMouseEvents(),mr(e)}},r.onTouchStart=function(e){if(!lr(e)){var t=r.props.vertical,n=fr(t,e);if(ar(e,r.handlesRefs)){var o=dr(t,e.target);r.dragOffset=n-o,n=o}else r.dragOffset=0;r.onStart(n),r.addDocumentTouchEvents(),mr(e)}},r.onFocus=function(e){var t=r.props,n=t.onFocus,o=t.vertical;if(ar(e,r.handlesRefs)){var i=dr(o,e.target);r.dragOffset=0,r.onStart(i),mr(e),n&&n(e)}},r.onBlur=function(e){var t=r.props.onBlur;r.onEnd(e),t&&t(e)},r.onMouseMove=function(e){if(!r.sliderRef)return void r.onEnd();var t=pr(r.props.vertical,e);r.onMove(e,t-r.dragOffset)},r.onTouchMove=function(e){if(lr(e)||!r.sliderRef)return void r.onEnd();var t=fr(r.props.vertical,e);r.onMove(e,t-r.dragOffset)},r.onKeyDown=function(e){r.sliderRef&&ar(e,r.handlesRefs)&&r.onKeyboard(e)},r.saveSlider=function(e){r.sliderRef=e};return r.handlesRefs={},r}return Go()(t,e),t.prototype.componentWillUnmount=function(){e.prototype.componentWillUnmount&&e.prototype.componentWillUnmount.call(this),this.removeDocumentEvents()},t.prototype.componentDidMount=function(){this.document=this.sliderRef&&this.sliderRef.ownerDocument},t.prototype.addDocumentTouchEvents=function(){this.onTouchMoveListener=Object(ri.a)(this.document,"touchmove",this.onTouchMove),this.onTouchUpListener=Object(ri.a)(this.document,"touchend",this.onEnd)},t.prototype.addDocumentMouseEvents=function(){this.onMouseMoveListener=Object(ri.a)(this.document,"mousemove",this.onMouseMove),this.onMouseUpListener=Object(ri.a)(this.document,"mouseup",this.onEnd)},t.prototype.removeDocumentEvents=function(){this.onTouchMoveListener&&this.onTouchMoveListener.remove(),this.onTouchUpListener&&this.onTouchUpListener.remove(),this.onMouseMoveListener&&this.onMouseMoveListener.remove(),this.onMouseUpListener&&this.onMouseUpListener.remove()},t.prototype.focus=function(){this.props.disabled||this.handlesRefs[0].focus()},t.prototype.blur=function(){this.props.disabled||this.handlesRefs[0].blur()},t.prototype.getSliderStart=function(){var e=this.sliderRef,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left},t.prototype.getSliderLength=function(){var e=this.sliderRef;if(!e)return 0;var t=e.getBoundingClientRect();return this.props.vertical?t.height:t.width},t.prototype.calcValue=function(e){var t=this.props,n=t.vertical,r=t.min,o=t.max,i=Math.abs(Math.max(e,0)/this.getSliderLength());return n?(1-i)*(o-r)+r:i*(o-r)+r},t.prototype.calcValueByPos=function(e){var t=e-this.getSliderStart();return this.trimAlignValue(this.calcValue(t))},t.prototype.calcOffset=function(e){var t=this.props,n=t.min;return(e-n)/(t.max-n)*100},t.prototype.saveHandle=function(e,t){this.handlesRefs[e]=t},t.prototype.render=function(){var t,n=this.props,r=n.prefixCls,o=n.className,i=n.marks,a=n.dots,s=n.step,l=n.included,u=n.disabled,c=n.vertical,p=n.min,f=n.max,d=n.children,h=n.maximumTrackStyle,v=n.style,m=n.railStyle,y=n.dotStyle,g=n.activeDotStyle,b=e.prototype.render.call(this),C=b.tracks,w=b.handles,S=ii()(r,(t={},t[r+"-with-marks"]=Object.keys(i).length,t[r+"-disabled"]=u,t[r+"-vertical"]=c,t[o]=o,t));return Zo.a.createElement("div",{ref:this.saveSlider,className:S,onTouchStart:u?gr:this.onTouchStart,onMouseDown:u?gr:this.onMouseDown,onKeyDown:u?gr:this.onKeyDown,onFocus:u?gr:this.onFocus,onBlur:u?gr:this.onBlur,style:v},Zo.a.createElement("div",{className:r+"-rail",style:Vo()({},h,m)}),C,Zo.a.createElement(zf,{prefixCls:r,vertical:c,marks:i,dots:a,step:s,included:l,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:f,min:p,dotStyle:y,activeDotStyle:g}),w,Zo.a.createElement(Wf,{className:r+"-mark",vertical:c,marks:i,included:l,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:f,min:p}),d)},t}(e),t.displayName="ComponentEnhancer("+e.displayName+")",t.propTypes=Vo()({},e.propTypes,{min:ni.a.number,max:ni.a.number,step:ni.a.number,marks:ni.a.object,included:ni.a.bool,className:ni.a.string,prefixCls:ni.a.string,disabled:ni.a.bool,children:ni.a.any,onBeforeChange:ni.a.func,onChange:ni.a.func,onAfterChange:ni.a.func,handle:ni.a.func,dots:ni.a.bool,vertical:ni.a.bool,style:ni.a.object,minimumTrackStyle:ni.a.object,maximumTrackStyle:ni.a.object,handleStyle:ni.a.oneOfType([ni.a.object,ni.a.arrayOf(ni.a.object)]),trackStyle:ni.a.oneOfType([ni.a.object,ni.a.arrayOf(ni.a.object)]),railStyle:ni.a.object,dotStyle:ni.a.object,activeDotStyle:ni.a.object,autoFocus:ni.a.bool,onFocus:ni.a.func,onBlur:ni.a.func}),t.defaultProps=Vo()({},e.defaultProps,{prefixCls:"rc-slider",className:"",min:0,max:100,step:1,marks:{},handle:function(e){var t=e.index,n=$a()(e,["index"]);return delete n.dragging,Zo.a.createElement(Uf,Vo()({},n,{key:t}))},onBeforeChange:gr,onChange:gr,onAfterChange:gr,included:!0,disabled:!1,dots:!1,vertical:!1,trackStyle:[{}],handleStyle:[{}],railStyle:{},dotStyle:{},activeDotStyle:{}}),n}function Cr(){if("undefined"!=typeof window&&window.document&&window.document.documentElement){var e=window.document.documentElement;return"flex"in e.style||"webkitFlex"in e.style||"Flex"in e.style||"msFlex"in e.style}return!1}function wr(e){return"string"==typeof e}function Sr(e,t){if("createEvent"in document){var n=document.createEvent("HTMLEvents");n.initEvent(t,!1,!0),e.dispatchEvent(n)}}function xr(){}function _r(e){return e&&!Jo.isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)}function kr(){}function Er(){}function Or(e){if(!e.getClientRects().length)return{top:0,left:0};var t=e.getBoundingClientRect();if(t.width||t.height){var n=e.ownerDocument,r=n.defaultView,o=n.documentElement;return{top:t.top+r.pageYOffset-o.clientTop,left:t.left+r.pageXOffset-o.clientLeft}}return t}function Tr(e,t){!function e(n,r,o,i){Array.isArray(n)&&(n=n.filter(function(e){return!!e})),Jo.Children.forEach(n,function(n,a){var s=r+"-"+a;o.push(s);var l=[];n.props.children&&n.type&&n.type.isTreeNode&&e(n.props.children,s,l,s),t(n,a,s,n.key||s,l,i)})}(e,0,[])}function Nr(e,t,n){!function t(r){r.childrenPos.forEach(function(r){var o=e[r];o.disableCheckbox||o.disabled||(o.halfChecked=!1,o.checked=n),t(o)})}(e[t]);!function t(n){if(n.parentPos){var r=e[n.parentPos],o=r.childrenPos.length,i=0;r.childrenPos.forEach(function(t){if(e[t].disableCheckbox)return void(o-=1);!0===e[t].checked?i++:!0===e[t].halfChecked&&(i+=.5)}),i===o?(r.checked=!0,r.halfChecked=!1):i>0?(r.halfChecked=!0,r.checked=!1):(r.checked=!1,r.halfChecked=!1),t(r)}}(e[t])}function Pr(e){var t=[],n=[],r=[],o=[];return Object.keys(e).forEach(function(i){var a=e[i];a.checked?(n.push(a.key),r.push(a.node),o.push({node:a.node,pos:i})):a.halfChecked&&t.push(a.key)}),{halfCheckedKeys:t,checkedKeys:n,checkedNodes:r,checkedNodesPositions:o}}function Mr(e,t){return t?{checked:e,halfChecked:t}:e}function Dr(e,t){return!(t.length<e.length)&&(!(t.length>e.length&&"-"!==t.charAt(e.length))&&t.substr(0,e.length)===e)}function Ir(){}function Ar(e){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function jr(e,t){return"value"===t?Ar(e):e.props[t]}function Rr(e){return e.combobox}function Lr(e){return!!(e.multiple||e.tags||e.treeCheckable)}function Kr(e){return Lr(e)||Rr(e)}function Fr(e){return!Kr(e)}function Vr(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function zr(e){e.preventDefault()}function Br(e){var t=e;return"label"===t&&(t="title"),t}function Wr(e,t){return e.every(function(e,n){return e===t[n]})}function Hr(e,t){return!(!t||!e)&&(!(t.length<e.length)&&(!(t.length>e.length&&"-"!==t.charAt(e.length))&&t.substr(0,e.length)===e))}function Ur(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function qr(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function Yr(e,t,n){!function e(n,r,o){var i=Ur(n);Zo.a.Children.forEach(n,function(n,a){var s=r+"-"+a;n&&n.props.children&&n.type&&e(n.props.children,s,{node:n,pos:s}),n&&t(n,a,s,n.key||s,qr(a,i,{}),o)})}(e,0,n)}function Gr(e){if(!e.length)return e;var t=[],n={};e.forEach(function(e){if(e.pos){var t=e.pos.split("-").length;n[t]||(n[t]=[]),n[t].push(e)}});var r=Object.keys(n).sort(function(e,t){return t-e});return r.reduce(function(e,r){return r&&r!==e&&n[e].forEach(function(e){var o=!1;n[r].forEach(function(t){Hr(t.pos,e.pos)&&(o=!0,t.children||(t.children=[]),t.children.push(e))}),o||t.push(e)}),r}),n[r[r.length-1]].concat(t)}function Xr(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=0;r<n.length;r++)!function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=e+1;o<n.length;o++)!function(e){t[n[e]].forEach(function(o,i){Hr(r,o)&&(t[n[e]][i]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})}(o)})}(r);var o=[];return n.forEach(function(e){o=o.concat(t[e])}),o}function $r(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function Jr(e){return e.split("-")}function Zr(e,t,n){var r=Object.keys(e);r.forEach(function(o,i){var a=Jr(o),s=!1;t.forEach(function(t){var l=Jr(t);a.length>l.length&&Wr(l,a)&&(e[o].halfChecked=!1,e[o].checked=n,r[i]=null),a[0]===l[0]&&a[1]===l[1]&&(s=!0)}),s||(r[i]=null)}),r=r.filter(function(e){return e});for(var o=0;o<t.length;o++)!function(n){!function o(i){var a=Jr(i).length;if(!(a<=2)){var s=0,l=0,u=$r(i);r.forEach(function(r){var o=Jr(r);if(o.length===a&&Wr(Jr(u),o))if(s++,e[r].checked){l++;var i=t.indexOf(r);i>-1&&(t.splice(i,1),i<=n&&n--)}else e[r].halfChecked&&(l+=.5)});var c=e[u];0===l?(c.checked=!1,c.halfChecked=!1):l===s?(c.checked=!0,c.halfChecked=!1):(c.halfChecked=!0,c.checked=!1),o(u)}}(t[n]),o=n}(o)}function Qr(e,t){var n=[],r=[],o=[];return Object.keys(e).forEach(function(t){var i=e[t];i.checked?(r.push(i.key),o.push(Vo()({},i,{pos:t}))):i.halfChecked&&n.push(i.key)}),{halfCheckedKeys:n,checkedKeys:r,checkedNodes:o,treeNodesStates:e,checkedPositions:t}}function eo(e,t){var n=[],r={};return Yr(e,function(e,o,i,a,s){r[i]={node:e,key:a,checked:!1,halfChecked:!1,siblingPosition:s},-1!==t.indexOf(Ar(e))&&(r[i].checked=!0,n.push(i))}),Zr(r,Xr(n.sort()),!0),Qr(r,n)}function to(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return Zo.a.Children.map(e,function(e,n){var r=t+"-"+n,o={title:e.props.title,label:e.props.label||e.props.title,value:e.props.value,key:e.key,_pos:r};return e.props.children&&(o.children=to(e.props.children,r)),o})}function no(e,t){e.forEach(function(e){t(e),e.children&&no(e.children,t)})}function ro(e,t){function n(e){e.forEach(function(e){if(!e.__checked){var t=o.indexOf(e.value),r=e.children;t>-1?(e.__checked=!0,a.push({node:e,pos:e._pos}),o.splice(t,1),r&&no(r,function(e){e.__checked=!0,a.push({node:e,pos:e._pos})})):r&&n(r)}})}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{root:!0},n=0;e.forEach(function(e){var t=e.children;if(!t||e.__checked||e.__halfChecked)e.__checked?n++:e.__halfChecked&&(n+=.5);else{var o=r(t,e);o.__checked?n++:o.__halfChecked&&(n+=.5)}});var o=e.length;return n===o?(t.__checked=!0,a.push({node:t,pos:t._pos})):n<o&&n>0&&(t.__halfChecked=!0),t.root?e:t}var o=[].concat(e);if(!o.length)return o;var i=to(t),a=[];return n(i),r(i),a.forEach(function(e,t){delete a[t].node.__checked,delete a[t].node._pos,a[t].node.props={title:a[t].node.title,label:a[t].node.label||a[t].node.title,value:a[t].node.value},a[t].node.children&&(a[t].node.props.children=a[t].node.children),delete a[t].node.title,delete a[t].node.label,delete a[t].node.value,delete a[t].node.children}),a}function oo(e,t){function n(e){for(var r,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(r={},r[t.id]=t.rootPId,r),i=[],a=0;a<e.length;a++)e[a]=Vo()({},e[a]),e[a][t.pId]===o[t.id]&&(e[a].key=e[a][t.id],i.push(e[a]),e.splice(a--,1));if(i.length&&(o.children=i,i.forEach(function(t){return n(e,t)})),o[t.id]===t.rootPId)return i}return n(e)}function io(e,t){return function(n){e[t]=n}}function ao(e,t){var n=e[t];if("string"!=typeof n||!n)return new Error}function so(e,t,n){var r=ni.a.shape({value:ao,label:ni.a.node});if(e.labelInValue){if(ni.a.oneOfType([ni.a.arrayOf(r),r]).apply(void 0,arguments))return new Error("Invalid prop `"+t+"` supplied to `"+n+"`, when `labelInValue` is `true`, `"+t+"` should in shape of `{ value: string, label?: string }`.")}else{if(!e.treeCheckable||!e.treeCheckStrictly){if(e.multiple&&""===e[t])return new Error("Invalid prop `"+t+"` of type `string` supplied to `"+n+"`, expected `array` when `multiple` is `true`.");return ni.a.oneOfType([ni.a.arrayOf(ni.a.string),ni.a.string]).apply(void 0,arguments)}if(ni.a.oneOfType([ni.a.arrayOf(r),r]).apply(void 0,arguments))return new Error("Invalid prop `"+t+"` supplied to `"+n+"`, when `treeCheckable` and `treeCheckStrictly` are `true`, `"+t+"` should in shape of `{ value: string, label?: string }`.")}}function lo(){}function uo(e,t){return String(jr(t,Br(this.props.treeNodeFilterProp))).indexOf(e)>-1}function co(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments[2];return e.map(function(e,r){var o=t+"-"+r,i=e.label,a=e.value,s=e.disabled,l=e.key,u=(e.hasOwnProperty,e.selectable),c=e.children,p=e.isLeaf,f=$a()(e,["label","value","disabled","key","hasOwnProperty","selectable","children","isLeaf"]),d=Vo()({value:a,title:i,key:l||a||o,disabled:s||!1,selectable:!1===u?u:!n},f);return c&&c.length?Zo.a.createElement(zd,d,co(c,o,n)):Zo.a.createElement(zd,Vo()({},d,{isLeaf:p}))})}function po(e,t){var n=String(e),r=Number(t)>>>0,o=n.slice(0,r+1).search(/\S+$/),i=n.slice(r).search(/\s/);return i<0?{word:n.slice(o),begin:o,end:n.length}:{word:n.slice(o,i+r),begin:o,end:i+r}}function fo(e,t){var n=t.getAnchorKey(),r=t.getAnchorOffset()-1,o=e.getCurrentContent(),i=o.getBlockForKey(n);if(i){return po(i.getText(),r)}return""}function ho(e,t,n,r){var o="immutable"===r?"IMMUTABLE":"MUTABLE",i=e.getSelection(),a=e.getCurrentContent();a.createEntity("mention",o,n||t);var s=fo(e,i),l=s.begin,u=s.end,c=uh.Modifier.replaceText(a,i.merge({anchorOffset:l,focusOffset:u}),t,null,a.getLastCreatedEntityKey()),p=uh.Modifier.insertText(c,c.getSelectionAfter()," "),f=uh.EditorState.push(e,p,"insert-mention");return uh.EditorState.forceSelection(f,p.getSelectionAfter())}function vo(e){var t=e.getSelection(),n=fo(e,t),r=n.begin,o=n.end,i=uh.Modifier.replaceText(e.getCurrentContent(),t.merge({anchorOffset:r,focusOffset:o}),"",null),a=uh.Modifier.insertText(i,i.getSelectionAfter()," "),s=uh.EditorState.push(e,a,"insert-mention");return uh.EditorState.forceSelection(s,a.getSelectionAfter())}function mo(e,t){var n=e.getBoundingClientRect();if(n.width||n.height){var r=t||e.parentElement;return{top:n.top-r.clientTop,left:n.left-r.clientLeft}}return n}function yo(e){var t=Array.isArray(e)?e:[e],n=t.join("").replace(/(\$|\^)/g,"\\$1");return t.length>1&&(n="["+n+"]"),new RegExp("(\\s|^)("+n+")[^\\s]*","g")}function go(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"@",n=yo(t),r=[];return e.getBlockMap().forEach(function(e){for(var t=e.getText(),o=void 0;null!==(o=n.exec(t));)r.push(o[0].trim())}),r}function bo(e){return e.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;").split("\xa0").join("&nbsp;").split("\n").join("<br > \n")}function Co(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Mh(e,t).generate()}function wo(e,t,n){for(var r=t.getText(),o=void 0,i=void 0;null!==(o=e.exec(r));)i=o.index,n(i,i+o[0].length)}function So(e,t,n){e.findEntityRanges(function(e){var t=e.getEntity();return t&&"mention"===n.getEntity(t).getType()},t)}function xo(){}function _o(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={onChange:xo,onUpArrow:xo,onDownArrow:xo,getEditorState:xo,setEditorState:xo,handleReturn:xo,onBlur:xo},n={callbacks:t,mentionStore:Ph},r=yo(e.prefix),o=e.tag||Eh,i=[{strategy:function(e,t){wo(r,e,t)},component:function(t){return Zo.a.createElement(_h,Vo()({},t,n,{style:e.mentionStyle,suggestionRegex:yo(e.prefix)}))}}];return"immutable"!==e.mode&&i.unshift({strategy:So,component:function(e){return Zo.a.createElement(Dh,Vo()({tag:o},e,{callbacks:t}))}}),{name:"mention",Suggestions:function(e){return Zo.a.createElement(Sh,Vo()({},e,n,{store:Ph}))},decorators:i,onChange:function(e){return t.onChange?t.onChange(e):e},callbacks:t,export:Co}}function ko(e){return uh.ContentState.createFromText(e)}function Eo(e,t){var n="cannot post "+e.action+" "+t.status+"'",r=new Error(n);return r.status=t.status,r.method="post",r.url=e.action,r}function Oo(e){var t=e.responseText||e.response;if(!t)return t;try{return JSON.parse(t)}catch(e){return t}}function To(e){var t=new XMLHttpRequest;e.onProgress&&t.upload&&(t.upload.onprogress=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),e.onProgress(t)});var n=new FormData;e.data&&Object.keys(e.data).map(function(t){n.append(t,e.data[t])}),n.append(e.filename,e.file),t.onerror=function(t){e.onError(t)},t.onload=function(){if(t.status<200||t.status>=300)return e.onError(Eo(e,t),Oo(t));e.onSuccess(Oo(t),t)},t.open("post",e.action,!0),e.withCredentials&&"withCredentials"in t&&(t.withCredentials=!0);var r=e.headers||{};null!==r["X-Requested-With"]&&t.setRequestHeader("X-Requested-With","XMLHttpRequest");for(var o in r)r.hasOwnProperty(o)&&null!==r[o]&&t.setRequestHeader(o,r[o]);return t.send(n),{abort:function(){t.abort()}}}function No(){return"rc-upload-"+Kh+"-"+ ++Fh}function Po(e,t){return-1!==e.indexOf(t,e.length-t.length)}function Mo(){}function Do(){return!0}function Io(e){return{lastModified:e.lastModified,lastModifiedDate:e.lastModifiedDate,name:e.filename||e.name,size:e.size,type:e.type,uid:e.uid,response:e.response,error:e.error,percent:0,originFileObj:e}}function Ao(){var e=.1;return function(t){var n=t;return n>=.98?n:(n+=e,e-=.01,e<.001&&(e=.001),100*n)}}function jo(e,t){var n=void 0!==e.uid?"uid":"name";return t.filter(function(t){return t[n]===e[n]})[0]}function Ro(e,t){var n=void 0!==e.uid?"uid":"name",r=t.filter(function(t){return t[n]!==e[n]});return r.length===t.length?null:r}Object.defineProperty(t,"__esModule",{value:!0});var Lo=n(8),Ko=n.n(Lo),Fo=n(1),Vo=n.n(Fo),zo=n(2),Bo=n.n(zo),Wo=n(7),Ho=n.n(Wo),Uo=n(3),qo=n.n(Uo),Yo=n(4),Go=n.n(Yo),Xo=n(19),$o=n.n(Xo),Jo=n(0),Zo=n.n(Jo),Qo=n(9),ei=n.n(Qo),ti=n(5),ni=n.n(ti),ri=n(35),oi=n(6),ii=n.n(oi),ai=n(31),si=n.n(ai),li=n(20),ui=n(60),ci=n.n(ui),pi=n(87),fi=Object(pi.b)(),di=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,a=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":$o()(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},hi=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.events=["resize","scroll","touchstart","touchmove","touchend","pageshow","load"],e.eventHandlers={},e.state={affixStyle:void 0,placeholderStyle:void 0},e.saveFixedNode=function(t){e.fixedNode=t},e.savePlaceholderNode=function(t){e.placeholderNode=t},e}return Go()(t,e),Ho()(t,[{key:"setAffixStyle",value:function(e,t){var n=this,r=this.props,o=r.onChange,i=void 0===o?l:o,a=r.target,s=void 0===a?u:a,c=this.state.affixStyle,p=s()===window;"scroll"===e.type&&c&&t&&p||si()(t,c)||this.setState({affixStyle:t},function(){var e=!!n.state.affixStyle;(t&&!c||!t&&c)&&i(e)})}},{key:"setPlaceholderStyle",value:function(e){var t=this.state.placeholderStyle;si()(e,t)||this.setState({placeholderStyle:e})}},{key:"syncPlaceholderStyle",value:function(e){var t=this.state.affixStyle;t&&(this.placeholderNode.style.cssText="",this.setAffixStyle(e,Vo()({},t,{width:this.placeholderNode.offsetWidth})),this.setPlaceholderStyle({width:this.placeholderNode.offsetWidth}))}},{key:"updatePosition",value:function(e){var t=this.props,n=t.offsetTop,o=t.offsetBottom,i=t.offset,l=t.target,c=void 0===l?u:l,p=c();n=n||i;var f=r(p,!0),d=Qo.findDOMNode(this),h=s(d,p),v={width:this.fixedNode.offsetWidth,height:this.fixedNode.offsetHeight},m={top:!1,bottom:!1};"number"!=typeof n&&"number"!=typeof o?(m.top=!0,n=0):(m.top="number"==typeof n,m.bottom="number"==typeof o);var y=a(p),g=p.innerHeight||p.clientHeight;if(f>h.top-n&&m.top){var b=h.width,C=y.top+n;this.setAffixStyle(e,{position:"fixed",top:C,left:y.left+h.left,width:b}),this.setPlaceholderStyle({width:b,height:v.height})}else if(f<h.top+v.height+o-g&&m.bottom){var w=p===window?0:window.innerHeight-y.bottom,S=h.width;this.setAffixStyle(e,{position:"fixed",bottom:w+o,left:y.left+h.left,width:S}),this.setPlaceholderStyle({width:S,height:h.height})}else{var x=this.state.affixStyle;"resize"===e.type&&x&&"fixed"===x.position&&d.offsetWidth?this.setAffixStyle(e,Vo()({},x,{width:d.offsetWidth})):this.setAffixStyle(e,null),this.setPlaceholderStyle(null)}"resize"===e.type&&this.syncPlaceholderStyle(e)}},{key:"componentDidMount",value:function(){var e=this,t=this.props.target||u;this.timeout=setTimeout(function(){e.setTargetEventListeners(t)})}},{key:"componentWillReceiveProps",value:function(e){this.props.target!==e.target&&(this.clearEventListeners(),this.setTargetEventListeners(e.target),this.updatePosition({}))}},{key:"componentWillUnmount",value:function(){this.clearEventListeners(),clearTimeout(this.timeout),this.updatePosition.cancel()}},{key:"setTargetEventListeners",value:function(e){var t=this,n=e();n&&(this.clearEventListeners(),this.events.forEach(function(e){t.eventHandlers[e]=Object(ri.a)(n,e,t.updatePosition)}))}},{key:"clearEventListeners",value:function(){var e=this;this.events.forEach(function(t){var n=e.eventHandlers[t];n&&n.remove&&n.remove()})}},{key:"render",value:function(){var e=ii()(Ko()({},this.props.prefixCls||"ant-affix",this.state.affixStyle)),t=Object(li.a)(this.props,["prefixCls","offsetTop","offsetBottom","target","onChange"]),n=Vo()({},this.state.placeholderStyle,this.props.style);return Jo.createElement("div",Vo()({},t,{style:n,ref:this.savePlaceholderNode}),Jo.createElement("div",{className:e,ref:this.saveFixedNode,style:this.state.affixStyle},this.props.children))}}]),t}(Jo.Component),vi=hi;hi.propTypes={offsetTop:ni.a.number,offsetBottom:ni.a.number,target:ni.a.func},di([i()],hi.prototype,"updatePosition",null);var mi=Object(pi.b)(),yi=/#([^#]+)$/,gi=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleScroll=function(){if(!n.animating){var e=n.props,t=e.offsetTop,r=e.bounds;n.setState({activeLink:n.getCurrentAnchor(t,r)})}},n.handleScrollTo=function(e){var t=n.props,r=t.offsetTop,o=t.target,i=void 0===o?c:o;n.animating=!0,n.setState({activeLink:e}),d(e,r,i,function(){n.animating=!1})},n.updateInk=function(){if("undefined"!=typeof document){var e=n.props.prefixCls,t=Qo.findDOMNode(n).getElementsByClassName(e+"-link-title-active")[0];t&&(n.inkNode.style.top=t.offsetTop+t.clientHeight/2-4.5+"px")}},n.saveInkNode=function(e){n.inkNode=e},n.state={activeLink:null},n.links=[],n}return Go()(t,e),Ho()(t,[{key:"getChildContext",value:function(){var e=this;return{antAnchor:{registerLink:function(t){e.links.includes(t)||e.links.push(t)},unregisterLink:function(t){var n=e.links.indexOf(t);-1!==n&&e.links.splice(n,1)},activeLink:this.state.activeLink,scrollTo:this.handleScrollTo}}}},{key:"componentDidMount",value:function(){var e=this.props.target||c;this.scrollEvent=Object(ri.a)(e(),"scroll",this.handleScroll),this.handleScroll()}},{key:"componentWillUnmount",value:function(){this.scrollEvent&&this.scrollEvent.remove()}},{key:"componentDidUpdate",value:function(){this.updateInk()}},{key:"getCurrentAnchor",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5;if("undefined"==typeof document)return"";var n=[];if(this.links.forEach(function(r){var o=yi.exec(r.toString());if(o){var i=document.getElementById(o[1]);if(i&&p(i)<e+t){var a=p(i);n.push({link:r,top:a})}}}),n.length){return n.reduce(function(e,t){return t.top>e.top?t:e}).link}return""}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=void 0===n?"":n,o=e.style,i=e.offsetTop,a=e.affix,s=e.showInkInFixed,l=e.children,u=this.state.activeLink,c=ii()(t+"-ink-ball",{visible:u}),p=ii()(r,t+"-wrapper"),f=ii()(t,{fixed:!a&&!s}),d=Vo()({maxHeight:i?"calc(100vh - "+i+"px)":"100vh"},o),h=Jo.createElement("div",{className:p,style:d},Jo.createElement("div",{className:f},Jo.createElement("div",{className:t+"-ink"},Jo.createElement("span",{className:c,ref:this.saveInkNode})),l));return a?Jo.createElement(vi,{offsetTop:i},h):h}}]),t}(Jo.Component),bi=gi;gi.defaultProps={prefixCls:"ant-anchor",affix:!0,showInkInFixed:!1},gi.childContextTypes={antAnchor:ni.a.object};var Ci=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleClick=function(){e.context.antAnchor.scrollTo(e.props.href)},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.context.antAnchor.registerLink(this.props.href)}},{key:"componentWillUnmount",value:function(){this.context.antAnchor.unregisterLink(this.props.href)}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.href,r=e.title,o=e.children,i=this.context.antAnchor.activeLink===n,a=ii()(t+"-link",Ko()({},t+"-link-active",i)),s=ii()(t+"-link-title",Ko()({},t+"-link-title-active",i));return Jo.createElement("div",{className:a},Jo.createElement("a",{className:s,href:n,title:"string"==typeof r?r:"",onClick:this.handleClick},r),o)}}]),t}(Jo.Component),wi=Ci;Ci.defaultProps={prefixCls:"ant-anchor",href:"#"},Ci.contextTypes={antAnchor:ni.a.object},bi.Link=wi;var Si=bi,xi=n(177),_i=n(70),ki=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleKeyDown=function(t){var n=e.props,r=n.onPressEnter,o=n.onKeyDown;13===t.keyCode&&r&&r(t),o&&o(t)},e.saveInput=function(t){e.input=t},e}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"getInputClassName",value:function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.disabled;return ii()(n,(e={},Ko()(e,n+"-sm","small"===r),Ko()(e,n+"-lg","large"===r),Ko()(e,n+"-disabled",o),e))}},{key:"renderLabeledInput",value:function(e){var t,n=this.props;if(!n.addonBefore&&!n.addonAfter)return e;var r=n.prefixCls+"-group",o=r+"-addon",i=n.addonBefore?Jo.createElement("span",{className:o},n.addonBefore):null,a=n.addonAfter?Jo.createElement("span",{className:o},n.addonAfter):null,s=ii()(n.prefixCls+"-wrapper",Ko()({},r,i||a)),l=ii()(n.prefixCls+"-group-wrapper",(t={},Ko()(t,n.prefixCls+"-group-wrapper-sm","small"===n.size),Ko()(t,n.prefixCls+"-group-wrapper-lg","large"===n.size),t));return i||a?Jo.createElement("span",{className:l,style:n.style},Jo.createElement("span",{className:s},i,Jo.cloneElement(e,{style:null}),a)):Jo.createElement("span",{className:s},i,e,a)}},{key:"renderLabeledIcon",value:function(e){var t,n=this.props;if(!("prefix"in n||"suffix"in n))return e;var r=n.prefix?Jo.createElement("span",{className:n.prefixCls+"-prefix"},n.prefix):null,o=n.suffix?Jo.createElement("span",{className:n.prefixCls+"-suffix"},n.suffix):null,i=ii()(n.className,n.prefixCls+"-affix-wrapper",(t={},Ko()(t,n.prefixCls+"-affix-wrapper-sm","small"===n.size),Ko()(t,n.prefixCls+"-affix-wrapper-lg","large"===n.size),t));return Jo.createElement("span",{className:i,style:n.style},r,Jo.cloneElement(e,{style:null,className:this.getInputClassName()}),o)}},{key:"renderInput",value:function(){var e=this.props,t=e.value,n=e.className,r=Object(li.a)(this.props,["prefixCls","onPressEnter","addonBefore","addonAfter","prefix","suffix"]);return"value"in this.props&&(r.value=h(t),delete r.defaultValue),this.renderLabeledIcon(Jo.createElement("input",Vo()({},r,{className:ii()(this.getInputClassName(),n),onKeyDown:this.handleKeyDown,ref:this.saveInput})))}},{key:"render",value:function(){return this.renderLabeledInput(this.renderInput())}}]),t}(Jo.Component),Ei=ki;ki.defaultProps={prefixCls:"ant-input",type:"text",disabled:!1},ki.propTypes={type:ni.a.string,id:ni.a.oneOfType([ni.a.string,ni.a.number]),size:ni.a.oneOf(["small","default","large"]),maxLength:ni.a.oneOfType([ni.a.string,ni.a.number]),disabled:ni.a.bool,value:ni.a.any,defaultValue:ni.a.any,className:ni.a.string,addonBefore:ni.a.node,addonAfter:ni.a.node,prefixCls:ni.a.string,autosize:ni.a.oneOfType([ni.a.bool,ni.a.object]),onPressEnter:ni.a.func,onKeyDown:ni.a.func,onKeyUp:ni.a.func,onFocus:ni.a.func,onBlur:ni.a.func,prefix:ni.a.node,suffix:ni.a.node};var Oi=function(e){var t,n=e.prefixCls,r=void 0===n?"ant-input-group":n,o=e.className,i=void 0===o?"":o,a=ii()(r,(t={},Ko()(t,r+"-lg","large"===e.size),Ko()(t,r+"-sm","small"===e.size),Ko()(t,r+"-compact",e.compact),t),i);return Jo.createElement("span",{className:a,style:e.style},e.children)},Ti=Oi,Ni=n(14),Pi=n(51),Mi=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Di=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onSearch=function(){var t=e.props.onSearch;t&&t(e.input.input.value),e.input.focus()},e.saveInput=function(t){e.input=t},e}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"getButtonOrIcon",value:function(){var e=this.props,t=e.enterButton,n=e.prefixCls,r=e.size;if(!t)return Jo.createElement(Ni.a,{className:n+"-icon",type:"search",key:"searchIcon"});var o=t;return o.type===Pi.a||"button"===o.type?Jo.cloneElement(o,o.type===Pi.a?{className:n+"-button",size:r,onClick:this.onSearch}:{onClick:this.onSearch}):Jo.createElement(Pi.a,{className:n+"-button",type:"primary",size:r,onClick:this.onSearch,key:"enterButton"},!0===t?Jo.createElement(Ni.a,{type:"search"}):t)}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=t.prefixCls,o=t.inputPrefixCls,i=t.size,a=t.suffix,s=t.enterButton,l=Mi(t,["className","prefixCls","inputPrefixCls","size","suffix","enterButton"]);delete l.onSearch;var u=this.getButtonOrIcon(),c=a?[a,u]:u,p=ii()(r,n,(e={},Ko()(e,r+"-enter-button",!!s),Ko()(e,r+"-"+i,!!i),e));return Jo.createElement(Ei,Vo()({onPressEnter:this.onSearch},l,{size:i,className:p,prefixCls:o,suffix:c,ref:this.saveInput}))}}]),t}(Jo.Component),Ii=Di;Di.defaultProps={inputPrefixCls:"ant-input",prefixCls:"ant-input-search",enterButton:!1};var Ai="\n min-height:0 !important;\n max-height:none !important;\n height:0 !important;\n visibility:hidden !important;\n overflow:hidden !important;\n position:absolute !important;\n z-index:-1000 !important;\n top:0 !important;\n right:0 !important\n",ji=["letter-spacing","line-height","padding-top","padding-bottom","font-family","font-weight","font-size","text-rendering","text-transform","width","text-indent","padding-left","padding-right","border-width","box-sizing"],Ri={},Li=void 0,Ki=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={textareaStyles:{}},e.resizeTextarea=function(){var t=e.props.autosize;if(t&&e.textAreaRef){var n=t?t.minRows:null,r=t?t.maxRows:null,o=m(e.textAreaRef,!1,n,r);e.setState({textareaStyles:o})}},e.handleTextareaChange=function(t){"value"in e.props||e.resizeTextarea();var n=e.props.onChange;n&&n(t)},e.handleKeyDown=function(t){var n=e.props,r=n.onPressEnter,o=n.onKeyDown;13===t.keyCode&&r&&r(t),o&&o(t)},e.saveTextAreaRef=function(t){e.textAreaRef=t},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.resizeTextarea()}},{key:"componentWillReceiveProps",value:function(e){this.props.value!==e.value&&(this.nextFrameActionId&&g(this.nextFrameActionId),this.nextFrameActionId=y(this.resizeTextarea))}},{key:"focus",value:function(){this.textAreaRef.focus()}},{key:"blur",value:function(){this.textAreaRef.blur()}},{key:"getTextAreaClassName",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.disabled;return ii()(t,n,Ko()({},t+"-disabled",r))}},{key:"render",value:function(){var e=this.props,t=Object(li.a)(e,["prefixCls","onPressEnter","autosize"]),n=Vo()({},e.style,this.state.textareaStyles);return"value"in t&&(t.value=t.value||""),Jo.createElement("textarea",Vo()({},t,{className:this.getTextAreaClassName(),style:n,onKeyDown:this.handleKeyDown,onChange:this.handleTextareaChange,ref:this.saveTextAreaRef}))}}]),t}(Jo.Component),Fi=Ki;Ki.defaultProps={prefixCls:"ant-input"},Ei.Group=Ti,Ei.Search=Ii,Ei.TextArea=Fi;var Vi=Ei,zi=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.focus=function(){e.ele.focus?e.ele.focus():Qo.findDOMNode(e.ele).focus()},e.blur=function(){e.ele.blur?e.ele.blur():Qo.findDOMNode(e.ele).blur()},e.saveRef=function(t){e.ele=t;var n=e.props.children.ref;"function"==typeof n&&n(t)},e}return Go()(t,e),Ho()(t,[{key:"render",value:function(){return Jo.cloneElement(this.props.children,Vo()({},this.props,{ref:this.saveRef}),null)}}]),t}(Jo.Component),Bi=zi,Wi=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getInputElement=function(){var t=e.props.children,n=t&&Jo.isValidElement(t)&&t.type!==xi.b?Jo.Children.only(e.props.children):Jo.createElement(Vi,null),r=Vo()({},n.props);return delete r.children,Jo.createElement(Bi,r,n)},e.saveSelect=function(t){e.select=t},e}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.select.focus()}},{key:"blur",value:function(){this.select.blur()}},{key:"render",value:function(){var e,t=this.props,n=t.size,r=t.className,o=void 0===r?"":r,i=t.notFoundContent,a=t.prefixCls,s=t.optionLabelProp,l=t.dataSource,u=t.children,c=ii()((e={},Ko()(e,a+"-lg","large"===n),Ko()(e,a+"-sm","small"===n),Ko()(e,o,!!o),Ko()(e,a+"-show-search",!0),Ko()(e,a+"-auto-complete",!0),e)),p=void 0,f=Jo.Children.toArray(u);return p=f.length&&b(f[0])?u:l?l.map(function(e){if(Jo.isValidElement(e))return e;switch(void 0===e?"undefined":$o()(e)){case"string":return Jo.createElement(xi.b,{key:e},e);case"object":return Jo.createElement(xi.b,{key:e.value},e.text);default:throw new Error("AutoComplete[dataSource] only supports type `string[] | Object[]`.")}}):[],Jo.createElement(_i.a,Vo()({},this.props,{className:c,mode:"combobox",optionLabelProp:s,getInputElement:this.getInputElement,notFoundContent:i,ref:this.saveSelect}),p)}}]),t}(Jo.Component),Hi=Wi;Wi.Option=xi.b,Wi.OptGroup=xi.a,Wi.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",optionLabelProp:"children",choiceTransitionName:"zoom",showSearch:!1,filterOption:!1};var Ui=n(18),qi=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleClose=function(e){e.preventDefault();var t=Qo.findDOMNode(n);t.style.height=t.offsetHeight+"px",t.style.height=t.offsetHeight+"px",n.setState({closing:!1}),(n.props.onClose||C)(e)},n.animationEnd=function(){n.setState({closed:!0,closing:!0}),(n.props.afterClose||C)()},n.state={closing:!0,closed:!1},n}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t=this.props,n=t.closable,r=t.description,o=t.type,i=t.prefixCls,a=void 0===i?"ant-alert":i,s=t.message,l=t.closeText,u=t.showIcon,c=t.banner,p=t.className,f=void 0===p?"":p,d=t.style,h=t.iconType;if(u=!(!c||void 0!==u)||u,o=c&&void 0===o?"warning":o||"info",!h){switch(o){case"success":h="check-circle";break;case"info":h="info-circle";break;case"error":h="cross-circle";break;case"warning":h="exclamation-circle";break;default:h="default"}r&&(h+="-o")}var v=ii()(a,(e={},Ko()(e,a+"-"+o,!0),Ko()(e,a+"-close",!this.state.closing),Ko()(e,a+"-with-description",!!r),Ko()(e,a+"-no-icon",!u),Ko()(e,a+"-banner",!!c),e),f);l&&(n=!0);var m=n?Jo.createElement("a",{onClick:this.handleClose,className:a+"-close-icon"},l||Jo.createElement(Ni.a,{type:"cross"})):null;return this.state.closed?null:Jo.createElement(Ui.a,{component:"",showProp:"data-show",transitionName:a+"-slide-up",onEnd:this.animationEnd},Jo.createElement("div",{"data-show":this.state.closing,className:v,style:d},u?Jo.createElement(Ni.a,{className:a+"-icon",type:h}):null,Jo.createElement("span",{className:a+"-message"},s),Jo.createElement("span",{className:a+"-description"},r),m))}}]),t}(Jo.Component),Yi=qi,Gi=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Xi=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.setScale=function(){var e=n.avatarChildren;if(e){var t=e.offsetWidth,r=Qo.findDOMNode(n).getBoundingClientRect().width;r-8<t?n.setState({scale:(r-8)/t}):n.setState({scale:1})}},n.handleImgLoadError=function(){return n.setState({isImgExist:!1})},n.state={scale:1,isImgExist:!0},n}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.setScale()}},{key:"componentDidUpdate",value:function(e,t){(e.children!==this.props.children||t.scale!==this.state.scale&&1===this.state.scale)&&this.setScale()}},{key:"render",value:function(){var e,t,n=this,r=this.props,o=r.prefixCls,i=r.shape,a=r.size,s=r.src,l=r.icon,u=r.className,c=Gi(r,["prefixCls","shape","size","src","icon","className"]),p=ii()((e={},Ko()(e,o+"-lg","large"===a),Ko()(e,o+"-sm","small"===a),e)),f=ii()(o,u,p,(t={},Ko()(t,o+"-"+i,i),Ko()(t,o+"-image",s&&this.state.isImgExist),Ko()(t,o+"-icon",l),t)),d=this.props.children;if(s&&this.state.isImgExist)d=Jo.createElement("img",{src:s,onError:this.handleImgLoadError});else if(l)d=Jo.createElement(Ni.a,{type:l});else{var h=this.avatarChildren;if(h||1!==this.state.scale){var v={msTransform:"scale("+this.state.scale+")",WebkitTransform:"scale("+this.state.scale+")",transform:"scale("+this.state.scale+")",position:"absolute",display:"inline-block",left:"calc(50% - "+Math.round(h.offsetWidth/2)+"px)"};d=Jo.createElement("span",{className:o+"-string",ref:function(e){return n.avatarChildren=e},style:v},d)}else d=Jo.createElement("span",{className:o+"-string",ref:function(e){return n.avatarChildren=e}},d)}return Jo.createElement("span",Vo()({},c,{className:f}),d)}}]),t}(Jo.Component),$i=Xi;Xi.defaultProps={prefixCls:"ant-avatar",shape:"circle",size:"default"};var Ji=Object(pi.b)(),Zi=function(e,t,n,r){var o=n-t;return e/=r/2,e<1?o/2*e*e*e+t:o/2*((e-=2)*e*e+2)+t},Qi=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.getCurrentScrollTop=function(){var e=n.props.target||S,t=e();return t===window?window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop:t.scrollTop},n.scrollToTop=function(e){var t=n.getCurrentScrollTop(),r=Date.now();Ji(function e(){var o=Date.now(),i=o-r;n.setScrollTop(Zi(i,t,0,450)),i<450&&Ji(e)}),(n.props.onClick||w)(e)},n.handleScroll=function(){var e=n.props,t=e.visibilityHeight,o=e.target,i=void 0===o?S:o,a=r(i(),!0);n.setState({visible:a>t})},n.state={visible:!1},n}return Go()(t,e),Ho()(t,[{key:"setScrollTop",value:function(e){var t=this.props.target||S,n=t();n===window?(document.body.scrollTop=e,document.documentElement.scrollTop=e):n.scrollTop=e}},{key:"componentDidMount",value:function(){var e=this.props.target||S;this.scrollEvent=Object(ri.a)(e(),"scroll",this.handleScroll),this.handleScroll()}},{key:"componentWillUnmount",value:function(){this.scrollEvent&&this.scrollEvent.remove()}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=void 0===t?"ant-back-top":t,r=e.className,o=void 0===r?"":r,i=e.children,a=ii()(n,o),s=Jo.createElement("div",{className:n+"-content"},Jo.createElement("div",{className:n+"-icon"})),l=Object(li.a)(this.props,["prefixCls","className","children","visibilityHeight","target"]),u=this.state.visible?Jo.createElement("div",Vo()({},l,{className:a,onClick:this.scrollToTop}),i||s):null;return Jo.createElement(Ui.a,{component:"",transitionName:"fade"},u)}}]),t}(Jo.Component),ea=Qi;Qi.defaultProps={visibilityHeight:400};var ta=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={animateStarted:!0,count:e.count},n}return Go()(t,e),Ho()(t,[{key:"getPositionByNum",value:function(e,t){if(this.state.animateStarted)return 10+e;var n=x(this.state.count)[t],r=x(this.lastCount)[t];return this.state.count>this.lastCount?n>=r?10+e:20+e:n<=r?10+e:e}},{key:"componentWillReceiveProps",value:function(e){var t=this;if("count"in e){if(this.state.count===e.count)return;this.lastCount=this.state.count,this.setState({animateStarted:!0},function(){setTimeout(function(){t.setState({animateStarted:!1,count:e.count},function(){var e=t.props.onAnimated;e&&e()})},5)})}}},{key:"renderNumberList",value:function(e){for(var t=[],n=0;n<30;n++){var r=e===n?"current":"";t.push(Jo.createElement("p",{key:n.toString(),className:r},n%10))}return t}},{key:"renderCurrentNumber",value:function(e,t){var n=this.getPositionByNum(e,t),r=this.state.animateStarted||void 0===x(this.lastCount)[t];return Object(Jo.createElement)("span",{className:this.props.prefixCls+"-only",style:{transition:r&&"none",msTransform:"translateY("+100*-n+"%)",WebkitTransform:"translateY("+100*-n+"%)",transform:"translateY("+100*-n+"%)"},key:t},this.renderNumberList(n))}},{key:"renderNumberElement",value:function(){var e=this,t=this.state;return!t.count||isNaN(t.count)?t.count:x(t.count).map(function(t,n){return e.renderCurrentNumber(t,n)}).reverse()}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.style,o=e.title,i=e.component,a=void 0===i?"sup":i,s=Object(li.a)(this.props,["count","onAnimated","component","prefixCls"]),l=Vo()({},s,{className:ii()(t,n),title:o});return r&&r.borderColor&&(l.style.boxShadow="0 0 0 1px "+r.borderColor+" inset"),Object(Jo.createElement)(a,l,this.renderNumberElement())}}]),t}(Jo.Component),na=ta;ta.defaultProps={prefixCls:"ant-scroll-number",count:null,onAnimated:function(){}};var ra=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},oa=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t,n,r=this.props,o=r.count,i=r.showZero,a=r.prefixCls,s=r.scrollNumberPrefixCls,l=r.overflowCount,u=r.className,c=r.style,p=r.children,f=r.dot,d=r.status,h=r.text,v=r.offset,m=ra(r,["count","showZero","prefixCls","scrollNumberPrefixCls","overflowCount","className","style","children","dot","status","text","offset"]),y=o>l?l+"+":o,g="0"===y||0===y,b=f&&!g||d;b&&(y="");var C=null===y||void 0===y||""===y,w=(C||g&&!i)&&!b,S=ii()((e={},Ko()(e,a+"-status-dot",!!d),Ko()(e,a+"-status-"+d,!!d),e)),x=ii()((t={},Ko()(t,a+"-dot",b),Ko()(t,a+"-count",!b),Ko()(t,a+"-multiple-words",!b&&o&&o.toString&&o.toString().length>1),Ko()(t,a+"-status-"+d,!!d),t)),_=ii()(u,a,(n={},Ko()(n,a+"-status",!!d),Ko()(n,a+"-not-a-wrapper",!p),n)),k=v?Vo()({marginTop:v[0],marginLeft:v[1]},c):c;if(!p&&d)return Jo.createElement("span",{className:_,style:k},Jo.createElement("span",{className:S}),Jo.createElement("span",{className:a+"-status-text"},h));var E=w?null:Jo.createElement(na,{prefixCls:s,"data-show":!w,className:x,count:y,title:o,style:k}),O=w||!h?null:Jo.createElement("span",{className:a+"-status-text"},h);return Jo.createElement("span",Vo()({},m,{className:_}),p,Jo.createElement(Ui.a,{component:"",showProp:"data-show",transitionName:p?a+"-zoom":"",transitionAppear:!0},E),O)}}]),t}(Jo.Component),ia=oa;oa.defaultProps={prefixCls:"ant-badge",scrollNumberPrefixCls:"ant-scroll-number",count:null,showZero:!1,dot:!1,overflowCount:99},oa.propTypes={count:ni.a.oneOfType([ni.a.string,ni.a.number]),showZero:ni.a.bool,dot:ni.a.bool,overflowCount:ni.a.number};var aa=n(27),sa=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},la=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.separator,r=e.children,o=sa(e,["prefixCls","separator","children"]),i=void 0;return i="href"in this.props?Jo.createElement("a",Vo()({className:t+"-link"},o),r):Jo.createElement("span",Vo()({className:t+"-link"},o),r),r?Jo.createElement("span",null,i,Jo.createElement("span",{className:t+"-separator"},n)):null}}]),t}(Jo.Component),ua=la;la.__ANT_BREADCRUMB_ITEM=!0,la.defaultProps={prefixCls:"ant-breadcrumb",separator:"/"},la.propTypes={prefixCls:ni.a.string,separator:ni.a.oneOfType([ni.a.string,ni.a.element]),href:ni.a.string};var ca=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){var e=this.props;Object(aa.a)(!("linkRender"in e||"nameRender"in e),"`linkRender` and `nameRender` are removed, please use `itemRender` instead, see: https://u.ant.design/item-render.")}},{key:"render",value:function(){var e=void 0,t=this.props,n=t.separator,r=t.prefixCls,o=t.style,i=t.className,a=t.routes,s=t.params,l=void 0===s?{}:s,u=t.children,c=t.itemRender,p=void 0===c?k:c;if(a&&a.length>0){var f=[];e=a.map(function(e){e.path=e.path||"";var t=e.path.replace(/^\//,"");return Object.keys(l).forEach(function(e){t=t.replace(":"+e,l[e])}),t&&f.push(t),Jo.createElement(ua,{separator:n,key:e.breadcrumbName||t},p(e,l,a,f))})}else u&&(e=Jo.Children.map(u,function(e,t){return e?(Object(aa.a)(e.type&&e.type.__ANT_BREADCRUMB_ITEM,"Breadcrumb only accepts Breadcrumb.Item as it's children"),Object(Jo.cloneElement)(e,{separator:n,key:t})):e}));return Jo.createElement("div",{className:ii()(i,r),style:o},e)}}]),t}(Jo.Component),pa=ca;ca.defaultProps={prefixCls:"ant-breadcrumb",separator:"/"},ca.propTypes={prefixCls:ni.a.string,separator:ni.a.node,routes:ni.a.array,params:ni.a.object,linkRender:ni.a.func,nameRender:ni.a.func},pa.Item=ua;var fa=pa,da=n(122),ha=n.n(da),va=n(21),ma=n.n(va),ya=n(15),ga=n.n(ya),ba={DATE_ROW_COUNT:6,DATE_COL_COUNT:7},Ca=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.render=function(){for(var e=this.props,t=e.value,n=t.localeData(),r=e.prefixCls,o=[],i=[],a=n.firstDayOfWeek(),s=void 0,l=ma()(),u=0;u<ba.DATE_COL_COUNT;u++){var c=(a+u)%ba.DATE_COL_COUNT;l.day(c),o[u]=n.weekdaysMin(l),i[u]=n.weekdaysShort(l)}e.showWeekNumber&&(s=Zo.a.createElement("th",{role:"columnheader",className:r+"-column-header "+r+"-week-number-header"},Zo.a.createElement("span",{className:r+"-column-header-inner"},"x")));var p=i.map(function(e,t){return Zo.a.createElement("th",{key:t,role:"columnheader",title:e,className:r+"-column-header"},Zo.a.createElement("span",{className:r+"-column-header-inner"},o[t]))});return Zo.a.createElement("thead",null,Zo.a.createElement("tr",{role:"row"},s,p))},t}(Zo.a.Component),wa=Ca,Sa={disabledHours:function(){return[]},disabledMinutes:function(){return[]},disabledSeconds:function(){return[]}},xa=ga()({displayName:"DateTBody",propTypes:{contentRender:ni.a.func,dateRender:ni.a.func,disabledDate:ni.a.func,prefixCls:ni.a.string,selectedValue:ni.a.oneOfType([ni.a.object,ni.a.arrayOf(ni.a.object)]),value:ni.a.object,hoverValue:ni.a.any,showWeekNumber:ni.a.bool},getDefaultProps:function(){return{hoverValue:[]}},render:function(){var e=this.props,t=e.contentRender,n=e.prefixCls,r=e.selectedValue,o=e.value,i=e.showWeekNumber,a=e.dateRender,s=e.disabledDate,l=e.hoverValue,u=void 0,c=void 0,p=void 0,f=[],d=E(o),h=n+"-cell",v=n+"-week-number-cell",m=n+"-date",y=n+"-today",g=n+"-selected-day",b=n+"-selected-date",C=n+"-selected-start-date",w=n+"-selected-end-date",S=n+"-in-range-cell",x=n+"-last-month-cell",_=n+"-next-month-btn-day",k=n+"-disabled-cell",T=n+"-disabled-cell-first-of-row",N=n+"-disabled-cell-last-of-row",P=o.clone();P.date(1);var M=P.day(),D=(M+7-o.localeData().firstDayOfWeek())%7,I=P.clone();I.add(0-D,"days");var A=0;for(u=0;u<ba.DATE_ROW_COUNT;u++)for(c=0;c<ba.DATE_COL_COUNT;c++)p=I,A&&(p=p.clone(),p.add(A,"days")),f.push(p),A++;var F=[];for(A=0,u=0;u<ba.DATE_ROW_COUNT;u++){var V,z=void 0,B=void 0,W=!1,H=[];for(i&&(B=Zo.a.createElement("td",{key:f[A].week(),role:"gridcell",className:v},f[A].week())),c=0;c<ba.DATE_COL_COUNT;c++){var U=null,q=null;p=f[A],c<ba.DATE_COL_COUNT-1&&(U=f[A+1]),c>0&&(q=f[A-1]);var Y=h,G=!1,X=!1;j(p,d)&&(Y+=" "+y,z=!0);var $=R(p,o),J=L(p,o);if(r&&Array.isArray(r)){var Z=l.length?l:r;if(!$&&!J){var Q=Z[0],ee=Z[1];Q&&j(p,Q)&&(X=!0,W=!0,Y+=" "+C),Q&&ee&&(j(p,ee)?(X=!0,W=!0,Y+=" "+w):p.isAfter(Q,"day")&&p.isBefore(ee,"day")&&(Y+=" "+S))}}else j(p,o)&&(X=!0,W=!0);j(p,r)&&(Y+=" "+b),$&&(Y+=" "+x),J&&(Y+=" "+_),s&&s(p,o)&&(G=!0,q&&s(q,o)||(Y+=" "+T),U&&s(U,o)||(Y+=" "+N)),X&&(Y+=" "+g),G&&(Y+=" "+k);var te=void 0;if(a)te=a(p,o);else{var ne=t?t(p,o):p.date();te=Zo.a.createElement("div",{key:K(p),className:m,"aria-selected":X,"aria-disabled":G},ne)}H.push(Zo.a.createElement("td",{key:A,onClick:G?void 0:e.onSelect.bind(null,p),onMouseEnter:G?void 0:e.onDayHover&&e.onDayHover.bind(null,p)||void 0,role:"gridcell",title:O(p),className:Y},te)),A++}F.push(Zo.a.createElement("tr",{key:u,role:"row",className:ii()((V={},V[n+"-current-week"]=z,V[n+"-active-week"]=W,V))},B,H))}return Zo.a.createElement("tbody",{className:n+"-tbody"},F)}}),_a=xa,ka=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls;return Zo.a.createElement("table",{className:t+"-table",cellSpacing:"0",role:"grid"},Zo.a.createElement(wa,e),Zo.a.createElement(_a,e))},t}(Zo.a.Component),Ea=ka,Oa=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));return r.state={value:n.value},r}return Go()(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value})},t.prototype.setAndSelectValue=function(e){this.setState({value:e}),this.props.onSelect(e)},t.prototype.months=function(){for(var e=this.state.value,t=e.clone(),n=[],r=0,o=0;o<4;o++){n[o]=[];for(var i=0;i<3;i++){t.month(r);var a=N(t);n[o][i]={value:r,content:a,title:a},r++}}return n},t.prototype.render=function(){var e=this,t=this.props,n=this.state.value,r=E(n),o=this.months(),i=n.month(),a=t.prefixCls,s=t.locale,l=t.contentRender,u=t.cellRender,c=o.map(function(o,c){var p=o.map(function(o){var c,p=!1;if(t.disabledDate){var f=n.clone();f.month(o.value),p=t.disabledDate(f)}var d=(c={},c[a+"-cell"]=1,c[a+"-cell-disabled"]=p,c[a+"-selected-cell"]=o.value===i,c[a+"-current-cell"]=r.year()===n.year()&&o.value===r.month(),c),h=void 0;if(u){var v=n.clone();v.month(o.value),h=u(v,s)}else{var m=void 0;if(l){var y=n.clone();y.month(o.value),m=l(y,s)}else m=o.content;h=Zo.a.createElement("a",{className:a+"-month"},m)}return Zo.a.createElement("td",{role:"gridcell",key:o.value,onClick:p?null:F.bind(e,o.value),title:o.title,className:ii()(d)},h)});return Zo.a.createElement("tr",{key:c,role:"row"},p)});return Zo.a.createElement("table",{className:a+"-table",cellSpacing:"0",role:"grid"},Zo.a.createElement("tbody",{className:a+"-tbody"},c))},t}(Jo.Component);Oa.defaultProps={onSelect:V},Oa.propTypes={onSelect:ni.a.func,cellRender:ni.a.func,prefixCls:ni.a.string,value:ni.a.object};var Ta=Oa,Na={propTypes:{value:ni.a.object,defaultValue:ni.a.object,onKeyDown:ni.a.func},getDefaultProps:function(){return{onKeyDown:z}},getInitialState:function(){var e=this.props;return{value:e.value||e.defaultValue||B(),selectedValue:e.selectedValue||e.defaultSelectedValue}},componentWillReceiveProps:function(e){var t=e.value,n=e.selectedValue;"value"in e&&(t=t||e.defaultValue||W(this.state.value),this.setState({value:t})),"selectedValue"in e&&this.setState({selectedValue:n})},onSelect:function(e,t){e&&this.setValue(e),this.setSelectedValue(e,t)},renderRoot:function(e){var t,n=this.props,r=n.prefixCls,o=(t={},t[r]=1,t[r+"-hidden"]=!n.visible,t[n.className]=!!n.className,t[e.className]=!!e.className,t);return Zo.a.createElement("div",{ref:this.saveRoot,className:""+ii()(o),style:this.props.style,tabIndex:"0",onKeyDown:this.onKeyDown},e.children)},setSelectedValue:function(e,t){"selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onSelect(e,t)},setValue:function(e){var t=this.state.value;"value"in this.props||this.setState({value:e}),(t&&e&&!t.isSame(e)||!t&&e||t&&!e)&&this.props.onChange(e)},isAllowedDate:function(e){return A(e,this.props.disabledDate,this.props.disabledTime)}},Pa=Na,Ma=n(162),Da={propTypes:{className:ni.a.string,locale:ni.a.object,style:ni.a.object,visible:ni.a.bool,onSelect:ni.a.func,prefixCls:ni.a.string,onChange:ni.a.func,onOk:ni.a.func},getDefaultProps:function(){return{locale:Ma.a,style:{},visible:!0,prefixCls:"rc-calendar",className:"",onSelect:H,onChange:H,onClear:H,renderFooter:function(){return null},renderSidebar:function(){return null}}},shouldComponentUpdate:function(e){return this.props.visible||e.visible},getFormat:function(){var e=this.props.format,t=this.props,n=t.locale,r=t.timePicker;return e||(e=r?n.dateTimeFormat:n.dateFormat),e},focus:function(){this.rootInstance&&this.rootInstance.focus()},saveRoot:function(e){this.rootInstance=e}},Ia=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.onYearChange=function(e){var t=this.props.value.clone();t.year(parseInt(e,10)),this.props.onValueChange(t)},t.prototype.onMonthChange=function(e){var t=this.props.value.clone();t.month(parseInt(e,10)),this.props.onValueChange(t)},t.prototype.yearSelectElement=function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.prefixCls,i=t.Select,a=e-n,s=a+r,l=[],u=a;u<s;u++)l.push(Zo.a.createElement(i.Option,{key:""+u},u));return Zo.a.createElement(i,{className:o+"-header-year-select",onChange:this.onYearChange.bind(this),dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1},l)},t.prototype.monthSelectElement=function(e){for(var t=this.props,n=t.value.clone(),r=t.prefixCls,o=[],i=t.Select,a=0;a<12;a++)n.month(a),o.push(Zo.a.createElement(i.Option,{key:""+a},N(n)));return Zo.a.createElement(i,{className:r+"-header-month-select",dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",overflowX:"hidden",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1,onChange:this.onMonthChange.bind(this)},o)},t.prototype.changeTypeToDate=function(){this.props.onTypeChange("date")},t.prototype.changeTypeToMonth=function(){this.props.onTypeChange("month")},t.prototype.render=function(){var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=e.type,i=e.showTypeSwitch,a=e.headerComponents,s=t.year(),l=t.month(),u=this.yearSelectElement(s),c="month"===o?null:this.monthSelectElement(l),p=r+"-header-switcher",f=i?Zo.a.createElement("span",{className:p},"date"===o?Zo.a.createElement("span",{className:p+"-focus"},n.month):Zo.a.createElement("span",{onClick:this.changeTypeToDate.bind(this),className:p+"-normal"},n.month),"month"===o?Zo.a.createElement("span",{className:p+"-focus"},n.year):Zo.a.createElement("span",{onClick:this.changeTypeToMonth.bind(this),className:p+"-normal"},n.year)):null;return Zo.a.createElement("div",{className:r+"-header"},f,c,u,a)},t}(Jo.Component);Ia.propTypes={value:ni.a.object,locale:ni.a.object,yearSelectOffset:ni.a.number,yearSelectTotal:ni.a.number,onValueChange:ni.a.func,onTypeChange:ni.a.func,Select:ni.a.func,prefixCls:ni.a.string,type:ni.a.string,showTypeSwitch:ni.a.bool,headerComponents:ni.a.array},Ia.defaultProps={yearSelectOffset:10,yearSelectTotal:20,onValueChange:U,onTypeChange:U};var Aa=Ia,ja=ga()({displayName:"FullCalendar",propTypes:{defaultType:ni.a.string,type:ni.a.string,prefixCls:ni.a.string,locale:ni.a.object,onTypeChange:ni.a.func,fullscreen:ni.a.bool,monthCellRender:ni.a.func,dateCellRender:ni.a.func,showTypeSwitch:ni.a.bool,Select:ni.a.func.isRequired,headerComponents:ni.a.array,headerComponent:ni.a.object,headerRender:ni.a.func,showHeader:ni.a.bool,disabledDate:ni.a.func},mixins:[Da,Pa],getDefaultProps:function(){return{defaultType:"date",fullscreen:!1,showTypeSwitch:!0,showHeader:!0,onTypeChange:function(){}}},getInitialState:function(){var e=void 0;return e="type"in this.props?this.props.type:this.props.defaultType,{type:e}},componentWillReceiveProps:function(e){"type"in e&&this.setState({type:e.type})},onMonthSelect:function(e){this.onSelect(e,{target:"month"})},setType:function(e){"type"in this.props||this.setState({type:e}),this.props.onTypeChange(e)},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.fullscreen,o=e.showHeader,i=e.headerComponent,a=e.headerRender,s=e.disabledDate,l=this.state,u=l.value,c=l.type,p=null;if(o)if(a)p=a(u,c,t);else{var f=i||Aa;p=Zo.a.createElement(f,Vo()({key:"calendar-header"},e,{prefixCls:n+"-full",type:c,value:u,onTypeChange:this.setType,onValueChange:this.setValue}))}var d="date"===c?Zo.a.createElement(Ea,{dateRender:e.dateCellRender,contentRender:e.dateCellContentRender,locale:t,prefixCls:n,onSelect:this.onSelect,value:u,disabledDate:s}):Zo.a.createElement(Ta,{cellRender:e.monthCellRender,contentRender:e.monthCellContentRender,locale:t,onSelect:this.onMonthSelect,prefixCls:n+"-month-panel",value:u,disabledDate:s}),h=[p,Zo.a.createElement("div",{key:"calendar-body",className:n+"-calendar-body"},d)],v=[n+"-full"];return r&&v.push(n+"-fullscreen"),this.renderRoot({children:h,className:v.join(" ")})}}),Ra=ja,La=n(26),Ka=n(90),Fa=_i.a.Option,Va=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onYearChange=function(t){var n=e.props,r=n.value,o=n.validRange,i=r.clone();if(i.year(parseInt(t,10)),o){var a=ha()(o,2),s=a[0],l=a[1],u=i.get("year"),c=i.get("month");u===l.get("year")&&c>l.get("month")&&i.month(l.get("month")),u===s.get("year")&&c<s.get("month")&&i.month(s.get("month"))}var p=e.props.onValueChange;p&&p(i)},e.onMonthChange=function(t){var n=e.props.value.clone();n.month(parseInt(t,10));var r=e.props.onValueChange;r&&r(n)},e.onTypeChange=function(t){var n=e.props.onTypeChange;n&&n(t.target.value)},e.getCalenderHeaderNode=function(t){e.calenderHeaderNode=t},e}return Go()(t,e),Ho()(t,[{key:"getYearSelectElement",value:function(e){var t=this,n=this.props,r=n.yearSelectOffset,o=n.yearSelectTotal,i=n.locale,a=n.prefixCls,s=n.fullscreen,l=n.validRange,u=e-r,c=u+o;l&&(u=l[0].get("year"),c=l[1].get("year")+1);for(var p="\u5e74"===i.year?"\u5e74":"",f=[],d=u;d<c;d++)f.push(Jo.createElement(Fa,{key:""+d},d+p));return Jo.createElement(_i.a,{size:s?"default":"small",dropdownMatchSelectWidth:!1,className:a+"-year-select",onChange:this.onYearChange,value:String(e),getPopupContainer:function(){return t.calenderHeaderNode}},f)}},{key:"getMonthsLocale",value:function(e){for(var t=e.clone(),n=e.localeData(),r=[],o=0;o<12;o++)t.month(o),r.push(n.monthsShort(t));return r}},{key:"getMonthSelectElement",value:function(e,t){var n=this,r=this.props,o=r.prefixCls,i=r.fullscreen,a=r.validRange,s=r.value,l=[],u=0,c=12;if(a){var p=ha()(a,2),f=p[0],d=p[1],h=s.get("year");d.get("year")===h?c=d.get("month")+1:u=f.get("month")}for(var v=u;v<c;v++)l.push(Jo.createElement(Fa,{key:""+v},t[v]));return Jo.createElement(_i.a,{size:i?"default":"small",dropdownMatchSelectWidth:!1,className:o+"-month-select",value:String(e),onChange:this.onMonthChange,getPopupContainer:function(){return n.calenderHeaderNode}},l)}},{key:"render",value:function(){var e=this.props,t=e.type,n=e.value,r=e.prefixCls,o=e.locale,i=e.fullscreen,a=this.getYearSelectElement(n.year()),s="date"===t?this.getMonthSelectElement(n.month(),this.getMonthsLocale(n)):null,l=i?"default":"small",u=Jo.createElement(Ka.Group,{onChange:this.onTypeChange,value:t,size:l},Jo.createElement(Ka.Button,{value:"date"},o.month),Jo.createElement(Ka.Button,{value:"month"},o.year));return Jo.createElement("div",{className:r+"-header",ref:this.getCalenderHeaderNode},a,s,u)}}]),t}(Jo.Component),za=Va;Va.defaultProps={prefixCls:"ant-fullcalendar-header",yearSelectOffset:10,yearSelectTotal:20};var Ba=n(182),Wa=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.monthCellRender=function(e){var t=n.props,r=t.prefixCls,o=t.monthCellRender,i=void 0===o?Y:o;return Jo.createElement("div",{className:r+"-month"},Jo.createElement("div",{className:r+"-value"},e.localeData().monthsShort(e)),Jo.createElement("div",{className:r+"-content"},i(e)))},n.dateCellRender=function(e){var t=n.props,r=t.prefixCls,o=t.dateCellRender,i=void 0===o?Y:o;return Jo.createElement("div",{className:r+"-date"},Jo.createElement("div",{className:r+"-value"},G(e.date())),Jo.createElement("div",{className:r+"-content"},i(e)))},n.setValue=function(e,t){"value"in n.props||n.setState({value:e}),"select"===t?n.props.onSelect&&n.props.onSelect(e):"changePanel"===t&&n.onPanelChange(e,n.state.mode)},n.setType=function(e){var t="date"===e?"month":"year";n.state.mode!==t&&(n.setState({mode:t}),n.onPanelChange(n.state.value,t))},n.onHeaderValueChange=function(e){n.setValue(e,"changePanel")},n.onHeaderTypeChange=function(e){n.setType(e)},n.onSelect=function(e){n.setValue(e,"select")},n.getDateRange=function(e,t){return function(n){if(!n)return!1;var r=ha()(e,2),o=r[0],i=r[1],a=!n.isBetween(o,i,"days","[]");return t?t(n)||a:a}},n.renderCalendar=function(e,t){var r=n.state,o=n.props,i=r.value,a=r.mode;i&&t&&i.locale(t);var s=o.prefixCls,l=o.style,u=o.className,c=o.fullscreen,p=o.dateFullCellRender,f=o.monthFullCellRender,d="year"===a?"month":"date",h=u||"";c&&(h+=" "+s+"-fullscreen");var v=f||n.monthCellRender,m=p||n.dateCellRender,y=o.disabledDate;return o.validRange&&(y=n.getDateRange(o.validRange,y)),Jo.createElement("div",{className:h,style:l},Jo.createElement(za,{fullscreen:c,type:d,value:i,locale:e.lang,prefixCls:s,onTypeChange:n.onHeaderTypeChange,onValueChange:n.onHeaderValueChange,validRange:o.validRange}),Jo.createElement(Ra,Vo()({},o,{disabledDate:y,Select:Y,locale:e.lang,type:d,prefixCls:s,showHeader:!1,value:i,monthCellRender:v,dateCellRender:m,onSelect:n.onSelect})))};var r=e.value||e.defaultValue||q(va)();if(!q(va).isMoment(r))throw new Error("The value/defaultValue of Calendar must be a moment object after `[email protected]`, see: https://u.ant.design/calendar-value");return n.state={value:r,mode:e.mode},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value}),"mode"in e&&e.mode!==this.props.mode&&this.setState({mode:e.mode})}},{key:"onPanelChange",value:function(e,t){var n=this.props.onPanelChange;n&&n(e,t)}},{key:"render",value:function(){return Jo.createElement(La.a,{componentName:"Calendar",defaultLocale:Ba.a},this.renderCalendar)}}]),t}(Jo.Component),Ha=Wa;Wa.defaultProps={locale:{},fullscreen:!0,prefixCls:"ant-fullcalendar",mode:"month",onSelect:Y,onPanelChange:Y},Wa.propTypes={monthCellRender:ni.a.func,dateCellRender:ni.a.func,monthFullCellRender:ni.a.func,dateFullCellRender:ni.a.func,fullscreen:ni.a.bool,locale:ni.a.object,prefixCls:ni.a.string,className:ni.a.string,style:ni.a.object,onPanelChange:ni.a.func,value:ni.a.object,onSelect:ni.a.func};var Ua=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},qa=function(e){var t=e.prefixCls,n=void 0===t?"ant-card":t,r=e.className,o=Ua(e,["prefixCls","className"]),i=ii()(n+"-grid",r);return Jo.createElement("div",Vo()({},o,{className:i}))},Ya=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Ga=function(e){var t=e.prefixCls,n=void 0===t?"ant-card":t,r=e.className,o=e.avatar,i=e.title,a=e.description,s=Ya(e,["prefixCls","className","avatar","title","description"]),l=ii()(n+"-meta",r),u=o?Jo.createElement("div",{className:n+"-meta-avatar"},o):null,c=i?Jo.createElement("div",{className:n+"-meta-title"},i):null,p=a?Jo.createElement("div",{className:n+"-meta-description"},a):null,f=c||p?Jo.createElement("div",{className:n+"-meta-detail"},c,p):null;return Jo.createElement("div",Vo()({},s,{className:l}),u,f)},Xa=n(17),$a=n.n(Xa),Ja={LEFT:37,UP:38,RIGHT:39,DOWN:40},Za=ga()({displayName:"TabPane",propTypes:{className:ni.a.string,active:ni.a.bool,style:ni.a.any,destroyInactiveTabPane:ni.a.bool,forceRender:ni.a.bool,placeholder:ni.a.node},getDefaultProps:function(){return{placeholder:null}},render:function(){var e,t=this.props,n=t.className,r=t.destroyInactiveTabPane,o=t.active,i=t.forceRender,a=t.rootPrefixCls,s=t.style,l=t.children,u=t.placeholder,c=$a()(t,["className","destroyInactiveTabPane","active","forceRender","rootPrefixCls","style","children","placeholder"]);this._isActived=this._isActived||o;var p=a+"-tabpane",f=ii()((e={},Ko()(e,p,1),Ko()(e,p+"-inactive",!o),Ko()(e,p+"-active",o),Ko()(e,n,n),e)),d=r?o:this._isActived;return Zo.a.createElement("div",Vo()({style:s,role:"tabpanel","aria-hidden":o?"false":"true",className:f},re(c)),d||i?l:u)}}),Qa=Za,es=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));ts.call(n);var r=void 0;return r="activeKey"in e?e.activeKey:"defaultActiveKey"in e?e.defaultActiveKey:ie(e),n.state={activeKey:r},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){"activeKey"in e?this.setState({activeKey:e.activeKey}):ae(e,this.state.activeKey)||this.setState({activeKey:ie(e)})}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.tabBarPosition,o=t.className,i=t.renderTabContent,a=t.renderTabBar,s=t.destroyInactiveTabPane,l=$a()(t,["prefixCls","tabBarPosition","className","renderTabContent","renderTabBar","destroyInactiveTabPane"]),u=ii()((e={},Ko()(e,n,1),Ko()(e,n+"-"+r,1),Ko()(e,o,!!o),e));this.tabBar=a();var c=[Zo.a.cloneElement(this.tabBar,{prefixCls:n,key:"tabBar",onKeyDown:this.onNavKeyDown,tabBarPosition:r,onTabClick:this.onTabClick,panels:t.children,activeKey:this.state.activeKey}),Zo.a.cloneElement(i(),{prefixCls:n,tabBarPosition:r,activeKey:this.state.activeKey,destroyInactiveTabPane:s,children:t.children,onChange:this.setActiveKey,key:"tabContent"})];return"bottom"===r&&c.reverse(),Zo.a.createElement("div",Vo()({className:u,style:t.style},re(l)),c)}}]),t}(Zo.a.Component),ts=function(){var e=this;this.onTabClick=function(t){e.tabBar.props.onTabClick&&e.tabBar.props.onTabClick(t),e.setActiveKey(t)},this.onNavKeyDown=function(t){var n=t.keyCode;if(n===Ja.RIGHT||n===Ja.DOWN){t.preventDefault();var r=e.getNextActiveKey(!0);e.onTabClick(r)}else if(n===Ja.LEFT||n===Ja.UP){t.preventDefault();var o=e.getNextActiveKey(!1);e.onTabClick(o)}},this.setActiveKey=function(t){e.state.activeKey!==t&&("activeKey"in e.props||e.setState({activeKey:t}),e.props.onChange(t))},this.getNextActiveKey=function(t){var n=e.state.activeKey,r=[];Zo.a.Children.forEach(e.props.children,function(e){e&&!e.props.disabled&&(t?r.push(e):r.unshift(e))});var o=r.length,i=o&&r[0].key;return r.forEach(function(e,t){e.key===n&&(i=t===o-1?r[0].key:r[t+1].key)}),i}},ns=es;es.propTypes={destroyInactiveTabPane:ni.a.bool,renderTabBar:ni.a.func.isRequired,renderTabContent:ni.a.func.isRequired,onChange:ni.a.func,children:ni.a.any,prefixCls:ni.a.string,className:ni.a.string,tabBarPosition:ni.a.string,style:ni.a.object,activeKey:ni.a.string,defaultActiveKey:ni.a.string},es.defaultProps={prefixCls:"rc-tabs",destroyInactiveTabPane:!1,onChange:oe,tabBarPosition:"top",style:{}},es.TabPane=Qa;var rs=ga()({displayName:"TabContent",propTypes:{animated:ni.a.bool,animatedWithMargin:ni.a.bool,prefixCls:ni.a.string,children:ni.a.any,activeKey:ni.a.string,style:ni.a.any,tabBarPosition:ni.a.string},getDefaultProps:function(){return{animated:!0}},getTabPanes:function(){var e=this.props,t=e.activeKey,n=e.children,r=[];return Zo.a.Children.forEach(n,function(n){if(n){var o=n.key,i=t===o;r.push(Zo.a.cloneElement(n,{active:i,destroyInactiveTabPane:e.destroyInactiveTabPane,rootPrefixCls:e.prefixCls}))}}),r},render:function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.activeKey,i=t.tabBarPosition,a=t.animated,s=t.animatedWithMargin,l=t.style,u=ii()((e={},Ko()(e,n+"-content",!0),Ko()(e,a?n+"-content-animated":n+"-content-no-animated",!0),e));if(a){var c=$(r,o);if(-1!==c){var p=s?ne(c,i):Q(te(c,i));l=Vo()({},l,p)}else l=Vo()({},l,{display:"none"})}return Zo.a.createElement("div",{className:u,style:l},this.getTabPanes())}}),os=rs,is=ns,as={getDefaultProps:function(){return{inkBarAnimated:!0}},componentDidUpdate:function(){ue(this)},componentDidMount:function(){ue(this,!0)},componentWillUnmount:function(){clearTimeout(this.timeout)},getInkBarNode:function(){var e,t=this.props,n=t.prefixCls,r=t.styles,o=t.inkBarAnimated,i=n+"-ink-bar",a=ii()((e={},Ko()(e,i,!0),Ko()(e,o?i+"-animated":i+"-no-animated",!0),e));return Zo.a.createElement("div",{style:r.inkBar,className:a,key:"inkBar",ref:this.saveRef("inkBar")})}},ss=n(124),ls=n.n(ss),us={getDefaultProps:function(){return{scrollAnimated:!0,onPrevClick:function(){},onNextClick:function(){}}},getInitialState:function(){return this.offset=0,{next:!1,prev:!1}},componentDidMount:function(){var e=this;this.componentDidUpdate(),this.debouncedResize=ls()(function(){e.setNextPrev(),e.scrollToActiveTab()},200),this.resizeEvent=Object(ri.a)(window,"resize",this.debouncedResize)},componentDidUpdate:function(e){var t=this.props;if(e&&e.tabBarPosition!==t.tabBarPosition)return void this.setOffset(0);var n=this.setNextPrev();this.isNextPrevShown(this.state)!==this.isNextPrevShown(n)?this.setState({},this.scrollToActiveTab):e&&t.activeKey===e.activeKey||this.scrollToActiveTab()},componentWillUnmount:function(){this.resizeEvent&&this.resizeEvent.remove(),this.debouncedResize&&this.debouncedResize.cancel&&this.debouncedResize.cancel()},setNextPrev:function(){var e=this.nav,t=this.getScrollWH(e),n=this.getOffsetWH(this.container),r=this.getOffsetWH(this.navWrap),o=this.offset,i=n-t,a=this.state,s=a.next,l=a.prev;if(i>=0)s=!1,this.setOffset(0,!1),o=0;else if(i<o)s=!0;else{s=!1;var u=r-t;this.setOffset(u,!1),o=u}return l=o<0,this.setNext(s),this.setPrev(l),{next:s,prev:l}},getOffsetWH:function(e){var t=this.props.tabBarPosition,n="offsetWidth";return"left"!==t&&"right"!==t||(n="offsetHeight"),e[n]},getScrollWH:function(e){var t=this.props.tabBarPosition,n="scrollWidth";return"left"!==t&&"right"!==t||(n="scrollHeight"),e[n]},getOffsetLT:function(e){var t=this.props.tabBarPosition,n="left";return"left"!==t&&"right"!==t||(n="top"),e.getBoundingClientRect()[n]},setOffset:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=Math.min(0,e);if(this.offset!==n){this.offset=n;var r={},o=this.props.tabBarPosition,i=this.nav.style,a=Z(i);r="left"===o||"right"===o?a?{value:"translate3d(0,"+n+"px,0)"}:{name:"top",value:n+"px"}:a?{value:"translate3d("+n+"px,0,0)"}:{name:"left",value:n+"px"},a?J(i,r.value):i[r.name]=r.value,t&&this.setNextPrev()}},setPrev:function(e){this.state.prev!==e&&this.setState({prev:e})},setNext:function(e){this.state.next!==e&&this.setState({next:e})},isNextPrevShown:function(e){return e?e.next||e.prev:this.state.next||this.state.prev},prevTransitionEnd:function(e){if("opacity"===e.propertyName){var t=this.container;this.scrollToActiveTab({target:t,currentTarget:t})}},scrollToActiveTab:function(e){var t=this.activeTab,n=this.navWrap;if((!e||e.target===e.currentTarget)&&t){var r=this.isNextPrevShown()&&this.lastNextPrevShown;if(this.lastNextPrevShown=this.isNextPrevShown(),r){var o=this.getScrollWH(t),i=this.getOffsetWH(n),a=this.offset,s=this.getOffsetLT(n),l=this.getOffsetLT(t);s>l?(a+=s-l,this.setOffset(a)):s+i<l+o&&(a-=l+o-(s+i),this.setOffset(a))}}},prev:function(e){this.props.onPrevClick(e);var t=this.navWrap,n=this.getOffsetWH(t),r=this.offset;this.setOffset(r+n)},next:function(e){this.props.onNextClick(e);var t=this.navWrap,n=this.getOffsetWH(t),r=this.offset;this.setOffset(r-n)},getScrollBarNode:function(e){var t,n,r,o,i=this.state,a=i.next,s=i.prev,l=this.props,u=l.prefixCls,c=l.scrollAnimated,p=s||a,f=Zo.a.createElement("span",{onClick:s?this.prev:null,unselectable:"unselectable",className:ii()((t={},Ko()(t,u+"-tab-prev",1),Ko()(t,u+"-tab-btn-disabled",!s),Ko()(t,u+"-tab-arrow-show",p),t)),onTransitionEnd:this.prevTransitionEnd},Zo.a.createElement("span",{className:u+"-tab-prev-icon"})),d=Zo.a.createElement("span",{onClick:a?this.next:null,unselectable:"unselectable",className:ii()((n={},Ko()(n,u+"-tab-next",1),Ko()(n,u+"-tab-btn-disabled",!a),Ko()(n,u+"-tab-arrow-show",p),n))},Zo.a.createElement("span",{className:u+"-tab-next-icon"})),h=u+"-nav",v=ii()((r={},Ko()(r,h,!0),Ko()(r,c?h+"-animated":h+"-no-animated",!0),r));return Zo.a.createElement("div",{className:ii()((o={},Ko()(o,u+"-nav-container",1),Ko()(o,u+"-nav-container-scrolling",p),o)),key:"container",ref:this.saveRef("container")},f,d,Zo.a.createElement("div",{className:u+"-nav-wrap",ref:this.saveRef("navWrap")},Zo.a.createElement("div",{className:u+"-nav-scroll"},Zo.a.createElement("div",{className:v,ref:this.saveRef("nav")},e))))}},cs=n(36),ps=n.n(cs),fs={getDefaultProps:function(){return{styles:{}}},onTabClick:function(e){this.props.onTabClick(e)},getTabs:function(){var e=this,t=this.props,n=t.panels,r=t.activeKey,o=t.prefixCls,i=t.tabBarGutter,a=[];return Zo.a.Children.forEach(n,function(t,s){if(t){var l=t.key,u=r===l?o+"-tab-active":"";u+=" "+o+"-tab";var c={};t.props.disabled?u+=" "+o+"-tab-disabled":c={onClick:e.onTabClick.bind(e,l)};var p={};r===l&&(p.ref=e.saveRef("activeTab")),ps()("tab"in t.props,"There must be `tab` property on children of Tabs."),a.push(Zo.a.createElement("div",Vo()({role:"tab","aria-disabled":t.props.disabled?"true":"false","aria-selected":r===l?"true":"false"},c,{className:u,key:l,style:{marginRight:i&&s===n.length-1?0:i}},p),t.props.tab))}}),a},getRootNode:function(e){var t=this.props,n=t.prefixCls,r=t.onKeyDown,o=t.className,i=t.extraContent,a=t.style,s=t.tabBarPosition,l=$a()(t,["prefixCls","onKeyDown","className","extraContent","style","tabBarPosition"]),u=ii()(n+"-bar",Ko()({},o,!!o)),c="top"===s||"bottom"===s,p=c?{float:"right"}:{},f=i&&i.props?i.props.style:{},d=e;return i&&(d=[Object(Jo.cloneElement)(i,{key:"extra",style:Vo()({},p,f)}),Object(Jo.cloneElement)(e,{key:"content"})],d=c?d:d.reverse()),Zo.a.createElement("div",Vo()({role:"tablist",className:u,tabIndex:"0",ref:this.saveRef("root"),onKeyDown:r,style:a},re(l)),d)}},ds={saveRef:function(e){var t=this;return function(n){t[e]=n}}},hs=ga()({displayName:"ScrollableInkTabBar",mixins:[ds,fs,as,us],render:function(){var e=this.getInkBarNode(),t=this.getTabs(),n=this.getScrollBarNode([e,t]);return this.getRootNode(n)}}),vs=hs,ms=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.createNewTab=function(t){var n=e.props.onEdit;n&&n(t,"add")},e.removeTab=function(t,n){if(n.stopPropagation(),t){var r=e.props.onEdit;r&&r(t,"remove")}},e.handleChange=function(t){var n=e.props.onChange;n&&n(t)},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){var e=Qo.findDOMNode(this);e&&!ce()&&-1===e.className.indexOf(" no-flex")&&(e.className+=" no-flex")}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.className,i=void 0===o?"":o,a=n.size,s=n.type,l=void 0===s?"line":s,u=n.tabPosition,c=n.children,p=n.tabBarExtraContent,f=n.tabBarStyle,d=n.hideAdd,h=n.onTabClick,v=n.onPrevClick,m=n.onNextClick,y=n.animated,g=void 0===y||y,b=n.tabBarGutter,C="object"===(void 0===g?"undefined":$o()(g))?{inkBarAnimated:g.inkBar,tabPaneAnimated:g.tabPane}:{inkBarAnimated:g,tabPaneAnimated:g},w=C.inkBarAnimated,S=C.tabPaneAnimated;"line"!==l&&(S="animated"in this.props&&S),Object(aa.a)(!(l.indexOf("card")>=0&&("small"===a||"large"===a)),"Tabs[type=card|editable-card] doesn't have small or large size, it's by designed.");var x=ii()(i,(e={},Ko()(e,r+"-vertical","left"===u||"right"===u),Ko()(e,r+"-"+a,!!a),Ko()(e,r+"-card",l.indexOf("card")>=0),Ko()(e,r+"-"+l,!0),Ko()(e,r+"-no-animation",!S),e)),_=[];"editable-card"===l&&(_=[],Jo.Children.forEach(c,function(e,n){var o=e.props.closable;o=void 0===o||o;var i=o?Jo.createElement(Ni.a,{type:"close",onClick:function(n){return t.removeTab(e.key,n)}}):null;_.push(Jo.cloneElement(e,{tab:Jo.createElement("div",{className:o?void 0:r+"-tab-unclosable"},e.props.tab,i),key:e.key||n}))}),d||(p=Jo.createElement("span",null,Jo.createElement(Ni.a,{type:"plus",className:r+"-new-tab",onClick:this.createNewTab}),p))),p=p?Jo.createElement("div",{className:r+"-extra-content"},p):null;var k=function(){return Jo.createElement(vs,{inkBarAnimated:w,extraContent:p,onTabClick:h,onPrevClick:v,onNextClick:m,style:f,tabBarGutter:b})};return Jo.createElement(is,Vo()({},this.props,{className:x,tabBarPosition:u,renderTabBar:k,renderTabContent:function(){return Jo.createElement(os,{animated:S,animatedWithMargin:!0})},onChange:this.handleChange}),_.length>0?_:c)}}]),t}(Jo.Component),ys=ms;ms.TabPane=Qa,ms.defaultProps={prefixCls:"ant-tabs",hideAdd:!1};var gs=this&&this.__decorate||function(e,t,n,r){var o,i=arguments.length,a=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":$o()(Reflect))&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},bs=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Cs=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={widerPadding:!1},e.onTabChange=function(t){e.props.onTabChange&&e.props.onTabChange(t)},e.saveRef=function(t){e.container=t},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.updateWiderPadding(),this.resizeEvent=Object(ri.a)(window,"resize",this.updateWiderPadding),"noHovering"in this.props&&(Object(aa.a)(!this.props.noHovering,"`noHovering` of Card is deperated, you can remove it safely or use `hoverable` instead."),Object(aa.a)(!!this.props.noHovering,"`noHovering={false}` of Card is deperated, use `hoverable` instead."))}},{key:"componentWillUnmount",value:function(){this.resizeEvent&&this.resizeEvent.remove(),this.updateWiderPadding.cancel()}},{key:"updateWiderPadding",value:function(){var e=this;if(this.container){this.container.offsetWidth>=936&&!this.state.widerPadding&&this.setState({widerPadding:!0},function(){e.updateWiderPaddingCalled=!0}),this.container.offsetWidth<936&&this.state.widerPadding&&this.setState({widerPadding:!1},function(){e.updateWiderPaddingCalled=!0})}}},{key:"isContainGrid",value:function(){var e=void 0;return Jo.Children.forEach(this.props.children,function(t){t&&t.type&&t.type===qa&&(e=!0)}),e}},{key:"getAction",value:function(e){return e&&e.length?e.map(function(t,n){return Jo.createElement("li",{style:{width:100/e.length+"%"},key:"action-"+n},Jo.createElement("span",null,t))}):null}},{key:"getCompatibleHoverable",value:function(){var e=this.props,t=e.noHovering,n=e.hoverable;return"noHovering"in this.props?!t||n:!!n}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=void 0===n?"ant-card":n,o=t.className,i=t.extra,a=t.bodyStyle,s=(t.noHovering,t.hoverable,t.title),l=t.loading,u=t.bordered,c=void 0===u||u,p=t.type,f=t.cover,d=t.actions,h=t.tabList,v=t.children,m=t.activeTabKey,y=t.defaultActiveTabKey,g=bs(t,["prefixCls","className","extra","bodyStyle","noHovering","hoverable","title","loading","bordered","type","cover","actions","tabList","children","activeTabKey","defaultActiveTabKey"]),b=ii()(r,o,(e={},Ko()(e,r+"-loading",l),Ko()(e,r+"-bordered",c),Ko()(e,r+"-hoverable",this.getCompatibleHoverable()),Ko()(e,r+"-wider-padding",this.state.widerPadding),Ko()(e,r+"-padding-transition",this.updateWiderPaddingCalled),Ko()(e,r+"-contain-grid",this.isContainGrid()),Ko()(e,r+"-contain-tabs",h&&h.length),Ko()(e,r+"-type-"+p,!!p),e)),C=Jo.createElement("div",{className:r+"-loading-content"},Jo.createElement("p",{className:r+"-loading-block",style:{width:"94%"}}),Jo.createElement("p",null,Jo.createElement("span",{className:r+"-loading-block",style:{width:"28%"}}),Jo.createElement("span",{className:r+"-loading-block",style:{width:"62%"}})),Jo.createElement("p",null,Jo.createElement("span",{className:r+"-loading-block",style:{width:"22%"}}),Jo.createElement("span",{className:r+"-loading-block",style:{width:"66%"}})),Jo.createElement("p",null,Jo.createElement("span",{className:r+"-loading-block",style:{width:"56%"}}),Jo.createElement("span",{className:r+"-loading-block",style:{width:"39%"}})),Jo.createElement("p",null,Jo.createElement("span",{className:r+"-loading-block",style:{width:"21%"}}),Jo.createElement("span",{className:r+"-loading-block",style:{width:"15%"}}),Jo.createElement("span",{className:r+"-loading-block",style:{width:"40%"}}))),w=void 0!==m,S=Ko()({},w?"activeKey":"defaultActiveKey",w?m:y),x=void 0,_=h&&h.length?Jo.createElement(ys,Vo()({},S,{className:r+"-head-tabs",size:"large",onChange:this.onTabChange}),h.map(function(e){return Jo.createElement(ys.TabPane,{tab:e.tab,key:e.key})})):null;(s||i||_)&&(x=Jo.createElement("div",{className:r+"-head"},Jo.createElement("div",{className:r+"-head-wrapper"},s&&Jo.createElement("div",{className:r+"-head-title"},s),i&&Jo.createElement("div",{className:r+"-extra"},i)),_));var k=f?Jo.createElement("div",{className:r+"-cover"},f):null,E=Jo.createElement("div",{className:r+"-body",style:a},l?C:v),O=d&&d.length?Jo.createElement("ul",{className:r+"-actions"},this.getAction(d)):null,T=Object(li.a)(g,["onTabChange"]);return Jo.createElement("div",Vo()({},T,{className:b,ref:this.saveRef}),x,k,E,O)}}]),t}(Jo.Component),ws=Cs;Cs.Grid=qa,Cs.Meta=Ga,gs([i()],Cs.prototype,"updateWiderPadding",null);var Ss=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),xs=function(e){function t(){return fe(this,t),de(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return he(t,e),Ss(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.isActive||e.isActive}},{key:"render",value:function(){var e;if(this._isActived=this.props.forceRender||this._isActived||this.props.isActive,!this._isActived)return null;var t=this.props,n=t.prefixCls,r=t.isActive,o=t.children,i=t.destroyInactivePanel,a=t.forceRender,s=ii()((e={},pe(e,n+"-content",!0),pe(e,n+"-content-active",r),pe(e,n+"-content-inactive",!r),e)),l=a||r||!i?Zo.a.createElement("div",{className:n+"-content-box"},o):null;return Zo.a.createElement("div",{className:s,role:"tabpanel"},l)}}]),t}(Jo.Component);xs.propTypes={prefixCls:ni.a.string,isActive:ni.a.bool,children:ni.a.any,destroyInactivePanel:ni.a.bool,forceRender:ni.a.bool};var _s=xs,ks=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),Es=function(e){function t(){return me(this,t),ye(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ge(t,e),ks(t,[{key:"handleItemClick",value:function(){this.props.onItemClick&&this.props.onItemClick()}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=t.id,o=t.style,i=t.prefixCls,a=t.header,s=t.headerClass,l=t.children,u=t.isActive,c=t.showArrow,p=t.destroyInactivePanel,f=t.disabled,d=t.forceRender,h=ii()(i+"-header",ve({},s,s)),v=ii()((e={},ve(e,i+"-item",!0),ve(e,i+"-item-active",u),ve(e,i+"-item-disabled",f),e),n);return Zo.a.createElement("div",{className:v,style:o,id:r,role:"tablist"},Zo.a.createElement("div",{className:h,onClick:this.handleItemClick.bind(this),role:"tab","aria-expanded":u},c&&Zo.a.createElement("i",{className:"arrow"}),a),Zo.a.createElement(Ui.a,{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},Zo.a.createElement(_s,{prefixCls:i,isActive:u,destroyInactivePanel:p,forceRender:d},l)))}}]),t}(Jo.Component);Es.propTypes={className:ni.a.oneOfType([ni.a.string,ni.a.object]),id:ni.a.string,children:ni.a.any,openAnimation:ni.a.object,prefixCls:ni.a.string,header:ni.a.oneOfType([ni.a.string,ni.a.number,ni.a.node]),headerClass:ni.a.string,showArrow:ni.a.bool,isActive:ni.a.bool,onItemClick:ni.a.func,style:ni.a.object,destroyInactivePanel:ni.a.bool,disabled:ni.a.bool,forceRender:ni.a.bool},Es.defaultProps={showArrow:!0,isActive:!1,destroyInactivePanel:!1,onItemClick:function(){},headerClass:"",forceRender:!1};var Os=Es,Ts=n(118),Ns=Ce,Ps=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),Ms=function(e){function t(e){xe(this,t);var n=_e(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e)),r=n.props,o=r.activeKey,i=r.defaultActiveKey,a=i;return"activeKey"in n.props&&(a=o),n.state={openAnimation:n.props.openAnimation||Ns(n.props.prefixCls),activeKey:Ee(a)},n}return ke(t,e),Ps(t,[{key:"componentWillReceiveProps",value:function(e){"activeKey"in e&&this.setState({activeKey:Ee(e.activeKey)}),"openAnimation"in e&&this.setState({openAnimation:e.openAnimation})}},{key:"onClickItem",value:function(e){var t=this.state.activeKey;if(this.props.accordion)t=t[0]===e?[]:[e];else{t=[].concat(Se(t));var n=t.indexOf(e);n>-1?t.splice(n,1):t.push(e)}this.setActiveKey(t)}},{key:"getItems",value:function(){var e=this,t=this.state.activeKey,n=this.props,r=n.prefixCls,o=n.accordion,i=n.destroyInactivePanel,a=[];return Jo.Children.forEach(this.props.children,function(n,s){if(n){var l=n.key||String(s),u=n.props,c=u.header,p=u.headerClass,f=u.disabled,d=!1;d=o?t[0]===l:t.indexOf(l)>-1;var h={key:l,header:c,headerClass:p,isActive:d,prefixCls:r,destroyInactivePanel:i,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:f?null:function(){return e.onClickItem(l)}};a.push(Zo.a.cloneElement(n,h))}}),a}},{key:"setActiveKey",value:function(e){"activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(this.props.accordion?e[0]:e)}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.style,i=ii()((e={},we(e,n,!0),we(e,r,!!r),e));return Zo.a.createElement("div",{className:i,style:o},this.getItems())}}]),t}(Jo.Component);Ms.propTypes={children:ni.a.any,prefixCls:ni.a.string,activeKey:ni.a.oneOfType([ni.a.string,ni.a.arrayOf(ni.a.string)]),defaultActiveKey:ni.a.oneOfType([ni.a.string,ni.a.arrayOf(ni.a.string)]),openAnimation:ni.a.object,onChange:ni.a.func,accordion:ni.a.bool,className:ni.a.string,style:ni.a.object,destroyInactivePanel:ni.a.bool},Ms.defaultProps={prefixCls:"rc-collapse",onChange:function(){},accordion:!1,destroyInactivePanel:!1},Ms.Panel=Os;var Ds=Ms,Is=Ds,As=(Ds.Panel,n(125)),js=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=void 0===n?"":n,o=e.showArrow,i=void 0===o||o,a=ii()(Ko()({},t+"-no-arrow",!i),r);return Jo.createElement(Is.Panel,Vo()({},this.props,{className:a}))}}]),t}(Jo.Component),Rs=js,Ls=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=void 0===n?"":n,o=e.bordered,i=ii()(Ko()({},t+"-borderless",!o),r);return Jo.createElement(Is,Vo()({},this.props,{className:i}))}}]),t}(Jo.Component),Ks=Ls;Ls.Panel=Rs,Ls.defaultProps={prefixCls:"ant-collapse",bordered:!0,openAnimation:Vo()({},As.a,{appear:function(){}})};var Fs=Ks;if("undefined"!=typeof window){var Vs=function(e){return{media:e,matches:!1,addListener:function(){},removeListener:function(){}}};window.matchMedia=window.matchMedia||Vs}var zs=n(323).default,Bs=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onWindowResized=function(){n.props.autoplay&&n.slick&&n.slick.innerSlider&&n.slick.innerSlider.autoPlay&&n.slick.innerSlider.autoPlay()},n.saveSlick=function(e){n.slick=e},n.onWindowResized=ls()(n.onWindowResized,500,{leading:!1}),n}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.props.autoplay&&window.addEventListener("resize",this.onWindowResized),this.innerSlider=this.slick&&this.slick.innerSlider}},{key:"componentWillUnmount",value:function(){this.props.autoplay&&(window.removeEventListener("resize",this.onWindowResized),this.onWindowResized.cancel())}},{key:"next",value:function(){this.slick.slickNext()}},{key:"prev",value:function(){this.slick.slickPrev()}},{key:"goTo",value:function(e){this.slick.slickGoTo(e)}},{key:"render",value:function(){var e=Vo()({},this.props);"fade"===e.effect&&(e.fade=!0);var t=e.prefixCls;return e.vertical&&(t=t+" "+t+"-vertical"),Jo.createElement("div",{className:t},Jo.createElement(zs,Vo()({ref:this.saveSlick},e)))}}]),t}(Jo.Component),Ws=Bs;Bs.defaultProps={dots:!0,arrows:!1,prefixCls:"ant-carousel",draggable:!1};var Hs=n(42),Us=n(188),qs=n.n(Us),Ys=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Gs=function(e){function t(n){Oe(this,t);var r=Te(this,e.call(this,n));return r.saveMenuItem=function(e){return function(t){r.menuItems[e]=t}},r.menuItems={},r}return Ne(t,e),t.prototype.componentDidMount=function(){this.scrollActiveItemToView()},t.prototype.componentDidUpdate=function(e){!e.visible&&this.props.visible&&this.scrollActiveItemToView()},t.prototype.getOption=function(e,t){var n=this.props,r=n.prefixCls,o=n.expandTrigger,i=this.props.onSelect.bind(this,e,t),a={onClick:i},s=r+"-menu-item",l=e.children&&e.children.length>0;(l||!1===e.isLeaf)&&(s+=" "+r+"-menu-item-expand"),"hover"===o&&l&&(a={onMouseEnter:this.delayOnSelect.bind(this,i),onMouseLeave:this.delayOnSelect.bind(this),onClick:i}),this.isActiveOption(e,t)&&(s+=" "+r+"-menu-item-active",a.ref=this.saveMenuItem(t)),e.disabled&&(s+=" "+r+"-menu-item-disabled"),e.loading&&(s+=" "+r+"-menu-item-loading");var u="";return e.title?u=e.title:"string"==typeof e.label&&(u=e.label),Zo.a.createElement("li",Ys({key:e.value,className:s,title:u},a),e.label)},t.prototype.getActiveOptions=function(e){var t=e||this.props.activeValue,n=this.props.options;return qs()(n,function(e,n){return e.value===t[n]})},t.prototype.getShowOptions=function(){var e=this.props.options,t=this.getActiveOptions().map(function(e){return e.children}).filter(function(e){return!!e});return t.unshift(e),t},t.prototype.delayOnSelect=function(e){for(var t=this,n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),"function"==typeof e&&(this.delayTimer=setTimeout(function(){e(r),t.delayTimer=null},150))},t.prototype.scrollActiveItemToView=function(){for(var e=this.getShowOptions().length,t=0;t<e;t++){var n=this.menuItems[t];if(n){var r=Object(Qo.findDOMNode)(n);r.parentNode.scrollTop=r.offsetTop}}},t.prototype.isActiveOption=function(e,t){var n=this.props.activeValue;return(void 0===n?[]:n)[t]===e.value},t.prototype.render=function(){var e=this,t=this.props,n=t.prefixCls,r=t.dropdownMenuColumnStyle;return Zo.a.createElement("div",null,this.getShowOptions().map(function(t,o){return Zo.a.createElement("ul",{className:n+"-menu",key:o,style:r},t.map(function(t){return e.getOption(t,o)}))}))},t}(Zo.a.Component);Gs.defaultProps={options:[],value:[],activeValue:[],onSelect:function(){},prefixCls:"rc-cascader-menus",visible:!1,expandTrigger:"click"},Gs.propTypes={value:ni.a.array,activeValue:ni.a.array,options:ni.a.array.isRequired,prefixCls:ni.a.string,expandTrigger:ni.a.string,onSelect:ni.a.func,visible:ni.a.bool,dropdownMenuColumnStyle:ni.a.object};var Xs=Gs,$s=n(23),Js=n(337),Zs=n.n(Js),Qs=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},el={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}},bottomRight:{points:["tr","br"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topRight:{points:["br","tr"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}}},tl=function(e){function t(n){Me(this,t);var r=De(this,e.call(this,n));r.setPopupVisible=function(e){"popupVisible"in r.props||r.setState({popupVisible:e}),e&&!r.state.visible&&r.setState({activeValue:r.state.value}),r.props.onPopupVisibleChange(e)},r.handleChange=function(e,t,n){"keydown"===n.type&&n.keyCode!==$s.a.ENTER||(r.props.onChange(e.map(function(e){return e.value}),e),r.setPopupVisible(t.visible))},r.handlePopupVisibleChange=function(e){r.setPopupVisible(e)},r.handleMenuSelect=function(e,t,n){var o=r.trigger.getRootDomNode();o&&o.focus&&o.focus();var i=r.props,a=i.changeOnSelect,s=i.loadData,l=i.expandTrigger;if(e&&!e.disabled){var u=r.state.activeValue;u=u.slice(0,t+1),u[t]=e.value;var c=r.getActiveOptions(u);if(!1===e.isLeaf&&!e.children&&s)return a&&r.handleChange(c,{visible:!0},n),r.setState({activeValue:u}),void s(c);var p={};e.children&&e.children.length?!a||"click"!==n.type&&"keydown"!==n.type||("hover"===l?r.handleChange(c,{visible:!1},n):r.handleChange(c,{visible:!0},n),p.value=u):(r.handleChange(c,{visible:!1},n),p.value=u),p.activeValue=u,("value"in r.props||"keydown"===n.type&&n.keyCode!==$s.a.ENTER)&&delete p.value,r.setState(p)}},r.handleKeyDown=function(e){var t=r.props.children;if(t&&t.props.onKeyDown)return void t.props.onKeyDown(e);var n=[].concat(r.state.activeValue),o=n.length-1<0?0:n.length-1,i=r.getCurrentLevelOptions(),a=i.map(function(e){return e.value}).indexOf(n[o]);if(e.keyCode===$s.a.DOWN||e.keyCode===$s.a.UP||e.keyCode===$s.a.LEFT||e.keyCode===$s.a.RIGHT||e.keyCode===$s.a.ENTER||e.keyCode===$s.a.BACKSPACE||e.keyCode===$s.a.ESC){if(!r.state.popupVisible&&e.keyCode!==$s.a.BACKSPACE&&e.keyCode!==$s.a.LEFT&&e.keyCode!==$s.a.RIGHT&&e.keyCode!==$s.a.ESC)return void r.setPopupVisible(!0);if(e.keyCode===$s.a.DOWN||e.keyCode===$s.a.UP){var s=a;-1!==s?e.keyCode===$s.a.DOWN?(s+=1,s=s>=i.length?0:s):(s-=1,s=s<0?i.length-1:s):s=0,n[o]=i[s].value}else if(e.keyCode===$s.a.LEFT||e.keyCode===$s.a.BACKSPACE)n.splice(n.length-1,1);else if(e.keyCode===$s.a.RIGHT)i[a]&&i[a].children&&n.push(i[a].children[0].value);else if(e.keyCode===$s.a.ESC)return void r.setPopupVisible(!1);n&&0!==n.length||r.setPopupVisible(!1);var l=r.getActiveOptions(n),u=l[l.length-1];r.handleMenuSelect(u,l.length-1,e),r.props.onKeyDown&&r.props.onKeyDown(e)}},r.saveTrigger=function(e){r.trigger=e};var o=[];return"value"in n?o=n.value||[]:"defaultValue"in n&&(o=n.defaultValue||[]),r.state={popupVisible:n.popupVisible,activeValue:o,value:o},r}return Ie(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e&&!Zs()(this.props.value,e.value)){var t={value:e.value||[],activeValue:e.value||[]};"loadData"in e&&delete t.activeValue,this.setState(t)}"popupVisible"in e&&this.setState({popupVisible:e.popupVisible})},t.prototype.getPopupDOMNode=function(){return this.trigger.getPopupDomNode()},t.prototype.getCurrentLevelOptions=function(){var e=this.props.options,t=this.state.activeValue,n=void 0===t?[]:t,r=qs()(e,function(e,t){return e.value===n[t]});return r[r.length-2]?r[r.length-2].children:[].concat(e).filter(function(e){return!e.disabled})},t.prototype.getActiveOptions=function(e){return qs()(this.props.options,function(t,n){return t.value===e[n]})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.transitionName,r=e.popupClassName,o=e.options,i=e.disabled,a=e.builtinPlacements,s=e.popupPlacement,l=e.children,u=Pe(e,["prefixCls","transitionName","popupClassName","options","disabled","builtinPlacements","popupPlacement","children"]),c=Zo.a.createElement("div",null),p="";return o&&o.length>0?c=Zo.a.createElement(Xs,Qs({},this.props,{value:this.state.value,activeValue:this.state.activeValue,onSelect:this.handleMenuSelect,visible:this.state.popupVisible})):p=" "+t+"-menus-empty",Zo.a.createElement(Hs.a,Qs({ref:this.saveTrigger},u,{options:o,disabled:i,popupPlacement:s,builtinPlacements:a,popupTransitionName:n,action:i?[]:["click"],popupVisible:!i&&this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,prefixCls:t+"-menus",popupClassName:r+p,popup:c}),Object(Jo.cloneElement)(l,{onKeyDown:this.handleKeyDown,tabIndex:i?void 0:0}))},t}(Jo.Component);tl.defaultProps={options:[],onChange:function(){},onPopupVisibleChange:function(){},disabled:!1,transitionName:"",prefixCls:"rc-cascader",popupClassName:"",popupPlacement:"bottomLeft",builtinPlacements:el,expandTrigger:"click"},tl.propTypes={value:ni.a.array,defaultValue:ni.a.array,options:ni.a.array.isRequired,onChange:ni.a.func,onPopupVisibleChange:ni.a.func,popupVisible:ni.a.bool,disabled:ni.a.bool,transitionName:ni.a.string,popupClassName:ni.a.string,popupPlacement:ni.a.string,prefixCls:ni.a.string,dropdownMenuColumnStyle:ni.a.object,builtinPlacements:ni.a.object,loadData:ni.a.func,changeOnSelect:ni.a.bool,children:ni.a.node,onKeyDown:ni.a.func,expandTrigger:ni.a.string};var nl=tl,rl=nl,ol=n(338),il=n.n(ol),al=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},sl=function(e){return e.join(" / ")},ll=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleChange=function(e,t){if(n.setState({inputValue:""}),t[0].__IS_FILTERED_OPTION){var r=e[0],o=t[0].path;return void n.setValue(r,o)}n.setValue(e,t)},n.handlePopupVisibleChange=function(e){"popupVisible"in n.props||n.setState({popupVisible:e,inputFocused:e,inputValue:e?n.state.inputValue:""});var t=n.props.onPopupVisibleChange;t&&t(e)},n.handleInputBlur=function(){n.setState({inputFocused:!1})},n.handleInputClick=function(e){var t=n.state,r=t.inputFocused,o=t.popupVisible;(r||o)&&(e.stopPropagation(),e.nativeEvent.stopImmediatePropagation())},n.handleKeyDown=function(e){e.keyCode===$s.a.BACKSPACE&&e.stopPropagation()},n.handleInputChange=function(e){var t=e.target.value;n.setState({inputValue:t})},n.setValue=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];"value"in n.props||n.setState({value:e});var r=n.props.onChange;r&&r(e,t)},n.clearSelection=function(e){e.preventDefault(),e.stopPropagation(),n.state.inputValue?n.setState({inputValue:""}):(n.setValue([]),n.handlePopupVisibleChange(!1))},n.saveInput=function(e){n.input=e},n.state={value:e.value||e.defaultValue||[],inputValue:"",inputFocused:!1,popupVisible:e.popupVisible,flattenOptions:e.showSearch&&n.flattenTree(e.options,e.changeOnSelect)},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value||[]}),"popupVisible"in e&&this.setState({popupVisible:e.popupVisible}),e.showSearch&&this.props.options!==e.options&&this.setState({flattenOptions:this.flattenTree(e.options,e.changeOnSelect)})}},{key:"getLabel",value:function(){var e=this.props,t=e.options,n=e.displayRender,r=void 0===n?sl:n,o=this.state.value,i=Array.isArray(o[0])?o[0]:o,a=il()(t,function(e,t){return e.value===i[t]});return r(a.map(function(e){return e.label}),a)}},{key:"flattenTree",value:function(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],o=[];return e.forEach(function(e){var i=r.concat(e);!t&&e.children&&e.children.length||o.push(i),e.children&&(o=o.concat(n.flattenTree(e.children,t,i)))}),o}},{key:"generateFilteredOptions",value:function(e){var t=this,n=this.props,r=n.showSearch,o=n.notFoundContent,i=r.filter,a=void 0===i?je:i,s=r.render,l=void 0===s?Re:s,u=r.sort,c=void 0===u?Le:u,p=this.state,f=p.flattenOptions,d=p.inputValue,h=f.filter(function(e){return a(t.state.inputValue,e)}).sort(function(e,t){return c(e,t,d)});return h.length>0?h.map(function(t){return{__IS_FILTERED_OPTION:!0,path:t,label:l(d,t,e),value:t.map(function(e){return e.value}),disabled:t.some(function(e){return e.disabled})}}):[{label:o,value:"ANT_CASCADER_NOT_FOUND",disabled:!0}]}},{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"render",value:function(){var e,t,n,r=this.props,o=this.state,i=r.prefixCls,a=r.inputPrefixCls,s=r.children,l=r.placeholder,u=r.size,c=r.disabled,p=r.className,f=r.style,d=r.allowClear,h=r.showSearch,v=void 0!==h&&h,m=al(r,["prefixCls","inputPrefixCls","children","placeholder","size","disabled","className","style","allowClear","showSearch"]),y=o.value,g=ii()((e={},Ko()(e,a+"-lg","large"===u),Ko()(e,a+"-sm","small"===u),e)),b=d&&!c&&y.length>0||o.inputValue?Jo.createElement(Ni.a,{type:"cross-circle",className:i+"-picker-clear",onClick:this.clearSelection}):null,C=ii()((t={},Ko()(t,i+"-picker-arrow",!0),Ko()(t,i+"-picker-arrow-expand",o.popupVisible),t)),w=ii()(p,i+"-picker",(n={},Ko()(n,i+"-picker-with-value",o.inputValue),Ko()(n,i+"-picker-disabled",c),Ko()(n,i+"-picker-"+u,!!u),n)),S=Object(li.a)(m,["onChange","options","popupPlacement","transitionName","displayRender","onPopupVisibleChange","changeOnSelect","expandTrigger","popupVisible","getPopupContainer","loadData","popupClassName","filterOption","renderFilteredOption","sortFilteredOption","notFoundContent"]),x=r.options;o.inputValue&&(x=this.generateFilteredOptions(i)),o.popupVisible?this.cachedOptions=x:x=this.cachedOptions;var _={};1===(x||[]).length&&"ANT_CASCADER_NOT_FOUND"===x[0].value&&(_.height="auto"),!1!==v.matchInputWidth&&o.inputValue&&this.input&&(_.width=this.input.input.offsetWidth);var k=s||Jo.createElement("span",{style:f,className:w},Jo.createElement("span",{className:i+"-picker-label"},this.getLabel()),Jo.createElement(Vi,Vo()({},S,{ref:this.saveInput,prefixCls:a,placeholder:y&&y.length>0?void 0:l,className:i+"-input "+g,value:o.inputValue,disabled:c,readOnly:!v,autoComplete:"off",onClick:v?this.handleInputClick:void 0,onBlur:v?this.handleInputBlur:void 0,onKeyDown:this.handleKeyDown,onChange:v?this.handleInputChange:void 0})),b,Jo.createElement(Ni.a,{type:"down",className:C}));return Jo.createElement(rl,Vo()({},r,{options:x,value:y,popupVisible:o.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,onChange:this.handleChange,dropdownMenuColumnStyle:_}),k)}}]),t}(Jo.Component),ul=ll;ll.defaultProps={prefixCls:"ant-cascader",inputPrefixCls:"ant-input",placeholder:"Please select",transitionName:"slide-up",popupPlacement:"bottomLeft",options:[],disabled:!1,allowClear:!0,notFoundContent:"Not Found"};var cl=n(62),pl=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},fl=void 0;if("undefined"!=typeof window){var dl=function(e){return{media:e,matches:!1,addListener:function(){},removeListener:function(){}}};window.matchMedia=window.matchMedia||dl,fl=n(186)}var hl=["xxl","xl","lg","md","sm","xs"],vl={xs:"(max-width: 575px)",sm:"(min-width: 576px)",md:"(min-width: 768px)",lg:"(min-width: 992px)",xl:"(min-width: 1200px)",xxl:"(min-width: 1600px)"},ml=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={screens:{}},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){var e=this;Object.keys(vl).map(function(t){return fl.register(vl[t],{match:function(){"object"===$o()(e.props.gutter)&&e.setState(function(e){return{screens:Vo()({},e.screens,Ko()({},t,!0))}})},unmatch:function(){"object"===$o()(e.props.gutter)&&e.setState(function(e){return{screens:Vo()({},e.screens,Ko()({},t,!1))}})},destroy:function(){}})})}},{key:"componentWillUnmount",value:function(){Object.keys(vl).map(function(e){return fl.unregister(vl[e])})}},{key:"getGutter",value:function(){var e=this.props.gutter;if("object"===(void 0===e?"undefined":$o()(e)))for(var t=0;t<=hl.length;t++){var n=hl[t];if(this.state.screens[n]&&void 0!==e[n])return e[n]}return e}},{key:"render",value:function(){var e,t=this.props,n=t.type,r=t.justify,o=t.align,i=t.className,a=t.style,s=t.children,l=t.prefixCls,u=void 0===l?"ant-row":l,c=pl(t,["type","justify","align","className","style","children","prefixCls"]),p=this.getGutter(),f=ii()((e={},Ko()(e,u,!n),Ko()(e,u+"-"+n,n),Ko()(e,u+"-"+n+"-"+r,n&&r),Ko()(e,u+"-"+n+"-"+o,n&&o),e),i),d=p>0?Vo()({marginLeft:p/-2,marginRight:p/-2},a):a,h=Jo.Children.map(s,function(e){return e?e.props&&p>0?Object(Jo.cloneElement)(e,{style:Vo()({paddingLeft:p/2,paddingRight:p/2},e.props.style)}):e:null}),v=Vo()({},c);return delete v.gutter,Jo.createElement("div",Vo()({},v,{className:f,style:d}),h)}}]),t}(Jo.Component),yl=ml;ml.defaultProps={gutter:0},ml.propTypes={type:ni.a.string,align:ni.a.string,justify:ni.a.string,className:ni.a.string,children:ni.a.node,gutter:ni.a.oneOfType([ni.a.object,ni.a.number]),prefixCls:ni.a.string};var gl=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},bl=ni.a.oneOfType([ni.a.string,ni.a.number]),Cl=ni.a.oneOfType([ni.a.object,ni.a.number]),wl=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t=this.props,n=t.span,r=t.order,o=t.offset,i=t.push,a=t.pull,s=t.className,l=t.children,u=t.prefixCls,c=void 0===u?"ant-col":u,p=gl(t,["span","order","offset","push","pull","className","children","prefixCls"]),f={};["xs","sm","md","lg","xl","xxl"].forEach(function(e){var n,r={};"number"==typeof t[e]?r.span=t[e]:"object"===$o()(t[e])&&(r=t[e]||{}),delete p[e],f=Vo()({},f,(n={},Ko()(n,c+"-"+e+"-"+r.span,void 0!==r.span),Ko()(n,c+"-"+e+"-order-"+r.order,r.order||0===r.order),Ko()(n,c+"-"+e+"-offset-"+r.offset,r.offset||0===r.offset),Ko()(n,c+"-"+e+"-push-"+r.push,r.push||0===r.push),Ko()(n,c+"-"+e+"-pull-"+r.pull,r.pull||0===r.pull),n))});var d=ii()((e={},Ko()(e,c+"-"+n,void 0!==n),Ko()(e,c+"-order-"+r,r),Ko()(e,c+"-offset-"+o,o),Ko()(e,c+"-push-"+i,i),Ko()(e,c+"-pull-"+a,a),e),s,f);return Jo.createElement("div",Vo()({},p,{className:d}),l)}}]),t}(Jo.Component),Sl=wl;wl.propTypes={span:bl,order:bl,offset:bl,push:bl,pull:bl,className:ni.a.string,children:ni.a.node,xs:Cl,sm:Cl,md:Cl,lg:Cl,xl:Cl,xxl:Cl};var xl=Sl,_l=ga()({displayName:"MonthPanel",propTypes:{onChange:ni.a.func,disabledDate:ni.a.func,onSelect:ni.a.func},getDefaultProps:function(){return{onChange:ze,onSelect:ze}},getInitialState:function(){var e=this.props;return this.nextYear=Ve.bind(this,1),this.previousYear=Ve.bind(this,-1),this.prefixCls=e.rootPrefixCls+"-month-panel",{value:e.value||e.defaultValue}},componentWillReceiveProps:function(e){"value"in e&&this.setState({value:e.value})},setAndChangeValue:function(e){this.setValue(e),this.props.onChange(e)},setAndSelectValue:function(e){this.setValue(e),this.props.onSelect(e)},setValue:function(e){"value"in this.props||this.setState({value:e})},render:function(){var e=this.props,t=this.state.value,n=e.cellRender,r=e.contentRender,o=e.locale,i=t.year(),a=this.prefixCls;return Zo.a.createElement("div",{className:a,style:e.style},Zo.a.createElement("div",null,Zo.a.createElement("div",{className:a+"-header"},Zo.a.createElement("a",{className:a+"-prev-year-btn",role:"button",onClick:this.previousYear,title:o.previousYear}),Zo.a.createElement("a",{className:a+"-year-select",role:"button",onClick:e.onYearPanelShow,title:o.yearSelect},Zo.a.createElement("span",{className:a+"-year-select-content"},i),Zo.a.createElement("span",{className:a+"-year-select-arrow"},"x")),Zo.a.createElement("a",{className:a+"-next-year-btn",role:"button",onClick:this.nextYear,title:o.nextYear})),Zo.a.createElement("div",{className:a+"-body"},Zo.a.createElement(Ta,{disabledDate:e.disabledDate,onSelect:this.setAndSelectValue,locale:o,value:t,cellRender:n,contentRender:r,prefixCls:a}))))}}),kl=_l,El=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));return r.prefixCls=n.rootPrefixCls+"-year-panel",r.state={value:n.value||n.defaultValue},r.nextDecade=Be.bind(r,10),r.previousDecade=Be.bind(r,-10),r}return Go()(t,e),t.prototype.years=function(){for(var e=this.state.value,t=e.year(),n=10*parseInt(t/10,10),r=n-1,o=[],i=0,a=0;a<4;a++){o[a]=[];for(var s=0;s<3;s++){var l=r+i,u=String(l);o[a][s]={content:u,year:l,title:u},i++}}return o},t.prototype.render=function(){var e=this,t=this.props,n=this.state.value,r=t.locale,o=this.years(),i=n.year(),a=10*parseInt(i/10,10),s=a+9,l=this.prefixCls,u=o.map(function(t,n){var r=t.map(function(t){var n,r=(n={},n[l+"-cell"]=1,n[l+"-selected-cell"]=t.year===i,n[l+"-last-decade-cell"]=t.year<a,n[l+"-next-decade-cell"]=t.year>s,n),o=void 0;return o=t.year<a?e.previousDecade:t.year>s?e.nextDecade:We.bind(e,t.year),Zo.a.createElement("td",{role:"gridcell",title:t.title,key:t.content,onClick:o,className:ii()(r)},Zo.a.createElement("a",{className:l+"-year"},t.content))});return Zo.a.createElement("tr",{key:n,role:"row"},r)});return Zo.a.createElement("div",{className:this.prefixCls},Zo.a.createElement("div",null,Zo.a.createElement("div",{className:l+"-header"},Zo.a.createElement("a",{className:l+"-prev-decade-btn",role:"button",onClick:this.previousDecade,title:r.previousDecade}),Zo.a.createElement("a",{className:l+"-decade-select",role:"button",onClick:t.onDecadePanelShow,title:r.decadeSelect},Zo.a.createElement("span",{className:l+"-decade-select-content"},a,"-",s),Zo.a.createElement("span",{className:l+"-decade-select-arrow"},"x")),Zo.a.createElement("a",{className:l+"-next-decade-btn",role:"button",onClick:this.nextDecade,title:r.nextDecade})),Zo.a.createElement("div",{className:l+"-body"},Zo.a.createElement("table",{className:l+"-table",cellSpacing:"0",role:"grid"},Zo.a.createElement("tbody",{className:l+"-tbody"},u)))))},t}(Zo.a.Component),Ol=El;El.propTypes={rootPrefixCls:ni.a.string,value:ni.a.object,defaultValue:ni.a.object},El.defaultProps={onSelect:function(){}};var Tl=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));return r.state={value:n.value||n.defaultValue},r.prefixCls=n.rootPrefixCls+"-decade-panel",r.nextCentury=He.bind(r,100),r.previousCentury=He.bind(r,-100),r}return Go()(t,e),t.prototype.render=function(){for(var e=this,t=this.state.value,n=this.props.locale,r=t.year(),o=100*parseInt(r/100,10),i=o-10,a=o+99,s=[],l=0,u=this.prefixCls,c=0;c<4;c++){s[c]=[];for(var p=0;p<3;p++){var f=i+10*l,d=i+10*l+9;s[c][p]={startDecade:f,endDecade:d},l++}}var h=s.map(function(t,n){var i=t.map(function(t){var n,i=t.startDecade,s=t.endDecade,l=i<o,c=s>a,p=(n={},n[u+"-cell"]=1,n[u+"-selected-cell"]=i<=r&&r<=s,n[u+"-last-century-cell"]=l,n[u+"-next-century-cell"]=c,n),f=i+"-"+s,d=void 0;return d=l?e.previousCentury:c?e.nextCentury:Ue.bind(e,i),Zo.a.createElement("td",{key:i,onClick:d,role:"gridcell",className:ii()(p)},Zo.a.createElement("a",{className:u+"-decade"},f))});return Zo.a.createElement("tr",{key:n,role:"row"},i)});return Zo.a.createElement("div",{className:this.prefixCls},Zo.a.createElement("div",{className:u+"-header"},Zo.a.createElement("a",{className:u+"-prev-century-btn",role:"button",onClick:this.previousCentury,title:n.previousCentury}),Zo.a.createElement("div",{className:u+"-century"},o,"-",a),Zo.a.createElement("a",{className:u+"-next-century-btn",role:"button",onClick:this.nextCentury,title:n.nextCentury})),Zo.a.createElement("div",{className:u+"-body"},Zo.a.createElement("table",{className:u+"-table",cellSpacing:"0",role:"grid"},Zo.a.createElement("tbody",{className:u+"-tbody"},h))))},t}(Zo.a.Component),Nl=Tl;Tl.propTypes={locale:ni.a.object,value:ni.a.object,defaultValue:ni.a.object,rootPrefixCls:ni.a.string},Tl.defaultProps={onSelect:function(){}};var Pl=ga()({displayName:"CalendarHeader",propTypes:{prefixCls:ni.a.string,value:ni.a.object,onValueChange:ni.a.func,showTimePicker:ni.a.bool,onPanelChange:ni.a.func,locale:ni.a.object,enablePrev:ni.a.any,enableNext:ni.a.any,disabledMonth:ni.a.func},getDefaultProps:function(){return{enableNext:1,enablePrev:1,onPanelChange:function(){},onValueChange:function(){}}},getInitialState:function(){return this.nextMonth=qe.bind(this,1),this.previousMonth=qe.bind(this,-1),this.nextYear=Ye.bind(this,1),this.previousYear=Ye.bind(this,-1),{yearPanelReferer:null}},onMonthSelect:function(e){this.props.onPanelChange(e,"date"),this.props.onMonthSelect?this.props.onMonthSelect(e):this.props.onValueChange(e)},onYearSelect:function(e){var t=this.state.yearPanelReferer;this.setState({yearPanelReferer:null}),this.props.onPanelChange(e,t),this.props.onValueChange(e)},onDecadeSelect:function(e){this.props.onPanelChange(e,"year"),this.props.onValueChange(e)},monthYearElement:function(e){var t=this,n=this.props,r=n.prefixCls,o=n.locale,i=n.value,a=i.localeData(),s=o.monthBeforeYear,l=r+"-"+(s?"my-select":"ym-select"),u=Zo.a.createElement("a",{className:r+"-year-select",role:"button",onClick:e?null:function(){return t.showYearPanel("date")},title:o.yearSelect},i.format(o.yearFormat)),c=Zo.a.createElement("a",{className:r+"-month-select",role:"button",onClick:e?null:this.showMonthPanel,title:o.monthSelect},a.monthsShort(i)),p=void 0;e&&(p=Zo.a.createElement("a",{className:r+"-day-select",role:"button"},i.format(o.dayFormat)));var f=[];return f=s?[c,p,u]:[u,c,p],Zo.a.createElement("span",{className:l},Fe(f))},showMonthPanel:function(){this.props.onPanelChange(null,"month")},showYearPanel:function(e){this.setState({yearPanelReferer:e}),this.props.onPanelChange(null,"year")},showDecadePanel:function(){this.props.onPanelChange(null,"decade")},render:function(){var e=this,t=this.props,n=t.prefixCls,r=t.locale,o=t.mode,i=t.value,a=t.showTimePicker,s=t.enableNext,l=t.enablePrev,u=t.disabledMonth,c=null;return"month"===o&&(c=Zo.a.createElement(kl,{locale:r,defaultValue:i,rootPrefixCls:n,onSelect:this.onMonthSelect,onYearPanelShow:function(){return e.showYearPanel("month")},disabledDate:u,cellRender:t.monthCellRender,contentRender:t.monthCellContentRender})),"year"===o&&(c=Zo.a.createElement(Ol,{locale:r,defaultValue:i,rootPrefixCls:n,onSelect:this.onYearSelect,onDecadePanelShow:this.showDecadePanel})),"decade"===o&&(c=Zo.a.createElement(Nl,{locale:r,defaultValue:i,rootPrefixCls:n,onSelect:this.onDecadeSelect})),Zo.a.createElement("div",{className:n+"-header"},Zo.a.createElement("div",{style:{position:"relative"}},Ge(l&&!a,Zo.a.createElement("a",{className:n+"-prev-year-btn",role:"button",onClick:this.previousYear,title:r.previousYear})),Ge(l&&!a,Zo.a.createElement("a",{className:n+"-prev-month-btn",role:"button",onClick:this.previousMonth,title:r.previousMonth})),this.monthYearElement(a),Ge(s&&!a,Zo.a.createElement("a",{className:n+"-next-month-btn",onClick:this.nextMonth,title:r.nextMonth})),Ge(s&&!a,Zo.a.createElement("a",{className:n+"-next-year-btn",onClick:this.nextYear,title:r.nextYear}))),c)}}),Ml=Pl,Dl=ga()({displayName:"CalendarFooter",propTypes:{prefixCls:ni.a.string,showDateInput:ni.a.bool,disabledTime:ni.a.any,timePicker:ni.a.element,selectedValue:ni.a.any,showOk:ni.a.bool,onSelect:ni.a.func,value:ni.a.object,renderFooter:ni.a.func,defaultValue:ni.a.object},onSelect:function(e){this.props.onSelect(e)},getRootDOMNode:function(){return ei.a.findDOMNode(this)},render:function(){var e=this.props,t=e.value,n=e.prefixCls,r=e.showOk,o=e.timePicker,i=e.renderFooter,a=null,s=i();if(e.showToday||o||s){var l,u=void 0;e.showToday&&(u=Zo.a.createElement(Xe,Vo()({},e,{value:t})));var c=void 0;(!0===r||!1!==r&&e.timePicker)&&(c=Zo.a.createElement($e,e));var p=void 0;e.timePicker&&(p=Zo.a.createElement(Je,e));var f=void 0;(u||p||c)&&(f=Zo.a.createElement("span",{className:n+"-footer-btn"},Fe([u,p,c])));var d=ii()((l={},l[n+"-footer"]=!0,l[n+"-footer-show-ok"]=c,l));a=Zo.a.createElement("div",{className:d},s,f)}return a}}),Il=Dl,Al=ga()({displayName:"DateInput",propTypes:{prefixCls:ni.a.string,timePicker:ni.a.object,value:ni.a.object,disabledTime:ni.a.any,format:ni.a.string,locale:ni.a.object,disabledDate:ni.a.func,onChange:ni.a.func,onClear:ni.a.func,placeholder:ni.a.string,onSelect:ni.a.func,selectedValue:ni.a.object},getInitialState:function(){var e=this.props.selectedValue;return{str:e&&e.format(this.props.format)||"",invalid:!1}},componentWillReceiveProps:function(e){this.cachedSelectionStart=this.dateInputInstance.selectionStart,this.cachedSelectionEnd=this.dateInputInstance.selectionEnd;var t=e.selectedValue;this.setState({str:t&&t.format(e.format)||"",invalid:!1})},componentDidUpdate:function(){this.state.invalid||this.dateInputInstance.setSelectionRange(this.cachedSelectionStart,this.cachedSelectionEnd)},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=void 0,r=this.props,o=r.disabledDate,i=r.format,a=r.onChange;if(t){var s=ma()(t,i,!0);if(!s.isValid())return void this.setState({invalid:!0});if(n=this.props.value.clone(),n.year(s.year()).month(s.month()).date(s.date()).hour(s.hour()).minute(s.minute()).second(s.second()),!n||o&&o(n))return void this.setState({invalid:!0});var l=this.props.selectedValue;l&&n?l.isSame(n)||a(n):l!==n&&a(n)}else a(null);this.setState({invalid:!1})},onClear:function(){this.setState({str:""}),this.props.onClear(null)},getRootDOMNode:function(){return ei.a.findDOMNode(this)},focus:function(){this.dateInputInstance&&this.dateInputInstance.focus()},saveDateInput:function(e){this.dateInputInstance=e},render:function(){var e=this.props,t=this.state,n=t.invalid,r=t.str,o=e.locale,i=e.prefixCls,a=e.placeholder,s=n?i+"-input-invalid":"";return Zo.a.createElement("div",{className:i+"-input-wrap"},Zo.a.createElement("div",{className:i+"-date-input-wrap"},Zo.a.createElement("input",{ref:this.saveDateInput,className:i+"-input "+s,value:r,disabled:e.disabled,placeholder:a,onChange:this.onInputChange})),e.showClear?Zo.a.createElement("a",{className:i+"-clear-btn",role:"button",title:o.clear,onClick:this.onClear}):null)}}),jl=Al,Rl=ga()({displayName:"Calendar",propTypes:{prefixCls:ni.a.string,className:ni.a.string,style:ni.a.object,defaultValue:ni.a.object,value:ni.a.object,selectedValue:ni.a.object,mode:ni.a.oneOf(["time","date","month","year","decade"]),locale:ni.a.object,showDateInput:ni.a.bool,showWeekNumber:ni.a.bool,showToday:ni.a.bool,showOk:ni.a.bool,onSelect:ni.a.func,onOk:ni.a.func,onKeyDown:ni.a.func,timePicker:ni.a.element,dateInputPlaceholder:ni.a.any,onClear:ni.a.func,onChange:ni.a.func,onPanelChange:ni.a.func,disabledDate:ni.a.func,disabledTime:ni.a.any,renderFooter:ni.a.func,renderSidebar:ni.a.func},mixins:[Da,Pa],getDefaultProps:function(){return{showToday:!0,showDateInput:!0,timePicker:null,onOk:Ze,onPanelChange:Ze}},getInitialState:function(){return{mode:this.props.mode||"date"}},componentWillReceiveProps:function(e){"mode"in e&&this.state.mode!==e.mode&&this.setState({mode:e.mode})},onKeyDown:function(e){if("input"!==e.target.nodeName.toLowerCase()){var t=e.keyCode,n=e.ctrlKey||e.metaKey,r=this.props.disabledDate,o=this.state.value;switch(t){case $s.a.DOWN:return ot.call(this,1),e.preventDefault(),1;case $s.a.UP:return ot.call(this,-1),e.preventDefault(),1;case $s.a.LEFT:return n?rt.call(this,-1):it.call(this,-1),e.preventDefault(),1;case $s.a.RIGHT:return n?rt.call(this,1):it.call(this,1),e.preventDefault(),1;case $s.a.HOME:return Qe.call(this),e.preventDefault(),1;case $s.a.END:return et.call(this),e.preventDefault(),1;case $s.a.PAGE_DOWN:return nt.call(this,1),e.preventDefault(),1;case $s.a.PAGE_UP:return nt.call(this,-1),e.preventDefault(),1;case $s.a.ENTER:return r&&r(o)||this.onSelect(o,{source:"keyboard"}),e.preventDefault(),1;default:return this.props.onKeyDown(e),1}}},onClear:function(){this.onSelect(null),this.props.onClear()},onOk:function(){var e=this.state.selectedValue;this.isAllowedDate(e)&&this.props.onOk(e)},onDateInputChange:function(e){this.onSelect(e,{source:"dateInput"})},onDateTableSelect:function(e){var t=this.props.timePicker;if(!this.state.selectedValue&&t){var n=t.props.defaultValue;n&&P(n,e)}this.onSelect(e)},onToday:function(){var e=this.state.value,t=E(e);this.onSelect(t,{source:"todayButton"})},onPanelChange:function(e,t){var n=this.props,r=this.state;"mode"in n||this.setState({mode:t}),n.onPanelChange(e||r.value,t)},getRootDOMNode:function(){return ei.a.findDOMNode(this)},openTimePicker:function(){this.onPanelChange(null,"time")},closeTimePicker:function(){this.onPanelChange(null,"date")},render:function(){var e=this.props,t=this.state,n=e.locale,r=e.prefixCls,o=e.disabledDate,i=e.dateInputPlaceholder,a=e.timePicker,s=e.disabledTime,l=t.value,u=t.selectedValue,c=t.mode,p="time"===c,f=p&&s&&a?M(u,s):null,d=null;if(a&&p){var h=Vo()({showHour:!0,showSecond:!0,showMinute:!0},a.props,f,{onChange:this.onDateInputChange,value:u,disabledTime:s});void 0!==a.props.defaultValue&&(h.defaultOpenValue=a.props.defaultValue),d=Zo.a.cloneElement(a,h)}var v=e.showDateInput?Zo.a.createElement(jl,{format:this.getFormat(),key:"date-input",value:l,locale:n,placeholder:i,showClear:!0,disabledTime:s,disabledDate:o,onClear:this.onClear,prefixCls:r,selectedValue:u,onChange:this.onDateInputChange}):null,m=[e.renderSidebar(),Zo.a.createElement("div",{className:r+"-panel",key:"panel"},v,Zo.a.createElement("div",{className:r+"-date-panel"},Zo.a.createElement(Ml,{locale:n,mode:c,value:l,onValueChange:this.setValue,onPanelChange:this.onPanelChange,showTimePicker:p,prefixCls:r}),a&&p?Zo.a.createElement("div",{className:r+"-time-picker"},Zo.a.createElement("div",{className:r+"-time-picker-panel"},d)):null,Zo.a.createElement("div",{className:r+"-body"},Zo.a.createElement(Ea,{locale:n,value:l,selectedValue:u,prefixCls:r,dateRender:e.dateRender,onSelect:this.onDateTableSelect,disabledDate:o,showWeekNumber:e.showWeekNumber})),Zo.a.createElement(Il,{showOk:e.showOk,renderFooter:e.renderFooter,locale:n,prefixCls:r,showToday:e.showToday,disabledTime:s,showTimePicker:p,showDateInput:e.showDateInput,timePicker:a,selectedValue:u,value:l,disabledDate:o,okDisabled:!this.isAllowedDate(u),onOk:this.onOk,onSelect:this.onSelect,onToday:this.onToday,onOpenTimePicker:this.openTimePicker,onCloseTimePicker:this.closeTimePicker})))];return this.renderRoot({children:m,className:e.showWeekNumber?r+"-week-number":""})}}),Ll=Rl,Kl=Ll,Fl=ga()({displayName:"MonthCalendar",propTypes:{monthCellRender:ni.a.func,dateCellRender:ni.a.func},mixins:[Da,Pa],getInitialState:function(){return{mode:"month"}},onKeyDown:function(e){var t=e.keyCode,n=e.ctrlKey||e.metaKey,r=this.state.value,o=this.props.disabledDate,i=r;switch(t){case $s.a.DOWN:i=r.clone(),i.add(3,"months");break;case $s.a.UP:i=r.clone(),i.add(-3,"months");break;case $s.a.LEFT:i=r.clone(),n?i.add(-1,"years"):i.add(-1,"months");break;case $s.a.RIGHT:i=r.clone(),n?i.add(1,"years"):i.add(1,"months");break;case $s.a.ENTER:return o&&o(r)||this.onSelect(r),e.preventDefault(),1;default:return}if(i!==r)return this.setValue(i),e.preventDefault(),1},handlePanelChange:function(e,t){"date"!==t&&this.setState({mode:t})},render:function(){var e=this.props,t=this.state,n=t.mode,r=t.value,o=Zo.a.createElement("div",{className:e.prefixCls+"-month-calendar-content"},Zo.a.createElement("div",{className:e.prefixCls+"-month-header-wrap"},Zo.a.createElement(Ml,{prefixCls:e.prefixCls,mode:n,value:r,locale:e.locale,disabledMonth:e.disabledDate,monthCellRender:e.monthCellRender,monthCellContentRender:e.monthCellContentRender,onMonthSelect:this.onSelect,onValueChange:this.setValue,onPanelChange:this.handlePanelChange})),Zo.a.createElement(Il,{prefixCls:e.prefixCls,renderFooter:e.renderFooter}));return this.renderRoot({className:e.prefixCls+"-month-calendar",children:o})}}),Vl=Fl,zl=n(120),Bl={adjustX:1,adjustY:1},Wl=[0,0],Hl={bottomLeft:{points:["tl","tl"],overflow:Bl,offset:[0,-3],targetOffset:Wl},bottomRight:{points:["tr","tr"],overflow:Bl,offset:[0,-3],targetOffset:Wl},topRight:{points:["br","br"],overflow:Bl,offset:[0,3],targetOffset:Wl},topLeft:{points:["bl","bl"],overflow:Bl,offset:[0,3],targetOffset:Wl}},Ul=Hl,ql=ga()({displayName:"Picker",propTypes:{animation:ni.a.oneOfType([ni.a.func,ni.a.string]),disabled:ni.a.bool,transitionName:ni.a.string,onChange:ni.a.func,onOpenChange:ni.a.func,children:ni.a.func,getCalendarContainer:ni.a.func,calendar:ni.a.element,style:ni.a.object,open:ni.a.bool,defaultOpen:ni.a.bool,prefixCls:ni.a.string,placement:ni.a.any,value:ni.a.oneOfType([ni.a.object,ni.a.array]),defaultValue:ni.a.oneOfType([ni.a.object,ni.a.array]),align:ni.a.object},getDefaultProps:function(){return{prefixCls:"rc-calendar-picker",style:{},align:{},placement:"bottomLeft",defaultOpen:!1,onChange:at,onOpenChange:at}},getInitialState:function(){var e=this.props,t=void 0;t="open"in e?e.open:e.defaultOpen;var n=e.value||e.defaultValue;return this.saveCalendarRef=st.bind(this,"calendarInstance"),{open:t,value:n}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},componentDidUpdate:function(e,t){!t.open&&this.state.open&&(this.focusTimeout=setTimeout(this.focusCalendar,0,this))},componentWillUnmount:function(){clearTimeout(this.focusTimeout)},onCalendarKeyDown:function(e){e.keyCode===$s.a.ESC&&(e.stopPropagation(),this.close(this.focus))},onCalendarSelect:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.props;"value"in n||this.setState({value:e}),("keyboard"===t.source||!n.calendar.props.timePicker&&"dateInput"!==t.source||"todayButton"===t.source)&&this.close(this.focus),n.onChange(e)},onKeyDown:function(e){e.keyCode!==$s.a.DOWN||this.state.open||(this.open(),e.preventDefault())},onCalendarOk:function(){this.close(this.focus)},onCalendarClear:function(){this.close(this.focus)},onVisibleChange:function(e){this.setOpen(e)},getCalendarElement:function(){var e=this.props,t=this.state,n=e.calendar.props,r=t.value,o=r,i={ref:this.saveCalendarRef,defaultValue:o||n.defaultValue,selectedValue:r,onKeyDown:this.onCalendarKeyDown,onOk:Object(zl.a)(n.onOk,this.onCalendarOk),onSelect:Object(zl.a)(n.onSelect,this.onCalendarSelect),onClear:Object(zl.a)(n.onClear,this.onCalendarClear)};return Zo.a.cloneElement(e.calendar,i)},setOpen:function(e,t){var n=this.props.onOpenChange;this.state.open!==e&&("open"in this.props||this.setState({open:e},t),n(e))},open:function(e){this.setOpen(!0,e)},close:function(e){this.setOpen(!1,e)},focus:function(){this.state.open||ei.a.findDOMNode(this).focus()},focusCalendar:function(){this.state.open&&this.calendarInstance&&this.calendarInstance.focus()},render:function(){var e=this.props,t=e.prefixCls,n=e.placement,r=e.style,o=e.getCalendarContainer,i=e.align,a=e.animation,s=e.disabled,l=e.dropdownClassName,u=e.transitionName,c=e.children,p=this.state;return Zo.a.createElement(Hs.a,{popup:this.getCalendarElement(),popupAlign:i,builtinPlacements:Ul,popupPlacement:n,action:s&&!p.open?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:o,popupStyle:r,popupAnimation:a,popupTransitionName:u,popupVisible:p.open,onPopupVisibleChange:this.onVisibleChange,prefixCls:t,popupClassName:l},Zo.a.cloneElement(c(p,e),{onKeyDown:this.onKeyDown}))}}),Yl=ql,Gl=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));Xl.call(n);var r=e.value,o=e.format;return n.state={str:r&&r.format(o)||"",invalid:!1},n}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){var e=this;if(this.props.focusOnOpen){(window.requestAnimationFrame||window.setTimeout)(function(){e.refs.input.focus(),e.refs.input.select()})}}},{key:"componentWillReceiveProps",value:function(e){var t=e.value,n=e.format;this.setState({str:t&&t.format(n)||"",invalid:!1})}},{key:"getClearButton",value:function(){var e=this.props,t=e.prefixCls;return e.allowEmpty?Zo.a.createElement("a",{className:t+"-clear-btn",role:"button",title:this.props.clearText,onMouseDown:this.onClear}):null}},{key:"getProtoValue",value:function(){return this.props.value||this.props.defaultOpenValue}},{key:"getInput",value:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=e.inputReadOnly,o=this.state,i=o.invalid,a=o.str,s=i?t+"-input-invalid":"";return Zo.a.createElement("input",{className:t+"-input "+s,ref:"input",onKeyDown:this.onKeyDown,value:a,placeholder:n,onChange:this.onInputChange,readOnly:!!r})}},{key:"render",value:function(){var e=this.props.prefixCls;return Zo.a.createElement("div",{className:e+"-input-wrap"},this.getInput(),this.getClearButton())}}]),t}(Jo.Component);Gl.propTypes={format:ni.a.string,prefixCls:ni.a.string,disabledDate:ni.a.func,placeholder:ni.a.string,clearText:ni.a.string,value:ni.a.object,inputReadOnly:ni.a.bool,hourOptions:ni.a.array,minuteOptions:ni.a.array,secondOptions:ni.a.array,disabledHours:ni.a.func,disabledMinutes:ni.a.func,disabledSeconds:ni.a.func,onChange:ni.a.func,onClear:ni.a.func,onEsc:ni.a.func,allowEmpty:ni.a.bool,defaultOpenValue:ni.a.object,currentSelectPanel:ni.a.string,focusOnOpen:ni.a.bool,onKeyDown:ni.a.func},Gl.defaultProps={inputReadOnly:!1};var Xl=function(){var e=this;this.onInputChange=function(t){var n=t.target.value;e.setState({str:n});var r=e.props,o=r.format,i=r.hourOptions,a=r.minuteOptions,s=r.secondOptions,l=r.disabledHours,u=r.disabledMinutes,c=r.disabledSeconds,p=r.onChange,f=r.allowEmpty;if(n){var d=e.props.value,h=e.getProtoValue().clone(),v=ma()(n,o,!0);if(!v.isValid())return void e.setState({invalid:!0});if(h.hour(v.hour()).minute(v.minute()).second(v.second()),i.indexOf(h.hour())<0||a.indexOf(h.minute())<0||s.indexOf(h.second())<0)return void e.setState({invalid:!0});var m=l(),y=u(h.hour()),g=c(h.hour(),h.minute());if(m&&m.indexOf(h.hour())>=0||y&&y.indexOf(h.minute())>=0||g&&g.indexOf(h.second())>=0)return void e.setState({invalid:!0});if(d){if(d.hour()!==h.hour()||d.minute()!==h.minute()||d.second()!==h.second()){var b=d.clone();b.hour(h.hour()),b.minute(h.minute()),b.second(h.second()),p(b)}}else d!==h&&p(h)}else{if(!f)return void e.setState({invalid:!0});p(null)}e.setState({invalid:!1})},this.onKeyDown=function(t){var n=e.props,r=n.onEsc,o=n.onKeyDown;27===t.keyCode&&r(),o(t)},this.onClear=function(){e.setState({str:""}),e.props.onClear()}},$l=Gl,Jl=function e(t,n,r){var o=window.requestAnimationFrame||function(){return setTimeout(arguments[0],10)};if(r<=0)return void(t.scrollTop=n);var i=n-t.scrollTop,a=i/r*10;o(function(){t.scrollTop=t.scrollTop+a,t.scrollTop!==n&&e(t,n,r-10)})},Zl=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.state={active:!1},r.onSelect=function(e){var t=r.props;(0,t.onSelect)(t.type,e)},r.handleMouseEnter=function(e){r.setState({active:!0}),r.props.onMouseEnter(e)},r.handleMouseLeave=function(){r.setState({active:!1})},r.saveList=function(e){r.list=e},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.scrollToSelected(0)}},{key:"componentDidUpdate",value:function(e){e.selectedIndex!==this.props.selectedIndex&&this.scrollToSelected(120)}},{key:"getOptions",value:function(){var e=this,t=this.props,n=t.options,r=t.selectedIndex,o=t.prefixCls;return n.map(function(t,n){var i,a=ii()((i={},Ko()(i,o+"-select-option-selected",r===n),Ko()(i,o+"-select-option-disabled",t.disabled),i)),s=null;return t.disabled||(s=e.onSelect.bind(e,t.value)),Zo.a.createElement("li",{className:a,key:n,onClick:s,disabled:t.disabled},t.value)})}},{key:"scrollToSelected",value:function(e){var t=ei.a.findDOMNode(this),n=ei.a.findDOMNode(this.list);if(n){var r=this.props.selectedIndex;r<0&&(r=0);var o=n.children[r],i=o.offsetTop;Jl(t,i,e)}}},{key:"render",value:function(){var e;if(0===this.props.options.length)return null;var t=this.props.prefixCls,n=ii()((e={},Ko()(e,t+"-select",1),Ko()(e,t+"-select-active",this.state.active),e));return Zo.a.createElement("div",{className:n,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave},Zo.a.createElement("ul",{ref:this.saveList},this.getOptions()))}}]),t}(Jo.Component);Zl.propTypes={prefixCls:ni.a.string,options:ni.a.array,selectedIndex:ni.a.number,type:ni.a.string,onSelect:ni.a.func,onMouseEnter:ni.a.func};var Ql=Zl,eu=function(e,t){var n=""+e;e<10&&(n="0"+e);var r=!1;return t&&t.indexOf(e)>=0&&(r=!0),{value:n,disabled:r}},tu=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.onItemChange=function(e,t){var n=r.props,o=n.onChange,i=n.defaultOpenValue,a=n.use12Hours,s=(r.props.value||i).clone();if("hour"===e)a?r.props.isAM?s.hour(+t%12):s.hour(+t%12+12):s.hour(+t);else if("minute"===e)s.minute(+t);else if("ampm"===e){var l=t.toUpperCase();a&&("PM"===l&&s.hour()<12&&s.hour(s.hour()%12+12),"AM"===l&&s.hour()>=12&&s.hour(s.hour()-12))}else s.second(+t);o(s)},r.onEnterSelectPanel=function(e){r.props.onCurrentSelectPanelChange(e)},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"getHourSelect",value:function(e){var t=this.props,n=t.prefixCls,r=t.hourOptions,o=t.disabledHours,i=t.showHour,a=t.use12Hours;if(!i)return null;var s=o(),l=void 0,u=void 0;return a?(l=[12].concat(r.filter(function(e){return e<12&&e>0})),u=e%12||12):(l=r,u=e),Zo.a.createElement(Ql,{prefixCls:n,options:l.map(function(e){return eu(e,s)}),selectedIndex:l.indexOf(u),type:"hour",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"hour")})}},{key:"getMinuteSelect",value:function(e){var t=this.props,n=t.prefixCls,r=t.minuteOptions,o=t.disabledMinutes,i=t.defaultOpenValue;if(!t.showMinute)return null;var a=this.props.value||i,s=o(a.hour());return Zo.a.createElement(Ql,{prefixCls:n,options:r.map(function(e){return eu(e,s)}),selectedIndex:r.indexOf(e),type:"minute",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"minute")})}},{key:"getSecondSelect",value:function(e){var t=this.props,n=t.prefixCls,r=t.secondOptions,o=t.disabledSeconds,i=t.showSecond,a=t.defaultOpenValue;if(!i)return null;var s=this.props.value||a,l=o(s.hour(),s.minute());return Zo.a.createElement(Ql,{prefixCls:n,options:r.map(function(e){return eu(e,l)}),selectedIndex:r.indexOf(e),type:"second",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"second")})}},{key:"getAMPMSelect",value:function(){var e=this.props,t=e.prefixCls,n=e.use12Hours,r=e.format;if(!n)return null;var o=["am","pm"].map(function(e){return r.match(/\sA/)?e.toUpperCase():e}).map(function(e){return{value:e}}),i=this.props.isAM?0:1;return Zo.a.createElement(Ql,{prefixCls:t,options:o,selectedIndex:i,type:"ampm",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"ampm")})}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.defaultOpenValue,r=this.props.value||n;return Zo.a.createElement("div",{className:t+"-combobox"},this.getHourSelect(r.hour()),this.getMinuteSelect(r.minute()),this.getSecondSelect(r.second()),this.getAMPMSelect(r.hour()))}}]),t}(Jo.Component);tu.propTypes={format:ni.a.string,defaultOpenValue:ni.a.object,prefixCls:ni.a.string,value:ni.a.object,onChange:ni.a.func,showHour:ni.a.bool,showMinute:ni.a.bool,showSecond:ni.a.bool,hourOptions:ni.a.array,minuteOptions:ni.a.array,secondOptions:ni.a.array,disabledHours:ni.a.func,disabledMinutes:ni.a.func,disabledSeconds:ni.a.func,onCurrentSelectPanelChange:ni.a.func,use12Hours:ni.a.bool,isAM:ni.a.bool};var nu=tu,ru=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onChange=function(e){n.setState({value:e}),n.props.onChange(e)},n.onCurrentSelectPanelChange=function(e){n.setState({currentSelectPanel:e})},n.disabledHours=function(){var e=n.props,t=e.use12Hours,r=e.disabledHours,o=r();return t&&Array.isArray(o)&&(o=n.isAM()?o.filter(function(e){return e<12}).map(function(e){return 0===e?12:e}):o.map(function(e){return 12===e?12:e-12})),o},n.state={value:e.value,selectionRange:[]},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){var t=e.value;t&&this.setState({value:t})}},{key:"close",value:function(){this.props.onEsc()}},{key:"isAM",value:function(){var e=this.state.value||this.props.defaultOpenValue;return e.hour()>=0&&e.hour()<12}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.placeholder,i=t.disabledMinutes,a=t.disabledSeconds,s=t.hideDisabledOptions,l=t.allowEmpty,u=t.showHour,c=t.showMinute,p=t.showSecond,f=t.format,d=t.defaultOpenValue,h=t.clearText,v=t.onEsc,m=t.addon,y=t.use12Hours,g=t.onClear,b=t.focusOnOpen,C=t.onKeyDown,w=t.hourStep,S=t.minuteStep,x=t.secondStep,_=t.inputReadOnly,k=this.state,E=k.value,O=k.currentSelectPanel,T=this.disabledHours(),N=i(E?E.hour():null),P=a(E?E.hour():null,E?E.minute():null),M=ct(24,T,s,w),D=ct(60,N,s,S),I=ct(60,P,s,x);return Zo.a.createElement("div",{className:ii()((e={},Ko()(e,n+"-inner",!0),Ko()(e,r,!!r),e))},Zo.a.createElement($l,{clearText:h,prefixCls:n,defaultOpenValue:d,value:E,currentSelectPanel:O,onEsc:v,format:f,placeholder:o,hourOptions:M,minuteOptions:D,secondOptions:I,disabledHours:this.disabledHours,disabledMinutes:i,disabledSeconds:a,onChange:this.onChange,onClear:g,allowEmpty:l,focusOnOpen:b,onKeyDown:C,inputReadOnly:_}),Zo.a.createElement(nu,{prefixCls:n,value:E,defaultOpenValue:d,format:f,onChange:this.onChange,showHour:u,showMinute:c,showSecond:p,hourOptions:M,minuteOptions:D,secondOptions:I,disabledHours:this.disabledHours,disabledMinutes:i,disabledSeconds:a,onCurrentSelectPanelChange:this.onCurrentSelectPanelChange,use12Hours:y,isAM:this.isAM()}),m(this))}}]),t}(Jo.Component);ru.propTypes={clearText:ni.a.string,prefixCls:ni.a.string,className:ni.a.string,defaultOpenValue:ni.a.object,value:ni.a.object,placeholder:ni.a.string,format:ni.a.string,inputReadOnly:ni.a.bool,disabledHours:ni.a.func,disabledMinutes:ni.a.func,disabledSeconds:ni.a.func,hideDisabledOptions:ni.a.bool,onChange:ni.a.func,onEsc:ni.a.func,allowEmpty:ni.a.bool,showHour:ni.a.bool,showMinute:ni.a.bool,showSecond:ni.a.bool,onClear:ni.a.func,use12Hours:ni.a.bool,hourStep:ni.a.number,minuteStep:ni.a.number,secondStep:ni.a.number,addon:ni.a.func,focusOnOpen:ni.a.bool,onKeyDown:ni.a.func},ru.defaultProps={prefixCls:"rc-time-picker-panel",onChange:ut,onClear:ut,disabledHours:ut,disabledMinutes:ut,disabledSeconds:ut,defaultOpenValue:ma()(),use12Hours:!1,addon:ut,onKeyDown:ut,inputReadOnly:!1};var ou=ru,iu={adjustX:1,adjustY:1},au=[0,0],su={bottomLeft:{points:["tl","tl"],overflow:iu,offset:[0,-3],targetOffset:au},bottomRight:{points:["tr","tr"],overflow:iu,offset:[0,-3],targetOffset:au},topRight:{points:["br","br"],overflow:iu,offset:[0,3],targetOffset:au},topLeft:{points:["bl","bl"],overflow:iu,offset:[0,3],targetOffset:au}},lu=su,uu=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));cu.call(n),n.saveInputRef=ft.bind(n,"picker"),n.savePanelRef=ft.bind(n,"panelInstance");var r=e.defaultOpen,o=e.defaultValue,i=e.open,a=void 0===i?r:i,s=e.value,l=void 0===s?o:s;return n.state={open:a,value:l},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})}},{key:"setValue",value:function(e){"value"in this.props||this.setState({value:e}),this.props.onChange(e)}},{key:"getFormat",value:function(){var e=this.props,t=e.format,n=e.showHour,r=e.showMinute,o=e.showSecond,i=e.use12Hours;if(t)return t;if(i){return[n?"h":"",r?"mm":"",o?"ss":""].filter(function(e){return!!e}).join(":").concat(" a")}return[n?"HH":"",r?"mm":"",o?"ss":""].filter(function(e){return!!e}).join(":")}},{key:"getPanelElement",value:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=e.disabledHours,o=e.disabledMinutes,i=e.disabledSeconds,a=e.hideDisabledOptions,s=e.inputReadOnly,l=e.allowEmpty,u=e.showHour,c=e.showMinute,p=e.showSecond,f=e.defaultOpenValue,d=e.clearText,h=e.addon,v=e.use12Hours,m=e.focusOnOpen,y=e.onKeyDown,g=e.hourStep,b=e.minuteStep,C=e.secondStep;return Zo.a.createElement(ou,{clearText:d,prefixCls:t+"-panel",ref:this.savePanelRef,value:this.state.value,inputReadOnly:s,onChange:this.onPanelChange,onClear:this.onPanelClear,defaultOpenValue:f,showHour:u,showMinute:c,showSecond:p,onEsc:this.onEsc,allowEmpty:l,format:this.getFormat(),placeholder:n,disabledHours:r,disabledMinutes:o,disabledSeconds:i,hideDisabledOptions:a,use12Hours:v,hourStep:g,minuteStep:b,secondStep:C,addon:h,focusOnOpen:m,onKeyDown:y})}},{key:"getPopupClassName",value:function(){var e=this.props,t=e.showHour,n=e.showMinute,r=e.showSecond,o=e.use12Hours,i=e.prefixCls,a=this.props.popupClassName;t&&n&&r||o||(a+=" "+i+"-panel-narrow");var s=0;return t&&(s+=1),n&&(s+=1),r&&(s+=1),o&&(s+=1),a+=" "+i+"-panel-column-"+s}},{key:"setOpen",value:function(e){var t=this.props,n=t.onOpen,r=t.onClose;this.state.open!==e&&("open"in this.props||this.setState({open:e}),e?n({open:e}):r({open:e}))}},{key:"focus",value:function(){this.picker.focus()}},{key:"blur",value:function(){this.picker.blur()}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=e.placement,o=e.align,i=e.disabled,a=e.transitionName,s=e.style,l=e.className,u=e.getPopupContainer,c=e.name,p=e.autoComplete,f=e.onFocus,d=e.onBlur,h=e.autoFocus,v=e.inputReadOnly,m=this.state,y=m.open,g=m.value,b=this.getPopupClassName();return Zo.a.createElement(Hs.a,{prefixCls:t+"-panel",popupClassName:b,popup:this.getPanelElement(),popupAlign:o,builtinPlacements:lu,popupPlacement:r,action:i?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:u,popupTransitionName:a,popupVisible:y,onPopupVisibleChange:this.onVisibleChange},Zo.a.createElement("span",{className:t+" "+l,style:s},Zo.a.createElement("input",{className:t+"-input",ref:this.saveInputRef,type:"text",placeholder:n,name:c,onKeyDown:this.onKeyDown,disabled:i,value:g&&g.format(this.getFormat())||"",autoComplete:p,onFocus:f,onBlur:d,autoFocus:h,onChange:pt,readOnly:!!v}),Zo.a.createElement("span",{className:t+"-icon"})))}}]),t}(Jo.Component);uu.propTypes={prefixCls:ni.a.string,clearText:ni.a.string,value:ni.a.object,defaultOpenValue:ni.a.object,inputReadOnly:ni.a.bool,disabled:ni.a.bool,allowEmpty:ni.a.bool,defaultValue:ni.a.object,open:ni.a.bool,defaultOpen:ni.a.bool,align:ni.a.object,placement:ni.a.any,transitionName:ni.a.string,getPopupContainer:ni.a.func,placeholder:ni.a.string,format:ni.a.string,showHour:ni.a.bool,showMinute:ni.a.bool,showSecond:ni.a.bool,style:ni.a.object,className:ni.a.string,popupClassName:ni.a.string,disabledHours:ni.a.func,disabledMinutes:ni.a.func,disabledSeconds:ni.a.func,hideDisabledOptions:ni.a.bool,onChange:ni.a.func,onOpen:ni.a.func,onClose:ni.a.func,onFocus:ni.a.func,onBlur:ni.a.func,addon:ni.a.func,name:ni.a.string,autoComplete:ni.a.string,use12Hours:ni.a.bool,hourStep:ni.a.number,minuteStep:ni.a.number,secondStep:ni.a.number,focusOnOpen:ni.a.bool,onKeyDown:ni.a.func,autoFocus:ni.a.bool},uu.defaultProps={clearText:"clear",prefixCls:"rc-time-picker",defaultOpen:!1,inputReadOnly:!1,style:{},className:"",popupClassName:"",align:{},defaultOpenValue:ma()(),allowEmpty:!0,showHour:!0,showMinute:!0,showSecond:!0,disabledHours:pt,disabledMinutes:pt,disabledSeconds:pt,hideDisabledOptions:!1,placement:"bottomLeft",onChange:pt,onOpen:pt,onClose:pt,onFocus:pt,onBlur:pt,addon:pt,use12Hours:!1,focusOnOpen:!1,onKeyDown:pt};var cu=function(){var e=this;this.onPanelChange=function(t){e.setValue(t)},this.onPanelClear=function(){e.setValue(null),e.setOpen(!1)},this.onVisibleChange=function(t){e.setOpen(t)},this.onEsc=function(){e.setOpen(!1),e.focus()},this.onKeyDown=function(t){40===t.keyCode&&e.setOpen(!0)}},pu=uu,fu=n(100),du=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.handleChange=function(e){"value"in n.props||n.setState({value:e});var t=n.props,r=t.onChange,o=t.format,i=void 0===o?"HH:mm:ss":o;r&&r(e,e&&e.format(i)||"")},n.handleOpenClose=function(e){var t=e.open,r=n.props.onOpenChange;r&&r(t)},n.saveTimePicker=function(e){n.timePickerRef=e},n.renderTimePicker=function(e){var t=Vo()({},n.props);delete t.defaultValue;var r=n.getDefaultFormat(),o=ii()(t.className,Ko()({},t.prefixCls+"-"+t.size,!!t.size)),i=function(e){return t.addon?Jo.createElement("div",{className:t.prefixCls+"-panel-addon"},t.addon(e)):null};return Jo.createElement(pu,Vo()({},dt(r),t,{ref:n.saveTimePicker,format:r,className:o,value:n.state.value,placeholder:void 0===t.placeholder?e.placeholder:t.placeholder,onChange:n.handleChange,onOpen:n.handleOpenClose,onClose:n.handleOpenClose,addon:i}))};var r=e.value||e.defaultValue;if(r&&!q(va).isMoment(r))throw new Error("The value/defaultValue of TimePicker must be a moment object after `[email protected]`, see: https://u.ant.design/time-picker-value");return n.state={value:r},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value})}},{key:"focus",value:function(){this.timePickerRef.focus()}},{key:"blur",value:function(){this.timePickerRef.blur()}},{key:"getDefaultFormat",value:function(){var e=this.props,t=e.format,n=e.use12Hours;return t||(n?"h:mm:ss a":"HH:mm:ss")}},{key:"render",value:function(){return Jo.createElement(La.a,{componentName:"TimePicker",defaultLocale:fu.a},this.renderTimePicker)}}]),t}(Jo.Component),hu=du;du.defaultProps={prefixCls:"ant-time-picker",align:{offset:[0,-2]},disabled:!1,disabledHours:void 0,disabledMinutes:void 0,disabledSeconds:void 0,hideDisabledOptions:!1,placement:"bottomLeft",transitionName:"slide-up",focusOnOpen:!0};var vu=n(121),mu=ga()({displayName:"CalendarPart",propTypes:{prefixCls:ni.a.string,value:ni.a.any,hoverValue:ni.a.any,selectedValue:ni.a.any,direction:ni.a.any,locale:ni.a.any,showDateInput:ni.a.bool,showTimePicker:ni.a.bool,format:ni.a.any,placeholder:ni.a.any,disabledDate:ni.a.any,timePicker:ni.a.any,disabledTime:ni.a.any,onInputSelect:ni.a.func,timePickerDisabledTime:ni.a.object,enableNext:ni.a.any,enablePrev:ni.a.any},render:function(){var e=this.props,t=e.prefixCls,n=e.value,r=e.hoverValue,o=e.selectedValue,i=e.mode,a=e.direction,s=e.locale,l=e.format,u=e.placeholder,c=e.disabledDate,p=e.timePicker,f=e.disabledTime,d=e.timePickerDisabledTime,h=e.showTimePicker,v=e.onInputSelect,m=e.enablePrev,y=e.enableNext,g=h&&p,b=g&&f?M(o,f):null,C=t+"-range",w={locale:s,value:n,prefixCls:t,showTimePicker:h},S="left"===a?0:1,x=g&&Zo.a.cloneElement(p,Vo()({showHour:!0,showMinute:!0,showSecond:!0},p.props,b,d,{onChange:v,defaultOpenValue:n,value:o[S]})),_=e.showDateInput&&Zo.a.createElement(jl,{format:l,locale:s,prefixCls:t,timePicker:p,disabledDate:c,placeholder:u,disabledTime:f,value:n,showClear:!1,selectedValue:o[S],onChange:v});return Zo.a.createElement("div",{className:C+"-part "+C+"-"+a},_,Zo.a.createElement("div",{style:{outline:"none"}},Zo.a.createElement(Ml,Vo()({},w,{mode:i,enableNext:y,enablePrev:m,onValueChange:e.onValueChange,onPanelChange:e.onPanelChange,disabledMonth:e.disabledMonth})),h?Zo.a.createElement("div",{className:t+"-time-picker"},Zo.a.createElement("div",{className:t+"-time-picker-panel"},x)):null,Zo.a.createElement("div",{className:t+"-body"},Zo.a.createElement(Ea,Vo()({},w,{hoverValue:r,selectedValue:o,dateRender:e.dateRender,onSelect:e.onSelect,onDayHover:e.onDayHover,disabledDate:c,showWeekNumber:e.showWeekNumber})))))}}),yu=mu,gu=ga()({displayName:"RangeCalendar",propTypes:{prefixCls:ni.a.string,dateInputPlaceholder:ni.a.any,defaultValue:ni.a.any,value:ni.a.any,hoverValue:ni.a.any,mode:ni.a.arrayOf(ni.a.oneOf(["date","month","year","decade"])),showDateInput:ni.a.bool,timePicker:ni.a.any,showOk:ni.a.bool,showToday:ni.a.bool,defaultSelectedValue:ni.a.array,selectedValue:ni.a.array,onOk:ni.a.func,showClear:ni.a.bool,locale:ni.a.object,onChange:ni.a.func,onSelect:ni.a.func,onValueChange:ni.a.func,onHoverChange:ni.a.func,onPanelChange:ni.a.func,format:ni.a.oneOfType([ni.a.object,ni.a.string]),onClear:ni.a.func,type:ni.a.any,disabledDate:ni.a.func,disabledTime:ni.a.func},mixins:[Da],getDefaultProps:function(){return{type:"both",defaultSelectedValue:[],onValueChange:mt,onHoverChange:mt,onPanelChange:mt,disabledTime:mt,onInputSelect:mt,showToday:!0,showDateInput:!0}},getInitialState:function(){var e=this.props,t=e.selectedValue||e.defaultSelectedValue,n=Ct(e,1);return{selectedValue:t,prevSelectedValue:t,firstSelectedValue:null,hoverValue:e.hoverValue||[],value:n,showTimePicker:!1,mode:e.mode||["date","date"]}},componentWillReceiveProps:function(e){var t=this.state,n={};"value"in e&&(n.value=Ct(e,0),this.setState(n)),"hoverValue"in e&&!gt(t.hoverValue,e.hoverValue)&&this.setState({hoverValue:e.hoverValue}),"selectedValue"in e&&(n.selectedValue=e.selectedValue,n.prevSelectedValue=e.selectedValue,this.setState(n)),"mode"in e&&!gt(t.mode,e.mode)&&this.setState({mode:e.mode})},onDatePanelEnter:function(){this.hasSelectedValue()&&this.fireHoverValueChange(this.state.selectedValue.concat())},onDatePanelLeave:function(){this.hasSelectedValue()&&this.fireHoverValueChange([])},onSelect:function(e){var t=this.props.type,n=this.state,r=n.selectedValue,o=n.prevSelectedValue,i=n.firstSelectedValue,a=void 0;if("both"===t)i?this.compare(i,e)<0?(P(o[1],e),a=[i,e]):(P(o[0],e),P(o[1],i),a=[e,i]):(P(o[0],e),a=[e]);else if("start"===t){P(o[0],e);var s=r[1];a=s&&this.compare(s,e)>0?[e,s]:[e]}else{var l=r[0];l&&this.compare(l,e)<=0?(P(o[1],e),a=[l,e]):(P(o[0],e),a=[e])}this.fireSelectValueChange(a)},onDayHover:function(e){var t=[],n=this.state,r=n.selectedValue,o=n.firstSelectedValue,i=this.props.type;if("start"===i&&r[1])t=this.compare(e,r[1])<0?[e,r[1]]:[e];else if("end"===i&&r[0])t=this.compare(e,r[0])>0?[r[0],e]:[];else{if(!o)return;t=this.compare(e,o)<0?[e,o]:[o,e]}this.fireHoverValueChange(t)},onToday:function(){var e=E(this.state.value[0]),t=e.clone().add(1,"months");this.setState({value:[e,t]})},onOpenTimePicker:function(){this.setState({showTimePicker:!0})},onCloseTimePicker:function(){this.setState({showTimePicker:!1})},onOk:function(){var e=this.state.selectedValue;this.isAllowedDateAndTime(e)&&this.props.onOk(this.state.selectedValue)},onStartInputSelect:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=["left"].concat(t);return St.apply(this,r)},onEndInputSelect:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=["right"].concat(t);return St.apply(this,r)},onStartValueChange:function(e){var t=[].concat(this.state.value);return t[0]=e,this.fireValueChange(t)},onEndValueChange:function(e){var t=[].concat(this.state.value);return t[1]=e,this.fireValueChange(t)},onStartPanelChange:function(e,t){var n=this.props,r=this.state,o=[t,r.mode[1]];"mode"in n||this.setState({mode:o});var i=[e||r.value[0],r.value[1]];n.onPanelChange(i,o)},onEndPanelChange:function(e,t){var n=this.props,r=this.state,o=[r.mode[0],t];"mode"in n||this.setState({mode:o});var i=[r.value[0],e||r.value[1]];n.onPanelChange(i,o)},getStartValue:function(){var e=this.state.value[0],t=this.state.selectedValue;return t[0]&&this.props.timePicker&&(e=e.clone(),P(t[0],e)),this.state.showTimePicker&&t[0]?t[0]:e},getEndValue:function(){var e=this.state,t=e.value,n=e.selectedValue,r=e.showTimePicker,o=t[1]?t[1].clone():t[0].clone().add(1,"month");return n[1]&&this.props.timePicker&&P(n[1],o),r?n[1]?n[1]:this.getStartValue():o},getEndDisableTime:function(){var e=this.state,t=e.selectedValue,n=e.value,r=this.props.disabledTime,o=r(t,"end")||{},i=t&&t[0]||n[0].clone();if(!t[1]||i.isSame(t[1],"day")){var a=i.hour(),s=i.minute(),l=i.second(),u=o.disabledHours,c=o.disabledMinutes,p=o.disabledSeconds,f=c?c():[],d=p?p():[];return u=wt(a,u),c=wt(s,c),p=wt(l,p),{disabledHours:function(){return u},disabledMinutes:function(e){return e===a?c:f},disabledSeconds:function(e,t){return e===a&&t===s?p:d}}}return o},isAllowedDateAndTime:function(e){return A(e[0],this.props.disabledDate,this.disabledStartTime)&&A(e[1],this.props.disabledDate,this.disabledEndTime)},isMonthYearPanelShow:function(e){return["month","year","decade"].indexOf(e)>-1},hasSelectedValue:function(){var e=this.state.selectedValue;return!!e[1]&&!!e[0]},compare:function(e,t){return this.props.timePicker?e.diff(t):e.diff(t,"days")},fireSelectValueChange:function(e,t){var n=this.props.timePicker,r=this.state.prevSelectedValue;if(n&&n.props.defaultValue){var o=n.props.defaultValue;!r[0]&&e[0]&&P(o[0],e[0]),!r[1]&&e[1]&&P(o[1],e[1])}if("selectedValue"in this.props||this.setState({selectedValue:e}),!this.state.selectedValue[0]||!this.state.selectedValue[1]){var i=e[0]||ma()(),a=e[1]||i.clone().add(1,"months");this.setState({selectedValue:e,value:bt([i,a])})}e[0]&&!e[1]&&(this.setState({firstSelectedValue:e[0]}),this.fireHoverValueChange(e.concat())),this.props.onChange(e),(t||e[0]&&e[1])&&(this.setState({prevSelectedValue:e,firstSelectedValue:null}),this.fireHoverValueChange([]),this.props.onSelect(e))},fireValueChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onValueChange(e)},fireHoverValueChange:function(e){var t=this.props;"hoverValue"in t||this.setState({hoverValue:e}),t.onHoverChange(e)},clear:function(){this.fireSelectValueChange([],!0),this.props.onClear()},disabledStartTime:function(e){return this.props.disabledTime(e,"start")},disabledEndTime:function(e){return this.props.disabledTime(e,"end")},disabledStartMonth:function(e){var t=this.state.value;return e.isSameOrAfter(t[1],"month")},disabledEndMonth:function(e){var t=this.state.value;return e.isSameOrBefore(t[0],"month")},render:function(){var e,t,n=this.props,r=this.state,o=n.prefixCls,i=n.dateInputPlaceholder,a=n.timePicker,s=n.showOk,l=n.locale,u=n.showClear,c=n.showToday,p=n.type,f=r.hoverValue,d=r.selectedValue,h=r.mode,v=r.showTimePicker,m=(e={},e[n.className]=!!n.className,e[o]=1,e[o+"-hidden"]=!n.visible,e[o+"-range"]=1,e[o+"-show-time-picker"]=v,e[o+"-week-number"]=n.showWeekNumber,e),y=ii()(m),g={selectedValue:r.selectedValue,onSelect:this.onSelect,onDayHover:"start"===p&&d[1]||"end"===p&&d[0]||f.length?this.onDayHover:void 0},b=void 0,C=void 0;i&&(Array.isArray(i)?(b=i[0],C=i[1]):b=C=i);var w=!0===s||!1!==s&&!!a,S=ii()((t={},t[o+"-footer"]=!0,t[o+"-range-bottom"]=!0,t[o+"-footer-show-ok"]=w,t)),x=this.getStartValue(),_=this.getEndValue(),k=E(x),O=k.month(),T=k.year(),N=x.year()===T&&x.month()===O||_.year()===T&&_.month()===O,P=x.clone().add(1,"months"),M=P.year()===_.year()&&P.month()===_.month();return Zo.a.createElement("div",{ref:this.saveRoot,className:y,style:n.style,tabIndex:"0"},n.renderSidebar(),Zo.a.createElement("div",{className:o+"-panel"},u&&d[0]&&d[1]?Zo.a.createElement("a",{className:o+"-clear-btn",role:"button",title:l.clear,onClick:this.clear}):null,Zo.a.createElement("div",{className:o+"-date-panel",onMouseLeave:"both"!==p?this.onDatePanelLeave:void 0,onMouseEnter:"both"!==p?this.onDatePanelEnter:void 0},Zo.a.createElement(yu,Vo()({},n,g,{hoverValue:f,direction:"left",disabledTime:this.disabledStartTime,disabledMonth:this.disabledStartMonth,format:this.getFormat(),value:x,mode:h[0],placeholder:b,onInputSelect:this.onStartInputSelect,onValueChange:this.onStartValueChange,onPanelChange:this.onStartPanelChange,showDateInput:this.props.showDateInput,timePicker:a,showTimePicker:v,enablePrev:!0,enableNext:!M||this.isMonthYearPanelShow(h[1])})),Zo.a.createElement("span",{className:o+"-range-middle"},"~"),Zo.a.createElement(yu,Vo()({},n,g,{hoverValue:f,direction:"right",format:this.getFormat(),timePickerDisabledTime:this.getEndDisableTime(),placeholder:C,value:_,mode:h[1],onInputSelect:this.onEndInputSelect,onValueChange:this.onEndValueChange,onPanelChange:this.onEndPanelChange,showDateInput:this.props.showDateInput,timePicker:a,showTimePicker:v,disabledTime:this.disabledEndTime,disabledMonth:this.disabledEndMonth,enablePrev:!M||this.isMonthYearPanelShow(h[0]),enableNext:!0}))),Zo.a.createElement("div",{className:S},n.renderFooter(),c||n.timePicker||w?Zo.a.createElement("div",{className:o+"-footer-btn"},c?Zo.a.createElement(Xe,Vo()({},n,{disabled:N,value:r.value[0],onToday:this.onToday,text:l.backToToday})):null,n.timePicker?Zo.a.createElement(Je,Vo()({},n,{showTimePicker:v,onOpenTimePicker:this.onOpenTimePicker,onCloseTimePicker:this.onCloseTimePicker,timePickerDisabled:!this.hasSelectedValue()||f.length})):null,w?Zo.a.createElement($e,Vo()({},n,{onOk:this.onOk,okDisabled:!this.isAllowedDateAndTime(d)||!this.hasSelectedValue()||f.length})):null):null)))}}),bu=gu,Cu=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.clearSelection=function(e){e.preventDefault(),e.stopPropagation(),n.setState({value:[]}),n.handleChange([])},n.clearHoverValue=function(){return n.setState({hoverValue:[]})},n.handleChange=function(e){var t=n.props;"value"in t||n.setState(function(t){var n=t.showDate;return{value:e,showDate:xt(e)||n}}),t.onChange(e,[_t(e[0],t.format),_t(e[1],t.format)])},n.handleOpenChange=function(e){"open"in n.props||n.setState({open:e}),!1===e&&n.clearHoverValue();var t=n.props.onOpenChange;t&&t(e)},n.handleShowDateChange=function(e){return n.setState({showDate:e})},n.handleHoverChange=function(e){return n.setState({hoverValue:e})},n.handleRangeMouseLeave=function(){n.state.open&&n.clearHoverValue()},n.handleCalendarInputSelect=function(e){e[0]&&n.setState(function(t){var n=t.showDate;return{value:e,showDate:xt(e)||n}})},n.handleRangeClick=function(e){"function"==typeof e&&(e=e()),n.setValue(e,!0);var t=n.props.onOk;t&&t(e)},n.savePicker=function(e){n.picker=e},n.renderFooter=function(){var e=n.props,t=e.prefixCls,r=e.ranges,o=e.renderExtraFooter;if(!r&&!o)return null;var i=o?Jo.createElement("div",{className:t+"-footer-extra",key:"extra"},o.apply(void 0,arguments)):null,a=Object.keys(r||{}).map(function(e){var t=r[e];return Jo.createElement("a",{key:e,onClick:function(){return n.handleRangeClick(t)},onMouseEnter:function(){return n.setState({hoverValue:t})},onMouseLeave:n.handleRangeMouseLeave},e)});return[Jo.createElement("div",{className:t+"-footer-extra "+t+"-range-quick-selector",key:"range"},a),i]};var r=e.value||e.defaultValue||[];if(r[0]&&!q(va).isMoment(r[0])||r[1]&&!q(va).isMoment(r[1]))throw new Error("The value/defaultValue of RangePicker must be a moment object array after `[email protected]`, see: https://u.ant.design/date-picker-value");var o=!r||Et(r)?e.defaultPickerValue:r;return n.state={value:r,showDate:kt(o||q(va)()),open:e.open,hoverValue:[]},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){if("value"in e){var t=this.state,n=e.value||[];this.setState({value:n,showDate:xt(n)||t.showDate})}"open"in e&&this.setState({open:e.open})}},{key:"setValue",value:function(e,t){this.handleChange(e),!t&&this.props.showTime||"open"in this.props||this.setState({open:!1})}},{key:"focus",value:function(){this.picker.focus()}},{key:"blur",value:function(){this.picker.blur()}},{key:"render",value:function(){var e,t=this,n=this.state,r=this.props,o=n.value,i=n.showDate,a=n.hoverValue,s=n.open,l=r.prefixCls,u=r.popupStyle,c=r.style,p=r.disabledDate,f=r.disabledTime,d=r.showTime,h=r.showToday,v=r.ranges,m=r.onOk,y=r.locale,g=r.localeCode,b=r.format,C=r.dateRender,w=r.onCalendarChange;Ot(o,g),Ot(i,g),Object(aa.a)(!("onOK"in r),"It should be `RangePicker[onOk]`, instead of `onOK`!");var S=ii()((e={},Ko()(e,l+"-time",d),Ko()(e,l+"-range-with-ranges",v),e)),x={onChange:this.handleChange},_={onOk:this.handleChange};r.timePicker?x.onChange=function(e){return t.handleChange(e)}:_={},"mode"in r&&(_.mode=r.mode);var k="placeholder"in r?r.placeholder[0]:y.lang.rangePlaceholder[0],E="placeholder"in r?r.placeholder[1]:y.lang.rangePlaceholder[1],O=Jo.createElement(bu,Vo()({},_,{onChange:w,format:b,prefixCls:l,className:S,renderFooter:this.renderFooter,timePicker:r.timePicker,disabledDate:p,disabledTime:f,dateInputPlaceholder:[k,E],locale:y.lang,onOk:m,dateRender:C,value:i,onValueChange:this.handleShowDateChange,hoverValue:a,onHoverChange:this.handleHoverChange,onPanelChange:r.onPanelChange,showToday:h,onInputSelect:this.handleCalendarInputSelect})),T={};r.showTime&&(T.width=c&&c.width||350);var N=!r.disabled&&r.allowClear&&o&&(o[0]||o[1])?Jo.createElement(Ni.a,{type:"cross-circle",className:l+"-picker-clear",onClick:this.clearSelection}):null,P=function(e){var t=e.value,n=t[0],o=t[1];return Jo.createElement("span",{className:r.pickerInputClass},Jo.createElement("input",{disabled:r.disabled,readOnly:!0,value:n&&n.format(r.format)||"",placeholder:k,className:l+"-range-picker-input",tabIndex:-1}),Jo.createElement("span",{className:l+"-range-picker-separator"}," ~ "),Jo.createElement("input",{disabled:r.disabled,readOnly:!0,value:o&&o.format(r.format)||"",placeholder:E,className:l+"-range-picker-input",tabIndex:-1}),N,Jo.createElement("span",{className:l+"-picker-icon"}))};return Jo.createElement("span",{ref:this.savePicker,id:r.id,className:ii()(r.className,r.pickerClass),style:Vo()({},c,T),tabIndex:r.disabled?-1:0,onFocus:r.onFocus,onBlur:r.onBlur},Jo.createElement(Yl,Vo()({},r,x,{calendar:O,value:o,open:s,onOpenChange:this.handleOpenChange,prefixCls:l+"-picker-container",style:u}),P))}}]),t}(Jo.Component),wu=Cu;Cu.defaultProps={prefixCls:"ant-calendar",allowClear:!0,showToday:!1};var Su=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.weekDateRender=function(e){var t=n.state.value,r=n.props.prefixCls;return t&&e.year()===t.year()&&e.week()===t.week()?Jo.createElement("div",{className:r+"-selected-day"},Jo.createElement("div",{className:r+"-date"},e.date())):Jo.createElement("div",{className:r+"-calendar-date"},e.date())},n.handleChange=function(e){"value"in n.props||n.setState({value:e}),n.props.onChange(e,Tt(e,n.props.format))},n.clearSelection=function(e){e.preventDefault(),e.stopPropagation(),n.handleChange(null)},n.saveInput=function(e){n.input=e};var r=e.value||e.defaultValue;if(r&&!q(va).isMoment(r))throw new Error("The value/defaultValue of DatePicker or MonthPicker must be a moment object after `[email protected]`, see: https://u.ant.design/date-picker-value");return n.state={value:r},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value})}},{key:"focus",value:function(){this.input.focus()}},{key:"blur",value:function(){this.input.blur()}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.className,o=t.disabled,i=t.pickerClass,a=t.popupStyle,s=t.pickerInputClass,l=t.format,u=t.allowClear,c=t.locale,p=t.localeCode,f=t.disabledDate,d=this.state.value;d&&p&&d.locale(p);var h="placeholder"in this.props?this.props.placeholder:c.lang.placeholder,v=Jo.createElement(Kl,{showWeekNumber:!0,dateRender:this.weekDateRender,prefixCls:n,format:l,locale:c.lang,showDateInput:!1,showToday:!1,disabledDate:f}),m=!o&&u&&this.state.value?Jo.createElement(Ni.a,{type:"cross-circle",className:n+"-picker-clear",onClick:this.clearSelection}):null,y=function(t){var r=t.value;return Jo.createElement("span",null,Jo.createElement("input",{ref:e.saveInput,disabled:o,readOnly:!0,value:r&&r.format(l)||"",placeholder:h,className:s,onFocus:e.props.onFocus,onBlur:e.props.onBlur}),m,Jo.createElement("span",{className:n+"-picker-icon"}))};return Jo.createElement("span",{className:ii()(r,i),id:this.props.id},Jo.createElement(Yl,Vo()({},this.props,{calendar:v,prefixCls:n+"-picker-container",value:d,onChange:this.handleChange,style:a}),y))}}]),t}(Jo.Component),xu=Su;Su.defaultProps={format:"gggg-wo",allowClear:!0};var _u=vt(lt(Kl)),ku=vt(lt(Vl),"YYYY-MM");Vo()(_u,{RangePicker:vt(wu),MonthPicker:ku,WeekPicker:vt(xu,"gggg-wo")});var Eu=_u,Ou=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Tu=n(129),Nu=n(89),Pu=n.n(Nu),Mu=n(189),Du=n.n(Mu),Iu=/%[sdj%]/g,Au=function(){},ju=Ft,Ru=Vt,Lu={email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,url:new RegExp("^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$","i"),hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},Ku={integer:function(e){return Ku.number(e)&&parseInt(e,10)===e},float:function(e){return Ku.number(e)&&!Ku.integer(e)},array:function(e){return Array.isArray(e)},regexp:function(e){if(e instanceof RegExp)return!0;try{return!!new RegExp(e)}catch(e){return!1}},date:function(e){return"function"==typeof e.getTime&&"function"==typeof e.getMonth&&"function"==typeof e.getYear},number:function(e){return!isNaN(e)&&"number"==typeof e},object:function(e){return"object"===(void 0===e?"undefined":$o()(e))&&!Ku.array(e)},method:function(e){return"function"==typeof e},email:function(e){return"string"==typeof e&&!!e.match(Lu.email)&&e.length<255},url:function(e){return"string"==typeof e&&!!e.match(Lu.url)},hex:function(e){return"string"==typeof e&&!!e.match(Lu.hex)}},Fu=zt,Vu=Bt,zu="enum",Bu=Wt,Wu=Ht,Hu={required:ju,whitespace:Ru,type:Fu,range:Vu,enum:Bu,pattern:Wu},Uu=Ut,qu=qt,Yu=Yt,Gu=Gt,Xu=Xt,$u=$t,Ju=Jt,Zu=Zt,Qu=Qt,ec="enum",tc=en,nc=tn,rc=nn,oc=rn,ic=on,ac={string:Uu,method:qu,number:Yu,boolean:Gu,regexp:Xu,integer:$u,float:Ju,array:Zu,object:Qu,enum:tc,pattern:nc,date:rc,url:ic,hex:ic,email:ic,required:oc},sc=an();sn.prototype={messages:function(e){return e&&(this._messages=Kt(an(),e)),this._messages},define:function(e){if(!e)throw new Error("Cannot configure a schema with no rules");if("object"!==(void 0===e?"undefined":$o()(e))||Array.isArray(e))throw new Error("Rules must be an object");this.rules={};var t=void 0,n=void 0;for(t in e)e.hasOwnProperty(t)&&(n=e[t],this.rules[t]=Array.isArray(n)?n:[n])},validate:function(e){function t(e){var t=void 0,n=void 0,r=[],o={};for(t=0;t<e.length;t++)!function(e){Array.isArray(e)?r=r.concat.apply(r,e):r.push(e)}(e[t]);if(r.length)for(t=0;t<r.length;t++)n=r[t].field,o[n]=o[n]||[],o[n].push(r[t]);else r=null,o=null;s(r,o)}var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments[2],i=e,a=r,s=o;if("function"==typeof a&&(s=a,a={}),!this.rules||0===Object.keys(this.rules).length)return void(s&&s());if(a.messages){var l=this.messages();l===sc&&(l=an()),Kt(l,a.messages),a.messages=l}else a.messages=this.messages();var u=void 0,c=void 0,p={};(a.keys||Object.keys(this.rules)).forEach(function(t){u=n.rules[t],c=i[t],u.forEach(function(r){var o=r;"function"==typeof o.transform&&(i===e&&(i=Vo()({},i)),c=i[t]=o.transform(c)),o="function"==typeof o?{validator:o}:Vo()({},o),o.validator=n.getValidationMethod(o),o.field=t,o.fullField=o.fullField||t,o.type=n.getType(o),o.validator&&(p[t]=p[t]||[],p[t].push({rule:o,value:c,source:i,field:t}))})});var f={};Rt(p,a,function(e,t){function n(e,t){return Vo()({},t,{fullField:o.fullField+"."+e})}function r(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],s=r;if(Array.isArray(s)||(s=[s]),s.length&&Au("async-validator:",s),s.length&&o.message&&(s=[].concat(o.message)),s=s.map(Lt(o)),a.first&&s.length)return f[o.field]=1,t(s);if(i){if(o.required&&!e.value)return s=o.message?[].concat(o.message).map(Lt(o)):a.error?[a.error(o,Pt(a.messages.required,o.field))]:[],t(s);var l={};if(o.defaultField)for(var u in e.value)e.value.hasOwnProperty(u)&&(l[u]=o.defaultField);l=Vo()({},l,e.rule.fields);for(var c in l)if(l.hasOwnProperty(c)){var p=Array.isArray(l[c])?l[c]:[l[c]];l[c]=p.map(n.bind(null,c))}var d=new sn(l);d.messages(a.messages),e.rule.options&&(e.rule.options.messages=a.messages,e.rule.options.error=a.error),d.validate(e.value,e.rule.options||a,function(e){t(e&&e.length?s.concat(e):e)})}else t(s)}var o=e.rule,i=!("object"!==o.type&&"array"!==o.type||"object"!==$o()(o.fields)&&"object"!==$o()(o.defaultField));i=i&&(o.required||!o.required&&e.value),o.field=e.field;var s=o.validator(o,e.value,r,e.source,a);s&&s.then&&s.then(function(){return r()},function(e){return r(e)})},function(e){t(e)})},getType:function(e){if(void 0===e.type&&e.pattern instanceof RegExp&&(e.type="pattern"),"function"!=typeof e.validator&&e.type&&!ac.hasOwnProperty(e.type))throw new Error(Pt("Unknown rule type %s",e.type));return e.type||"string"},getValidationMethod:function(e){if("function"==typeof e.validator)return e.validator;var t=Object.keys(e),n=t.indexOf("message");return-1!==n&&t.splice(n,1),1===t.length&&"required"===t[0]?ac.required:ac[this.getType(e)]||!1}},sn.register=function(e,t){if("function"!=typeof t)throw new Error("Cannot register a validator by type, validator is not a function");ac[e]=t},sn.messages=sc;var lc=sn,uc=n(137),cc=n.n(uc),pc=n(194),fc=n.n(pc),dc=function e(t){Bo()(this,e),Vo()(this,t)},hc=n(197),vc=n.n(hc),mc=function(){function e(t){Bo()(this,e),yc.call(this),this.fields=this.flattenFields(t),this.fieldsMeta={}}return Ho()(e,[{key:"updateFields",value:function(e){this.fields=this.flattenFields(e)}},{key:"flattenFields",value:function(e){return vn(e,function(e,t){return ln(t)},"You must wrap field data with `createFormField`.")}},{key:"flattenRegisteredFields",value:function(e){var t=this.getAllFieldsName();return vn(e,function(e){return t.indexOf(e)>=0},"You cannot set field before registering it.")}},{key:"setFields",value:function(e){var t=this,n=this.fieldsMeta,r=Vo()({},this.fields,e),o={};Object.keys(n).forEach(function(e){return o[e]=t.getValueFromFields(e,r)}),Object.keys(o).forEach(function(e){var n=o[e],i=t.getFieldMeta(e);if(i&&i.normalize){var a=i.normalize(n,t.getValueFromFields(e,t.fields),o);a!==n&&(r[e]=Vo()({},r[e],{value:a}))}}),this.fields=r}},{key:"resetFields",value:function(e){var t=this.fields;return(e?this.getValidFieldsFullName(e):this.getAllFieldsName()).reduce(function(e,n){var r=t[n];return r&&"value"in r&&(e[n]={}),e},{})}},{key:"setFieldMeta",value:function(e,t){this.fieldsMeta[e]=t}},{key:"getFieldMeta",value:function(e){return this.fieldsMeta[e]=this.fieldsMeta[e]||{},this.fieldsMeta[e]}},{key:"getValueFromFields",value:function(e,t){var n=t[e];if(n&&"value"in n)return n.value;var r=this.getFieldMeta(e);return r&&r.initialValue}},{key:"getValidFieldsName",value:function(){var e=this,t=this.fieldsMeta;return t?Object.keys(t).filter(function(t){return!e.getFieldMeta(t).hidden}):[]}},{key:"getAllFieldsName",value:function(){var e=this.fieldsMeta;return e?Object.keys(e):[]}},{key:"getValidFieldsFullName",value:function(e){var t=Array.isArray(e)?e:[e];return this.getValidFieldsName().filter(function(e){return t.some(function(t){return e===t||xn(e,t)&&[".","["].indexOf(e[t.length])>=0})})}},{key:"getFieldValuePropValue",value:function(e){var t=e.name,n=e.getValueProps,r=e.valuePropName,o=this.getField(t),i="value"in o?o.value:e.initialValue;return n?n(i):Ko()({},r,i)}},{key:"getField",value:function(e){return Vo()({},this.fields[e],{name:e})}},{key:"getNotCollectedFields",value:function(){var e=this;return this.getValidFieldsName().filter(function(t){return!e.fields[t]}).map(function(t){return{name:t,dirty:!1,value:e.getFieldMeta(t).initialValue}}).reduce(function(e,t){return fc()(e,t.name,un(t))},{})}},{key:"getNestedAllFields",value:function(){var e=this;return Object.keys(this.fields).reduce(function(t,n){return fc()(t,n,un(e.fields[n]))},this.getNotCollectedFields())}},{key:"getFieldMember",value:function(e,t){return this.getField(e)[t]}},{key:"getNestedFields",value:function(e,t){return(e||this.getValidFieldsName()).reduce(function(e,n){return fc()(e,n,t(n))},{})}},{key:"getNestedField",value:function(e,t){var n=this.getValidFieldsFullName(e);if(0===n.length||1===n.length&&n[0]===e)return t(e);var r="["===n[0][e.length],o=r?e.length:e.length+1;return n.reduce(function(e,n){return fc()(e,n.slice(o),t(n))},r?[]:{})}},{key:"isValidNestedFieldName",value:function(e){return this.getAllFieldsName().every(function(t){return!_n(t,e)&&!_n(e,t)})}},{key:"clearField",value:function(e){delete this.fields[e],delete this.fieldsMeta[e]}}]),e}(),yc=function(){var e=this;this.setFieldsInitialValue=function(t){var n=e.flattenRegisteredFields(t),r=e.fieldsMeta;Object.keys(n).forEach(function(t){r[t]&&e.setFieldMeta(t,Vo()({},e.getFieldMeta(t),{initialValue:n[t]}))})},this.getAllValues=function(){var t=e.fieldsMeta,n=e.fields;return Object.keys(t).reduce(function(t,r){return fc()(t,r,e.getValueFromFields(r,n))},{})},this.getFieldsValue=function(t){return e.getNestedFields(t,e.getFieldValue)},this.getFieldValue=function(t){var n=e.fields;return e.getNestedField(t,function(t){return e.getValueFromFields(t,n)})},this.getFieldsError=function(t){return e.getNestedFields(t,e.getFieldError)},this.getFieldError=function(t){return e.getNestedField(t,function(t){return bn(e.getFieldMember(t,"errors"))})},this.isFieldValidating=function(t){return e.getFieldMember(t,"validating")},this.isFieldsValidating=function(t){return(t||e.getValidFieldsName()).some(function(t){return e.isFieldValidating(t)})},this.isFieldTouched=function(t){return e.getFieldMember(t,"touched")},this.isFieldsTouched=function(t){return(t||e.getValidFieldsName()).some(function(t){return e.isFieldTouched(t)})}},gc="onChange",bc=En,Cc={getForm:function(){return{getFieldsValue:this.fieldsStore.getFieldsValue,getFieldValue:this.fieldsStore.getFieldValue,getFieldInstance:this.getFieldInstance,setFieldsValue:this.setFieldsValue,setFields:this.setFields,setFieldsInitialValue:this.fieldsStore.setFieldsInitialValue,getFieldDecorator:this.getFieldDecorator,getFieldProps:this.getFieldProps,getFieldsError:this.fieldsStore.getFieldsError,getFieldError:this.fieldsStore.getFieldError,isFieldValidating:this.fieldsStore.isFieldValidating,isFieldsValidating:this.fieldsStore.isFieldsValidating,isFieldsTouched:this.fieldsStore.isFieldsTouched,isFieldTouched:this.fieldsStore.isFieldTouched,isSubmitting:this.isSubmitting,submit:this.submit,validateFields:this.validateFields,resetFields:this.resetFields}}},wc={getForm:function(){return Vo()({},Cc.getForm.call(this),{validateFieldsAndScroll:this.validateFieldsAndScroll})},validateFieldsAndScroll:function(e,t,n){var r=this,o=Cn(e,t,n),i=o.names,a=o.callback,s=o.options,l=function(e,t){if(e){var n=r.fieldsStore.getValidFieldsName(),o=void 0,i=void 0,l=!0,u=!1,c=void 0;try{for(var p,f=n[Symbol.iterator]();!(l=(p=f.next()).done);l=!0){var d=p.value;if(Du()(e,d)){var h=r.getFieldInstance(d);if(h){var v=ei.a.findDOMNode(h),m=v.getBoundingClientRect().top;(void 0===i||i>m)&&(i=m,o=v)}}}}catch(e){u=!0,c=e}finally{try{!l&&f.return&&f.return()}finally{if(u)throw c}}if(o){var y=s.container||Tn(o);Pu()(o,y,Vo()({onlyScrollIfNeeded:!0},s.scroll))}}"function"==typeof a&&a(e,t)};return this.validateFields(i,s,l)}},Sc=Nn,xc=n(71),_c=n.n(xc),kc=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={helpShow:!1},e.onHelpAnimEnd=function(t,n){e.setState({helpShow:n})},e.onLabelClick=function(t){var n=e.props.label,r=e.props.id||e.getId();if(r){if(1!==document.querySelectorAll('[id="'+r+'"]').length){"string"==typeof n&&t.preventDefault();var o=Qo.findDOMNode(e).querySelector('[id="'+r+'"]');o&&o.focus&&o.focus()}}},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){Object(aa.a)(this.getControls(this.props.children,!0).length<=1,"`Form.Item` cannot generate `validateStatus` and `help` automatically, while there are more than one `getFieldDecorator` in it.")}},{key:"shouldComponentUpdate",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return _c.a.shouldComponentUpdate.apply(this,t)}},{key:"getHelpMsg",value:function(){var e=this.props,t=this.getOnlyControl();if(void 0===e.help&&t){var n=this.getField().errors;return n?n.map(function(e){return e.message}).join(", "):""}return e.help}},{key:"getControls",value:function(e,n){for(var r=[],o=Jo.Children.toArray(e),i=0;i<o.length&&(n||!(r.length>0));i++){var a=o[i];(!a.type||a.type!==t&&"FormItem"!==a.type.displayName)&&a.props&&("data-__meta"in a.props?r.push(a):a.props.children&&(r=r.concat(this.getControls(a.props.children,n))))}return r}},{key:"getOnlyControl",value:function(){var e=this.getControls(this.props.children,!1)[0];return void 0!==e?e:null}},{key:"getChildProp",value:function(e){var t=this.getOnlyControl();return t&&t.props&&t.props[e]}},{key:"getId",value:function(){return this.getChildProp("id")}},{key:"getMeta",value:function(){return this.getChildProp("data-__meta")}},{key:"getField",value:function(){return this.getChildProp("data-__field")}},{key:"renderHelp",value:function(){var e=this.props.prefixCls,t=this.getHelpMsg(),n=t?Jo.createElement("div",{className:e+"-explain",key:"help"},t):null;return Jo.createElement(Ui.a,{transitionName:"show-help",component:"",transitionAppear:!0,key:"help",onEnd:this.onHelpAnimEnd},n)}},{key:"renderExtra",value:function(){var e=this.props,t=e.prefixCls,n=e.extra;return n?Jo.createElement("div",{className:t+"-extra"},n):null}},{key:"getValidateStatus",value:function(){if(!this.getOnlyControl())return"";var e=this.getField();if(e.validating)return"validating";if(e.errors)return"error";var t="value"in e?e.value:this.getMeta().initialValue;return void 0!==t&&null!==t&&""!==t?"success":""}},{key:"renderValidateWrapper",value:function(e,t,n){var r=this.props,o=this.getOnlyControl,i=void 0===r.validateStatus&&o?this.getValidateStatus():r.validateStatus,a=this.props.prefixCls+"-item-control";return i&&(a=ii()(this.props.prefixCls+"-item-control",{"has-feedback":r.hasFeedback||"validating"===i,"has-success":"success"===i,"has-warning":"warning"===i,"has-error":"error"===i,"is-validating":"validating"===i})),Jo.createElement("div",{className:a},Jo.createElement("span",{className:this.props.prefixCls+"-item-children"},e),t,n)}},{key:"renderWrapper",value:function(e){var t=this.props,n=t.prefixCls,r=t.wrapperCol,o=ii()(n+"-item-control-wrapper",r&&r.className);return Jo.createElement(Sl,Vo()({},r,{className:o,key:"wrapper"}),e)}},{key:"isRequired",value:function(){var e=this.props.required;if(void 0!==e)return e;if(this.getOnlyControl()){return((this.getMeta()||{}).validate||[]).filter(function(e){return!!e.rules}).some(function(e){return e.rules.some(function(e){return e.required})})}return!1}},{key:"renderLabel",value:function(){var e=this.props,t=e.prefixCls,n=e.label,r=e.labelCol,o=e.colon,i=e.id,a=this.context,s=this.isRequired(),l=ii()(t+"-item-label",r&&r.className),u=ii()(Ko()({},t+"-item-required",s)),c=n;return o&&!a.vertical&&"string"==typeof n&&""!==n.trim()&&(c=n.replace(/[\uff1a|:]\s*$/,"")),n?Jo.createElement(Sl,Vo()({},r,{className:l,key:"label"}),Jo.createElement("label",{htmlFor:i||this.getId(),className:u,title:"string"==typeof n?n:"",onClick:this.onLabelClick},c)):null}},{key:"renderChildren",value:function(){var e=this.props.children;return[this.renderLabel(),this.renderWrapper(this.renderValidateWrapper(e,this.renderHelp(),this.renderExtra()))]}},{key:"renderFormItem",value:function(e){var t,n=this.props,r=n.prefixCls,o=n.style,i=(t={},Ko()(t,r+"-item",!0),Ko()(t,r+"-item-with-help",!!this.getHelpMsg()||this.state.helpShow),Ko()(t,r+"-item-no-colon",!n.colon),Ko()(t,""+n.className,!!n.className),t);return Jo.createElement(yl,{className:ii()(i),style:o},e)}},{key:"render",value:function(){var e=this.renderChildren();return this.renderFormItem(e)}}]),t}(Jo.Component),Ec=kc;kc.defaultProps={hasFeedback:!1,prefixCls:"ant-form",colon:!0},kc.propTypes={prefixCls:ni.a.string,label:ni.a.oneOfType([ni.a.string,ni.a.node]),labelCol:ni.a.object,help:ni.a.oneOfType([ni.a.node,ni.a.bool]),validateStatus:ni.a.oneOf(["","success","warning","error","validating"]),hasFeedback:ni.a.bool,wrapperCol:ni.a.object,className:ni.a.string,id:ni.a.string,children:ni.a.node,colon:ni.a.bool},kc.contextTypes={vertical:ni.a.bool};var Oc=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return Object(aa.a)(!e.form,"It is unnecessary to pass `form` to `Form` after [email protected]."),n}return Go()(t,e),Ho()(t,[{key:"shouldComponentUpdate",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return _c.a.shouldComponentUpdate.apply(this,t)}},{key:"getChildContext",value:function(){return{vertical:"vertical"===this.props.layout}}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.hideRequiredMark,o=t.className,i=void 0===o?"":o,a=t.layout,s=ii()(n,(e={},Ko()(e,n+"-horizontal","horizontal"===a),Ko()(e,n+"-vertical","vertical"===a),Ko()(e,n+"-inline","inline"===a),Ko()(e,n+"-hide-required-mark",r),e),i),l=Object(li.a)(this.props,["prefixCls","className","layout","form","hideRequiredMark"]);return Jo.createElement("form",Vo()({},l,{className:s}))}}]),t}(Jo.Component),Tc=Oc;Oc.defaultProps={prefixCls:"ant-form",layout:"horizontal",hideRequiredMark:!1,onSubmit:function(e){e.preventDefault()}},Oc.propTypes={prefixCls:ni.a.string,layout:ni.a.oneOf(["horizontal","inline","vertical"]),children:ni.a.any,onSubmit:ni.a.func,hideRequiredMark:ni.a.bool},Oc.childContextTypes={vertical:ni.a.bool},Oc.Item=Ec,Oc.createFormField=un,Oc.create=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Sc(Vo()({fieldNameProp:"id"},e,{fieldMetaProp:"data-__meta",fieldDataProp:"data-__field"}))};var Nc=Tc,Pc=("undefined"!=typeof window&&window,function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={active:!1},e.onTouchStart=function(t){e.triggerEvent("TouchStart",!0,t)},e.onTouchMove=function(t){e.triggerEvent("TouchMove",!1,t)},e.onTouchEnd=function(t){e.triggerEvent("TouchEnd",!1,t)},e.onTouchCancel=function(t){e.triggerEvent("TouchCancel",!1,t)},e.onMouseDown=function(t){e.props.onTouchStart&&e.triggerEvent("TouchStart",!0,t),e.triggerEvent("MouseDown",!0,t)},e.onMouseUp=function(t){e.props.onTouchEnd&&e.triggerEvent("TouchEnd",!1,t),e.triggerEvent("MouseUp",!1,t)},e.onMouseLeave=function(t){e.triggerEvent("MouseLeave",!1,t)},e}return Go()(t,e),Ho()(t,[{key:"componentDidUpdate",value:function(){this.props.disabled&&this.state.active&&this.setState({active:!1})}},{key:"triggerEvent",value:function(e,t,n){var r="on"+e;this.props[r]&&this.props[r](n),t!==this.state.active&&this.setState({active:t})}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.disabled,r=e.activeClassName,o=e.activeStyle,i=n?void 0:{onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchCancel,onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onMouseLeave:this.onMouseLeave},a=Zo.a.Children.only(t);if(!n&&this.state.active){var s=a.props,l=s.style,u=s.className;return!1!==o&&(o&&(l=Vo()({},l,o)),u=ii()(u,r)),Zo.a.cloneElement(a,Vo()({className:u,style:l},i))}return Zo.a.cloneElement(a,i)}}]),t}(Zo.a.Component)),Mc=Pc;Pc.defaultProps={disabled:!1};var Dc=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.disabled,r=e.onTouchStart,o=e.onTouchEnd,i=e.onMouseDown,a=e.onMouseUp,s=e.onMouseLeave,l=$a()(e,["prefixCls","disabled","onTouchStart","onTouchEnd","onMouseDown","onMouseUp","onMouseLeave"]);return Zo.a.createElement(Mc,{disabled:n,onTouchStart:r,onTouchEnd:o,onMouseDown:i,onMouseUp:a,onMouseLeave:s,activeClassName:t+"-handler-active"},Zo.a.createElement("span",l))},t}(Jo.Component);Dc.propTypes={prefixCls:ni.a.string,disabled:ni.a.bool,onTouchStart:ni.a.func,onTouchEnd:ni.a.func,onMouseDown:ni.a.func,onMouseUp:ni.a.func,onMouseLeave:ni.a.func};var Ic=Dc,Ac=Number.MAX_SAFE_INTEGER||Math.pow(2,53)-1,jc=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));Rc.call(r);var o=void 0;return o="value"in n?n.value:n.defaultValue,o=r.toNumber(o),r.state={inputValue:r.toPrecisionAsStep(o),value:o,focused:n.autoFocus},r}return Go()(t,e),t.prototype.componentDidMount=function(){this.componentDidUpdate()},t.prototype.componentWillReceiveProps=function(e){if("value"in e){var t=this.state.focused?e.value:this.getValidValue(e.value,e.min,e.max);this.setState({value:t,inputValue:this.inputting?t:this.toPrecisionAsStep(t)})}},t.prototype.componentWillUpdate=function(){try{this.start=this.input.selectionStart,this.end=this.input.selectionEnd}catch(e){}},t.prototype.componentDidUpdate=function(){if(this.props.focusOnUpDown&&this.state.focused){var e=this.input.setSelectionRange;e&&"function"==typeof e&&void 0!==this.start&&void 0!==this.end?this.input.setSelectionRange(this.start,this.end):this.focus()}},t.prototype.componentWillUnmount=function(){this.stop()},t.prototype.getCurrentValidValue=function(e){var t=e;return t=""===t?"":this.isNotCompleteNumber(t)?this.state.value:this.getValidValue(t),this.toNumber(t)},t.prototype.getRatio=function(e){var t=1;return e.metaKey||e.ctrlKey?t=.1:e.shiftKey&&(t=10),t},t.prototype.getValueFromEvent=function(e){return e.target.value.trim().replace(/\u3002/g,".")},t.prototype.getValidValue=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.props.min,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.props.max,r=parseFloat(e,10);return isNaN(r)?e:(r<t&&(r=t),r>n&&(r=n),r)},t.prototype.setValue=function(e,t){var n=this.isNotCompleteNumber(parseFloat(e,10))?void 0:parseFloat(e,10),r=n!==this.state.value||""+n!=""+this.state.inputValue;"value"in this.props?this.setState({inputValue:this.toPrecisionAsStep(this.state.value)},t):this.setState({value:n,inputValue:this.toPrecisionAsStep(e)},t),r&&this.props.onChange(n)},t.prototype.getPrecision=function(e){if("precision"in this.props)return this.props.precision;var t=e.toString();if(t.indexOf("e-")>=0)return parseInt(t.slice(t.indexOf("e-")+2),10);var n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},t.prototype.getMaxPrecision=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if("precision"in this.props)return this.props.precision;var n=this.props.step,r=this.getPrecision(t),o=this.getPrecision(n),i=this.getPrecision(e);return e?Math.max(i,r+o):r+o},t.prototype.getPrecisionFactor=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=this.getMaxPrecision(e,t);return Math.pow(10,n)},t.prototype.focus=function(){this.input.focus()},t.prototype.blur=function(){this.input.blur()},t.prototype.formatWrapper=function(e){return this.props.formatter?this.props.formatter(e):e},t.prototype.toPrecisionAsStep=function(e){if(this.isNotCompleteNumber(e)||""===e)return e;var t=Math.abs(this.getMaxPrecision(e));return 0===t?e.toString():isNaN(t)?e.toString():Number(e).toFixed(t)},t.prototype.isNotCompleteNumber=function(e){return isNaN(e)||""===e||null===e||e&&e.toString().indexOf(".")===e.toString().length-1},t.prototype.toNumber=function(e){return this.isNotCompleteNumber(e)?e:"precision"in this.props?Number(Number(e).toFixed(this.props.precision)):Number(e)},t.prototype.toNumberWhenUserInput=function(e){return(/\.\d*0$/.test(e)||e.length>16)&&this.state.focused?e:this.toNumber(e)},t.prototype.upStep=function(e,t){var n=this.props,r=n.step,o=n.min,i=this.getPrecisionFactor(e,t),a=Math.abs(this.getMaxPrecision(e,t)),s=void 0;return s="number"==typeof e?((i*e+i*r*t)/i).toFixed(a):o===-1/0?r:o,this.toNumber(s)},t.prototype.downStep=function(e,t){var n=this.props,r=n.step,o=n.min,i=this.getPrecisionFactor(e,t),a=Math.abs(this.getMaxPrecision(e,t)),s=void 0;return s="number"==typeof e?((i*e-i*r*t)/i).toFixed(a):o===-1/0?-r:o,this.toNumber(s)},t.prototype.step=function(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,o=arguments[3];this.stop(),t&&(t.persist(),t.preventDefault());var i=this.props;if(!i.disabled){var a=this.getCurrentValidValue(this.state.inputValue)||0;if(!this.isNotCompleteNumber(a)){var s=this[e+"Step"](a,r),l=s>i.max||s<i.min;s>i.max?s=i.max:s<i.min&&(s=i.min),this.setValue(s),this.setState({focused:!0}),l||(this.autoStepTimer=setTimeout(function(){n[e](t,r,!0)},o?200:600))}}},t.prototype.render=function(){var e,t=Vo()({},this.props),n=t.prefixCls,r=t.disabled,o=t.readOnly,i=t.useTouch,a=ii()((e={},e[n]=!0,e[t.className]=!!t.className,e[n+"-disabled"]=r,e[n+"-focused"]=this.state.focused,e)),s="",l="",u=this.state.value;if(u||0===u)if(isNaN(u))s=n+"-handler-up-disabled",l=n+"-handler-down-disabled";else{var c=Number(u);c>=t.max&&(s=n+"-handler-up-disabled"),c<=t.min&&(l=n+"-handler-down-disabled")}var p=!t.readOnly&&!t.disabled,f=void 0;void 0!==(f=this.state.focused?this.state.inputValue:this.toPrecisionAsStep(this.state.value))&&null!==f||(f="");var d=void 0,h=void 0;i?(d={onTouchStart:p&&!s?this.up:Pn,onTouchEnd:this.stop},h={onTouchStart:p&&!l?this.down:Pn,onTouchEnd:this.stop}):(d={onMouseDown:p&&!s?this.up:Pn,onMouseUp:this.stop,onMouseLeave:this.stop},h={onMouseDown:p&&!l?this.down:Pn,onMouseUp:this.stop,onMouseLeave:this.stop});var v=this.formatWrapper(f),m=!!s||r||o,y=!!l||r||o;return Zo.a.createElement("div",{className:a,style:t.style,onMouseEnter:t.onMouseEnter,onMouseLeave:t.onMouseLeave,onMouseOver:t.onMouseOver,onMouseOut:t.onMouseOut},Zo.a.createElement("div",{className:n+"-handler-wrap"},Zo.a.createElement(Ic,Vo()({ref:"up",disabled:m,prefixCls:n,unselectable:"unselectable"},d,{role:"button","aria-label":"Increase Value","aria-disabled":!!m,className:n+"-handler "+n+"-handler-up "+s}),this.props.upHandler||Zo.a.createElement("span",{unselectable:"unselectable",className:n+"-handler-up-inner",onClick:Mn})),Zo.a.createElement(Ic,Vo()({ref:"down",disabled:y,prefixCls:n,unselectable:"unselectable"},h,{role:"button","aria-label":"Decrease Value","aria-disabled":!!y,className:n+"-handler "+n+"-handler-down "+l}),this.props.downHandler||Zo.a.createElement("span",{unselectable:"unselectable",className:n+"-handler-down-inner",onClick:Mn}))),Zo.a.createElement("div",{className:n+"-input-wrap",role:"spinbutton","aria-valuemin":t.min,"aria-valuemax":t.max,"aria-valuenow":u},Zo.a.createElement("input",{required:t.required,type:t.type,placeholder:t.placeholder,onClick:t.onClick,className:n+"-input",tabIndex:t.tabIndex,autoComplete:"off",onFocus:this.onFocus,onBlur:this.onBlur,onKeyDown:p?this.onKeyDown:Pn,onKeyUp:p?this.onKeyUp:Pn,autoFocus:t.autoFocus,maxLength:t.maxLength,readOnly:t.readOnly,disabled:t.disabled,max:t.max,min:t.min,step:t.step,name:t.name,id:t.id,onChange:this.onChange,ref:this.saveInput,value:v,pattern:t.pattern})))},t}(Zo.a.Component);jc.propTypes={value:ni.a.oneOfType([ni.a.number,ni.a.string]),defaultValue:ni.a.oneOfType([ni.a.number,ni.a.string]),focusOnUpDown:ni.a.bool,autoFocus:ni.a.bool,onChange:ni.a.func,onKeyDown:ni.a.func,onKeyUp:ni.a.func,prefixCls:ni.a.string,tabIndex:ni.a.string,disabled:ni.a.bool,onFocus:ni.a.func,onBlur:ni.a.func,readOnly:ni.a.bool,max:ni.a.number,min:ni.a.number,step:ni.a.oneOfType([ni.a.number,ni.a.string]),upHandler:ni.a.node,downHandler:ni.a.node,useTouch:ni.a.bool,formatter:ni.a.func,parser:ni.a.func,onMouseEnter:ni.a.func,onMouseLeave:ni.a.func,onMouseOver:ni.a.func,onMouseOut:ni.a.func,precision:ni.a.number,required:ni.a.bool,pattern:ni.a.string},jc.defaultProps={focusOnUpDown:!0,useTouch:!1,prefixCls:"rc-input-number",min:-Ac,step:1,style:{},onChange:Pn,onKeyDown:Pn,onFocus:Pn,onBlur:Pn,parser:Dn,required:!1};var Rc=function(){var e=this;this.onKeyDown=function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];if(38===t.keyCode){var i=e.getRatio(t);e.up(t,i),e.stop()}else if(40===t.keyCode){var a=e.getRatio(t);e.down(t,a),e.stop()}var s=e.props.onKeyDown;s&&s.apply(void 0,[t].concat(r))},this.onKeyUp=function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];e.stop();var i=e.props.onKeyUp;i&&i.apply(void 0,[t].concat(r))},this.onChange=function(t){e.state.focused&&(e.inputting=!0);var n=e.props.parser(e.getValueFromEvent(t));e.setState({inputValue:n}),e.props.onChange(e.toNumberWhenUserInput(n))},this.onFocus=function(){var t;e.setState({focused:!0}),(t=e.props).onFocus.apply(t,arguments)},this.onBlur=function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];e.inputting=!1,e.setState({focused:!1});var i=e.getCurrentValidValue(e.state.inputValue);t.persist(),e.setValue(i,function(){var n;(n=e.props).onBlur.apply(n,[t].concat(r))})},this.stop=function(){e.autoStepTimer&&clearTimeout(e.autoStepTimer)},this.down=function(t,n,r){e.step("down",t,n,r)},this.up=function(t,n,r){e.step("up",t,n,r)},this.saveInput=function(t){e.input=t}},Lc=jc,Kc=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Fc=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t=this,n=this.props,r=n.className,o=n.size,i=Kc(n,["className","size"]),a=ii()((e={},Ko()(e,this.props.prefixCls+"-lg","large"===o),Ko()(e,this.props.prefixCls+"-sm","small"===o),e),r);return Jo.createElement(Lc,Vo()({ref:function(e){return t.inputNumberRef=e},className:a},i))}},{key:"focus",value:function(){this.inputNumberRef.focus()}},{key:"blur",value:function(){this.inputNumberRef.blur()}}]),t}(Jo.Component),Vc=Fc;Fc.defaultProps={prefixCls:"ant-input-number",step:1};var zc=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Bc=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.children,o=zc(e,["prefixCls","className","children"]),i=ii()(n,t);return Jo.createElement("div",Vo()({className:i},o),r)}}]),t}(Jo.Component),Wc=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={siders:[]},e}return Go()(t,e),Ho()(t,[{key:"getChildContext",value:function(){var e=this;return{siderHook:{addSider:function(t){e.setState({siders:[].concat(ci()(e.state.siders),[t])})},removeSider:function(t){e.setState({siders:e.state.siders.filter(function(e){return e!==t})})}}}}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.children,o=e.hasSider,i=zc(e,["prefixCls","className","children","hasSider"]),a=ii()(n,t,Ko()({},t+"-has-sider",o||this.state.siders.length>0));return Jo.createElement("div",Vo()({className:a},i),r)}}]),t}(Jo.Component);Wc.childContextTypes={siderHook:ni.a.object};var Hc=In({prefixCls:"ant-layout"})(Wc),Uc=In({prefixCls:"ant-layout-header"})(Bc),qc=In({prefixCls:"ant-layout-footer"})(Bc),Yc=In({prefixCls:"ant-layout-content"})(Bc);Hc.Header=Uc,Hc.Footer=qc,Hc.Content=Yc;var Gc=Hc,Xc=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n};if("undefined"!=typeof window){var $c=function(e){return{media:e,matches:!1,addListener:function(){},removeListener:function(){}}};window.matchMedia=window.matchMedia||$c}var Jc={xs:"480px",sm:"576px",md:"768px",lg:"992px",xl:"1200px",xxl:"1600px"},Zc=function(){var e=0;return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return e+=1,""+t+e}}(),Qc=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.responsiveHandler=function(e){n.setState({below:e.matches}),n.state.collapsed!==e.matches&&n.setCollapsed(e.matches,"responsive")},n.setCollapsed=function(e,t){"collapsed"in n.props||n.setState({collapsed:e});var r=n.props.onCollapse;r&&r(e,t)},n.toggle=function(){var e=!n.state.collapsed;n.setCollapsed(e,"clickTrigger")},n.belowShowChange=function(){n.setState({belowShow:!n.state.belowShow})},n.uniqueId=Zc("ant-sider-");var r=void 0;"undefined"!=typeof window&&(r=window.matchMedia),r&&e.breakpoint&&e.breakpoint in Jc&&(n.mql=r("(max-width: "+Jc[e.breakpoint]+")"));var o=void 0;return o="collapsed"in e?e.collapsed:e.defaultCollapsed,n.state={collapsed:o,below:!1},n}return Go()(t,e),Ho()(t,[{key:"getChildContext",value:function(){return{siderCollapsed:this.state.collapsed,collapsedWidth:this.props.collapsedWidth}}},{key:"componentWillReceiveProps",value:function(e){"collapsed"in e&&this.setState({collapsed:e.collapsed})}},{key:"componentDidMount",value:function(){this.mql&&(this.mql.addListener(this.responsiveHandler),this.responsiveHandler(this.mql)),this.context.siderHook&&this.context.siderHook.addSider(this.uniqueId)}},{key:"componentWillUnmount",value:function(){this.mql&&this.mql.removeListener(this.responsiveHandler),this.context.siderHook&&this.context.siderHook.removeSider(this.uniqueId)}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.collapsible,i=t.reverseArrow,a=t.trigger,s=t.style,l=t.width,u=t.collapsedWidth,c=Xc(t,["prefixCls","className","collapsible","reverseArrow","trigger","style","width","collapsedWidth"]),p=Object(li.a)(c,["collapsed","defaultCollapsed","onCollapse","breakpoint"]),f=this.state.collapsed?u:l,d=0===u||"0"===u||"0px"===u?Jo.createElement("span",{onClick:this.toggle,className:n+"-zero-width-trigger"},Jo.createElement(Ni.a,{type:"bars"})):null,h={expanded:i?Jo.createElement(Ni.a,{type:"right"}):Jo.createElement(Ni.a,{type:"left"}),collapsed:i?Jo.createElement(Ni.a,{type:"left"}):Jo.createElement(Ni.a,{type:"right"})},v=this.state.collapsed?"collapsed":"expanded",m=h[v],y=null!==a?d||Jo.createElement("div",{className:n+"-trigger",onClick:this.toggle,style:{width:f}},a||m):null,g=Vo()({},s,{flex:"0 0 "+f+"px",maxWidth:f+"px",minWidth:f+"px",width:f+"px"}),b=ii()(r,n,(e={},Ko()(e,n+"-collapsed",!!this.state.collapsed),Ko()(e,n+"-has-trigger",o&&null!==a&&!d),Ko()(e,n+"-below",!!this.state.below),Ko()(e,n+"-zero-width",0===f||"0"===f||"0px"===f),e));return Jo.createElement("div",Vo()({className:b},p,{style:g}),Jo.createElement("div",{className:n+"-children"},this.props.children),o||this.state.below&&d?y:null)}}]),t}(Jo.Component),ep=Qc;Qc.__ANT_LAYOUT_SIDER=!0,Qc.defaultProps={prefixCls:"ant-layout-sider",collapsible:!1,defaultCollapsed:!1,reverseArrow:!1,width:200,collapsedWidth:80,style:{}},Qc.childContextTypes={siderCollapsed:ni.a.bool,collapsedWidth:ni.a.oneOfType([ni.a.number,ni.a.string])},Qc.contextTypes={siderHook:ni.a.object},Gc.Sider=ep;var tp=Gc,np=n(46),rp=n(139),op=n(140),ip=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},ap=function(e){var t=e.prefixCls,n=void 0===t?"ant-list":t,r=e.className,o=e.avatar,i=e.title,a=e.description,s=ip(e,["prefixCls","className","avatar","title","description"]),l=ii()(n+"-item-meta",r),u=Jo.createElement("div",{className:n+"-item-meta-content"},i&&Jo.createElement("h4",{className:n+"-item-meta-title"},i),a&&Jo.createElement("div",{className:n+"-item-meta-description"},a));return Jo.createElement("div",Vo()({},s,{className:l}),o&&Jo.createElement("div",{className:n+"-item-meta-avatar"},o),(i||a)&&u)},sp=["",1,2,3,4,6,8,12,24],lp=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.context.grid,t=this.props,n=t.prefixCls,r=void 0===n?"ant-list":n,o=t.children,i=t.actions,a=t.extra,s=t.className,l=ip(t,["prefixCls","children","actions","extra","className"]),u=ii()(r+"-item",s),c=[],p=[];Jo.Children.forEach(o,function(e){e&&e.type&&e.type===ap?c.push(e):p.push(e)});var f=ii()(r+"-item-content",Ko()({},r+"-item-content-single",c.length<1)),d=p.length>0?Jo.createElement("div",{className:f},p):null,h=void 0;if(i&&i.length>0){var v=function(e,t){return Jo.createElement("li",{key:r+"-item-action-"+t},e,t!==i.length-1&&Jo.createElement("em",{className:r+"-item-action-split"}))};h=Jo.createElement("ul",{className:r+"-item-action"},i.map(function(e,t){return v(e,t)}))}var m=Jo.createElement("div",{className:r+"-item-extra-wrap"},Jo.createElement("div",{className:r+"-item-main"},c,d,h),Jo.createElement("div",{className:r+"-item-extra"},a));return e?Jo.createElement(Sl,{span:An(e,"column"),xs:An(e,"xs"),sm:An(e,"sm"),md:An(e,"md"),lg:An(e,"lg"),xl:An(e,"xl"),xxl:An(e,"xxl")},Jo.createElement("div",Vo()({},l,{className:u}),a&&m,!a&&c,!a&&d,!a&&h)):Jo.createElement("div",Vo()({},l,{className:u}),a&&m,!a&&c,!a&&d,!a&&h)}}]),t}(Jo.Component),up=lp;lp.Meta=ap,lp.propTypes={column:ni.a.oneOf(sp),xs:ni.a.oneOf(sp),sm:ni.a.oneOf(sp),md:ni.a.oneOf(sp),lg:ni.a.oneOf(sp),xl:ni.a.oneOf(sp),xxl:ni.a.oneOf(sp)},lp.contextTypes={grid:ni.a.any};var cp=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},pp=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.keys={},e.renderItem=function(t,n){var r=e.props,o=r.dataSource,i=r.renderItem,a=r.rowKey,s=void 0;return s="function"==typeof a?a(o[n]):"string"==typeof a?o[a]:o.key,s||(s="list-item-"+n),e.keys[n]=s,i(t,n)},e.renderEmpty=function(t){var n=Vo()({},t,e.props.locale);return Jo.createElement("div",{className:e.props.prefixCls+"-empty-text"},n.emptyText)},e}return Go()(t,e),Ho()(t,[{key:"getChildContext",value:function(){return{grid:this.props.grid}}},{key:"isSomethingAfterLastTtem",value:function(){var e=this.props,t=e.loadMore,n=e.pagination,r=e.footer;return!!(t||n||r)}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.bordered,o=n.split,i=n.className,a=n.children,s=n.itemLayout,l=n.loadMore,u=n.pagination,c=n.prefixCls,p=n.grid,f=n.dataSource,d=n.size,h=(n.rowKey,n.renderItem,n.header),v=n.footer,m=n.loading,y=cp(n,["bordered","split","className","children","itemLayout","loadMore","pagination","prefixCls","grid","dataSource","size","rowKey","renderItem","header","footer","loading"]),g=m;"boolean"==typeof g&&(g={spinning:g});var b=g&&g.spinning,C="";switch(d){case"large":C="lg";break;case"small":C="sm"}var w=ii()(c,i,(e={},Ko()(e,c+"-vertical","vertical"===s),Ko()(e,c+"-"+C,C),Ko()(e,c+"-split",o),Ko()(e,c+"-bordered",r),Ko()(e,c+"-loading",b),Ko()(e,c+"-grid",p),Ko()(e,c+"-something-after-last-item",this.isSomethingAfterLastTtem()),e)),S=Jo.createElement("div",{className:c+"-pagination"},Jo.createElement(op.a,u)),x=void 0;if(x=b&&Jo.createElement("div",{style:{minHeight:53}}),f.length>0){var _=f.map(function(e,n){return t.renderItem(e,n)}),k=Jo.Children.map(_,function(e,n){return Jo.cloneElement(e,{key:t.keys[n]})});x=p?Jo.createElement(yl,{gutter:p.gutter},k):k}else a||b||(x=Jo.createElement(La.a,{componentName:"Table",defaultLocale:np.a.Table},this.renderEmpty));var E=Jo.createElement("div",null,Jo.createElement(rp.a,g,x),l,!l&&u?S:null);return Jo.createElement("div",Vo()({className:w},y),h&&Jo.createElement("div",{className:c+"-header"},h),E,a,v&&Jo.createElement("div",{className:c+"-footer"},v))}}]),t}(Jo.Component),fp=pp;pp.Item=up,pp.childContextTypes={grid:ni.a.any},pp.defaultProps={dataSource:[],prefixCls:"ant-list",bordered:!1,split:!0,loading:!1,pagination:!1};var dp=Vo()({},np.a.Modal),hp=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"getChildContext",value:function(){return{antLocale:Vo()({},this.props.locale,{exist:!0})}}},{key:"componentWillMount",value:function(){Ln(this.props.locale),this.componentDidUpdate()}},{key:"componentWillReceiveProps",value:function(e){this.props.locale!==e.locale&&Ln(e.locale)}},{key:"componentDidUpdate",value:function(){var e=this.props.locale;jn(e&&e.Modal)}},{key:"componentWillUnmount",value:function(){jn()}},{key:"render",value:function(){return Jo.Children.only(this.props.children)}}]),t}(Jo.Component),vp=hp;hp.propTypes={locale:ni.a.object},hp.defaultProps={locale:{}},hp.childContextTypes={antLocale:ni.a.object};var mp=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.close=function(){r.clearCloseTimer(),r.props.onClose()},r.startCloseTimer=function(){r.props.duration&&(r.closeTimer=setTimeout(function(){r.close()},1e3*r.props.duration))},r.clearCloseTimer=function(){r.closeTimer&&(clearTimeout(r.closeTimer),r.closeTimer=null)},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.startCloseTimer()}},{key:"componentWillUnmount",value:function(){this.clearCloseTimer()}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls+"-notice",r=(e={},Ko()(e,""+n,1),Ko()(e,n+"-closable",t.closable),Ko()(e,t.className,!!t.className),e);return Zo.a.createElement("div",{className:ii()(r),style:t.style,onMouseEnter:this.clearCloseTimer,onMouseLeave:this.startCloseTimer},Zo.a.createElement("div",{className:n+"-content"},t.children),t.closable?Zo.a.createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},Zo.a.createElement("span",{className:n+"-close-x"})):null)}}]),t}(Jo.Component);mp.propTypes={duration:ni.a.number,onClose:ni.a.func,children:ni.a.any},mp.defaultProps={onEnd:function(){},onClose:function(){},duration:1.5,style:{right:"50%"}};var yp=mp,gp=0,bp=Date.now(),Cp=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.state={notices:[]},r.add=function(e){var t=e.key=e.key||Kn();r.setState(function(n){var r=n.notices;if(!r.filter(function(e){return e.key===t}).length)return{notices:r.concat(e)}})},r.remove=function(e){r.setState(function(t){return{notices:t.notices.filter(function(t){return t.key!==e})}})},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"getTransitionName",value:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t}},{key:"render",value:function(){var e,t=this,n=this.props,r=this.state.notices.map(function(e){var r=Object(zl.a)(t.remove.bind(t,e.key),e.onClose);return Zo.a.createElement(yp,Vo()({prefixCls:n.prefixCls},e,{onClose:r}),e.content)}),o=(e={},Ko()(e,n.prefixCls,1),Ko()(e,n.className,!!n.className),e);return Zo.a.createElement("div",{className:ii()(o),style:n.style},Zo.a.createElement(Ui.a,{transitionName:this.getTransitionName()},r))}}]),t}(Jo.Component);Cp.propTypes={prefixCls:ni.a.string,transitionName:ni.a.string,animation:ni.a.oneOfType([ni.a.string,ni.a.object]),style:ni.a.object},Cp.defaultProps={prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}},Cp.newInstance=function(e,t){function n(e){s||(s=!0,t({notice:function(t){e.add(t)},removeNotice:function(t){e.remove(t)},component:e,destroy:function(){ei.a.unmountComponentAtNode(a),a.parentNode.removeChild(a)}}))}var r=e||{},o=r.getContainer,i=$a()(r,["getContainer"]),a=document.createElement("div");if(o){o().appendChild(a)}else document.body.appendChild(a);var s=!1;ei.a.render(Zo.a.createElement(Cp,Vo()({},i,{ref:n})),a)};var wp=Cp,Sp=wp,xp=3,_p=void 0,kp=void 0,Ep=1,Op="ant-message",Tp="move-up",Np=void 0,Pp={info:function(e,t,n){return Vn(e,t,"info",n)},success:function(e,t,n){return Vn(e,t,"success",n)},error:function(e,t,n){return Vn(e,t,"error",n)},warn:function(e,t,n){return Vn(e,t,"warning",n)},warning:function(e,t,n){return Vn(e,t,"warning",n)},loading:function(e,t,n){return Vn(e,t,"loading",n)},config:function(e){void 0!==e.top&&(_p=e.top,kp=null),void 0!==e.duration&&(xp=e.duration),void 0!==e.prefixCls&&(Op=e.prefixCls),void 0!==e.getContainer&&(Np=e.getContainer),void 0!==e.transitionName&&(Tp=e.transitionName,kp=null)},destroy:function(){kp&&(kp.destroy(),kp=null)}},Mp=n(198),Dp=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.shouldComponentUpdate=function(e){return!!e.hiddenClassName||!!e.visible},t.prototype.render=function(){var e=this.props.className;this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName);var t=Vo()({},this.props);return delete t.hiddenClassName,delete t.visible,t.className=e,Jo.createElement("div",Vo()({},t))},t}(Jo.Component),Ip=Dp,Ap=void 0,jp=0,Rp=0,Lp=function(e){function t(){Bo()(this,t);var n=qo()(this,e.apply(this,arguments));return n.onAnimateLeave=function(){var e=n.props.afterClose;n.wrap&&(n.wrap.style.display="none"),n.inTransition=!1,n.removeScrollingEffect(),e&&e()},n.onMaskClick=function(e){Date.now()-n.openTime<300||e.target===e.currentTarget&&n.close(e)},n.onKeyDown=function(e){var t=n.props;if(t.keyboard&&e.keyCode===$s.a.ESC&&n.close(e),t.visible&&e.keyCode===$s.a.TAB){var r=document.activeElement,o=n.wrap;e.shiftKey?r===o&&n.sentinel.focus():r===n.sentinel&&o.focus()}},n.getDialogElement=function(){var e=n.props,t=e.closable,r=e.prefixCls,o={};void 0!==e.width&&(o.width=e.width),void 0!==e.height&&(o.height=e.height);var i=void 0;e.footer&&(i=Jo.createElement("div",{className:r+"-footer",ref:"footer"},e.footer));var a=void 0;e.title&&(a=Jo.createElement("div",{className:r+"-header",ref:"header"},Jo.createElement("div",{className:r+"-title",id:n.titleId},e.title)));var s=void 0;t&&(s=Jo.createElement("button",{onClick:n.close,"aria-label":"Close",className:r+"-close"},Jo.createElement("span",{className:r+"-close-x"})));var l=Vo()({},e.style,o),u=n.getTransitionName(),c=Jo.createElement(Ip,{key:"dialog-element",role:"document",ref:n.saveRef("dialog"),style:l,className:r+" "+(e.className||""),visible:e.visible},Jo.createElement("div",{className:r+"-content"},s,a,Jo.createElement("div",Vo()({className:r+"-body",style:e.bodyStyle,ref:"body"},e.bodyProps),e.children),i),Jo.createElement("div",{tabIndex:0,ref:n.saveRef("sentinel"),style:{width:0,height:0,overflow:"hidden"}},"sentinel"));return Jo.createElement(Ui.a,{key:"dialog",showProp:"visible",onLeave:n.onAnimateLeave,transitionName:u,component:"",transitionAppear:!0},e.visible||!e.destroyOnClose?c:null)},n.getZIndexStyle=function(){var e={},t=n.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},n.getWrapStyle=function(){return Vo()({},n.getZIndexStyle(),n.props.wrapStyle)},n.getMaskStyle=function(){return Vo()({},n.getZIndexStyle(),n.props.maskStyle)},n.getMaskElement=function(){var e=n.props,t=void 0;if(e.mask){var r=n.getMaskTransitionName();t=Jo.createElement(Ip,Vo()({style:n.getMaskStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible},e.maskProps)),r&&(t=Jo.createElement(Ui.a,{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:r},t))}return t},n.getMaskTransitionName=function(){var e=n.props,t=e.maskTransitionName,r=e.maskAnimation;return!t&&r&&(t=e.prefixCls+"-"+r),t},n.getTransitionName=function(){var e=n.props,t=e.transitionName,r=e.animation;return!t&&r&&(t=e.prefixCls+"-"+r),t},n.setScrollbar=function(){n.bodyIsOverflowing&&void 0!==n.scrollbarWidth&&(document.body.style.paddingRight=n.scrollbarWidth+"px")},n.addScrollingEffect=function(){1===++Rp&&(n.checkScrollbar(),n.setScrollbar(),document.body.style.overflow="hidden")},n.removeScrollingEffect=function(){0===--Rp&&(document.body.style.overflow="",n.resetScrollbar())},n.close=function(e){var t=n.props.onClose;t&&t(e)},n.checkScrollbar=function(){var e=window.innerWidth;if(!e){var t=document.documentElement.getBoundingClientRect();e=t.right-Math.abs(t.left)}n.bodyIsOverflowing=document.body.clientWidth<e,n.bodyIsOverflowing&&(n.scrollbarWidth=zn())},n.resetScrollbar=function(){document.body.style.paddingRight=""},n.adjustDialog=function(){if(n.wrap&&void 0!==n.scrollbarWidth){var e=n.wrap.scrollHeight>document.documentElement.clientHeight;n.wrap.style.paddingLeft=(!n.bodyIsOverflowing&&e?n.scrollbarWidth:"")+"px",n.wrap.style.paddingRight=(n.bodyIsOverflowing&&!e?n.scrollbarWidth:"")+"px"}},n.resetAdjustments=function(){n.wrap&&(n.wrap.style.paddingLeft=n.wrap.style.paddingLeft="")},n.saveRef=function(e){return function(t){n[e]=t}},n}return Go()(t,e),t.prototype.componentWillMount=function(){this.inTransition=!1,this.titleId="rcDialogTitle"+jp++},t.prototype.componentDidMount=function(){this.componentDidUpdate({})},t.prototype.componentDidUpdate=function(e){var t=this.props,n=this.props.mousePosition;if(t.visible){if(!e.visible){this.openTime=Date.now(),this.lastOutSideFocusNode=document.activeElement,this.addScrollingEffect(),this.wrap.focus();var r=Qo.findDOMNode(this.dialog);if(n){var o=Hn(r);Wn(r,n.x-o.left+"px "+(n.y-o.top)+"px")}else Wn(r,"")}}else if(e.visible&&(this.inTransition=!0,t.mask&&this.lastOutSideFocusNode)){try{this.lastOutSideFocusNode.focus()}catch(e){this.lastOutSideFocusNode=null}this.lastOutSideFocusNode=null}},t.prototype.componentWillUnmount=function(){(this.props.visible||this.inTransition)&&this.removeScrollingEffect()},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.maskClosable,r=this.getWrapStyle();return e.visible&&(r.display=null),Jo.createElement("div",null,this.getMaskElement(),Jo.createElement("div",Vo()({tabIndex:-1,onKeyDown:this.onKeyDown,className:t+"-wrap "+(e.wrapClassName||""),ref:this.saveRef("wrap"),onClick:n?this.onMaskClick:void 0,role:"dialog","aria-labelledby":e.title?this.titleId:null,style:r},e.wrapProps),this.getDialogElement()))},t}(Jo.Component),Kp=Lp;Lp.defaultProps={className:"",mask:!0,visible:!1,keyboard:!0,closable:!0,maskClosable:!0,destroyOnClose:!1,prefixCls:"rc-dialog"};var Fp=n(179),Vp=n(180),zp=!!Qo.createPortal,Bp=function(e){function t(){Bo()(this,t);var n=qo()(this,e.apply(this,arguments));return n.saveDialog=function(e){n._component=e},n.getComponent=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Jo.createElement(Kp,Vo()({ref:n.saveDialog},n.props,e,{key:"dialog"}))},n.getContainer=function(){if(n.props.getContainer)return n.props.getContainer();var e=document.createElement("div");return document.body.appendChild(e),e},n}return Go()(t,e),t.prototype.shouldComponentUpdate=function(e){var t=e.visible;return!(!this.props.visible&&!t)},t.prototype.componentWillUnmount=function(){zp||(this.props.visible?this.renderComponent({afterClose:this.removeContainer,onClose:function(){},visible:!1}):this.removeContainer())},t.prototype.render=function(){var e=this,t=this.props.visible,n=null;return zp?((t||this._component)&&(n=Jo.createElement(Vp.a,{getContainer:this.getContainer},this.getComponent())),n):Jo.createElement(Fp.a,{parent:this,visible:t,autoDestroy:!1,getComponent:this.getComponent,getContainer:this.getContainer},function(t){var n=t.renderComponent,r=t.removeContainer;return e.renderComponent=n,e.removeContainer=r,null})},t}(Jo.Component);Bp.defaultProps={visible:!1};var Wp=Bp,Hp=void 0,Up=void 0,qp=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleCancel=function(t){var n=e.props.onCancel;n&&n(t)},e.handleOk=function(t){var n=e.props.onOk;n&&n(t)},e.renderFooter=function(t){var n=e.props,r=n.okText,o=n.okType,i=n.cancelText,a=n.confirmLoading;return Jo.createElement("div",null,Jo.createElement(Pi.a,{onClick:e.handleCancel},i||t.cancelText),Jo.createElement(Pi.a,{type:o,loading:a,onClick:e.handleOk},r||t.okText))},e}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){Up||(Object(ri.a)(document.documentElement,"click",function(e){Hp={x:e.pageX,y:e.pageY},setTimeout(function(){return Hp=null},100)}),Up=!0)}},{key:"render",value:function(){var e=this.props,t=e.footer,n=e.visible,r=Jo.createElement(La.a,{componentName:"Modal",defaultLocale:Rn()},this.renderFooter);return Jo.createElement(Wp,Vo()({},this.props,{footer:void 0===t?r:t,visible:n,mousePosition:Hp,onClose:this.handleCancel}))}}]),t}(Jo.Component),Yp=qp;qp.defaultProps={prefixCls:"ant-modal",width:520,transitionName:"zoom",maskTransitionName:"fade",confirmLoading:!1,visible:!1,okType:"primary"},qp.propTypes={prefixCls:ni.a.string,onOk:ni.a.func,onCancel:ni.a.func,okText:ni.a.node,cancelText:ni.a.node,width:ni.a.oneOfType([ni.a.number,ni.a.string]),confirmLoading:ni.a.bool,visible:ni.a.bool,align:ni.a.object,footer:ni.a.node,title:ni.a.node,closable:ni.a.bool};var Gp=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onClick=function(){var e=n.props,t=e.actionFn,r=e.closeModal;if(t){var o=void 0;t.length?o=t(r):(o=t())||r(),o&&o.then&&(n.setState({loading:!0}),o.then(function(){r.apply(void 0,arguments)},function(){n.setState({loading:!1})}))}else r()},n.state={loading:!1},n}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){if(this.props.autoFocus){var e=Qo.findDOMNode(this);this.timeoutId=setTimeout(function(){return e.focus()})}}},{key:"componentWillUnmount",value:function(){clearTimeout(this.timeoutId)}},{key:"render",value:function(){var e=this.props,t=e.type,n=e.children,r=this.state.loading;return Jo.createElement(Pi.a,{type:t,onClick:this.onClick,loading:r},n)}}]),t}(Jo.Component),Xp=Gp,$p=this,Jp=!!Qo.createPortal,Zp=function(e){var t=e.onCancel,n=e.onOk,r=e.close,o=e.zIndex,i=e.afterClose,a=e.visible,s=e.keyboard,l=e.iconType||"question-circle",u=e.okType||"primary",c=e.prefixCls||"ant-confirm",p=!("okCancel"in e)||e.okCancel,f=e.width||416,d=e.style||{},h=void 0!==e.maskClosable&&e.maskClosable,v=Rn(),m=e.okText||(p?v.okText:v.justOkText),y=e.cancelText||v.cancelText,g=ii()(c,c+"-"+e.type,e.className),b=p&&Jo.createElement(Xp,{actionFn:t,closeModal:r},y);return Jo.createElement(Yp,{className:g,onCancel:r.bind($p,{triggerCancel:!0}),visible:a,title:"",transitionName:"zoom",footer:"",maskTransitionName:"fade",maskClosable:h,style:d,width:f,zIndex:o,afterClose:i,keyboard:s},Jo.createElement("div",{className:c+"-body-wrapper"},Jo.createElement("div",{className:c+"-body"},Jo.createElement(Ni.a,{type:l}),Jo.createElement("span",{className:c+"-title"},e.title),Jo.createElement("div",{className:c+"-content"},e.content)),Jo.createElement("div",{className:c+"-btns"},b,Jo.createElement(Xp,{type:u,actionFn:n,closeModal:r,autoFocus:!0},m))))};Yp.info=function(e){return Un(Vo()({type:"info",iconType:"info-circle",okCancel:!1},e))},Yp.success=function(e){return Un(Vo()({type:"success",iconType:"check-circle",okCancel:!1},e))},Yp.error=function(e){return Un(Vo()({type:"error",iconType:"cross-circle",okCancel:!1},e))},Yp.warning=Yp.warn=function(e){return Un(Vo()({type:"warning",iconType:"exclamation-circle",okCancel:!1},e))},Yp.confirm=function(e){return Un(Vo()({type:"confirm",okCancel:!0},e))};var Qp=Yp,ef={},tf=4.5,nf=24,rf=24,of="topRight",af=void 0,sf={success:"check-circle-o",info:"info-circle-o",error:"cross-circle-o",warning:"exclamation-circle-o"},lf={open:Xn,close:function(e){Object.keys(ef).forEach(function(t){return ef[t].removeNotice(e)})},config:qn,destroy:function(){Object.keys(ef).forEach(function(e){ef[e].destroy(),delete ef[e]})}};["success","info","warning","error"].forEach(function(e){lf[e]=function(t){return lf.open(Vo()({},t,{type:e}))}}),lf.warn=lf.warning;var uf=lf,cf=n(63),pf=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},ff=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onConfirm=function(e){n.setVisible(!1);var t=n.props.onConfirm;t&&t.call(n,e)},n.onCancel=function(e){n.setVisible(!1);var t=n.props.onCancel;t&&t.call(n,e)},n.onVisibleChange=function(e){n.setVisible(e)},n.saveTooltip=function(e){n.tooltip=e},n.renderOverlay=function(e){var t=n.props,r=t.prefixCls,o=t.title,i=t.cancelText,a=t.okText,s=t.okType;return Jo.createElement("div",null,Jo.createElement("div",{className:r+"-inner-content"},Jo.createElement("div",{className:r+"-message"},Jo.createElement(Ni.a,{type:"exclamation-circle"}),Jo.createElement("div",{className:r+"-message-title"},o)),Jo.createElement("div",{className:r+"-buttons"},Jo.createElement(Pi.a,{onClick:n.onCancel,size:"small"},i||e.cancelText),Jo.createElement(Pi.a,{onClick:n.onConfirm,type:s,size:"small"},a||e.okText))))},n.state={visible:e.visible},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){"visible"in e&&this.setState({visible:e.visible})}},{key:"getPopupDomNode",value:function(){return this.tooltip.getPopupDomNode()}},{key:"setVisible",value:function(e){var t=this.props;"visible"in t||this.setState({visible:e});var n=t.onVisibleChange;n&&n(e)}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.placement,r=pf(e,["prefixCls","placement"]),o=Jo.createElement(La.a,{componentName:"Popconfirm",defaultLocale:np.a.Popconfirm},this.renderOverlay);return Jo.createElement(cf.a,Vo()({},r,{prefixCls:t,placement:n,onVisibleChange:this.onVisibleChange,visible:this.state.visible,overlay:o,ref:this.saveTooltip}))}}]),t}(Jo.Component),df=ff;ff.defaultProps={prefixCls:"ant-popover",transitionName:"zoom-big",placement:"top",trigger:"click",okType:"primary"};var hf=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveTooltip=function(t){e.tooltip=t},e}return Go()(t,e),Ho()(t,[{key:"getPopupDomNode",value:function(){return this.tooltip.getPopupDomNode()}},{key:"getOverlay",value:function(){var e=this.props,t=e.title,n=e.prefixCls,r=e.content;return Object(aa.a)(!("overlay"in this.props),"Popover[overlay] is removed, please use Popover[content] instead, see: https://u.ant.design/popover-content"),Jo.createElement("div",null,t&&Jo.createElement("div",{className:n+"-title"},t),Jo.createElement("div",{className:n+"-inner-content"},r))}},{key:"render",value:function(){var e=Vo()({},this.props);return delete e.title,Jo.createElement(cf.a,Vo()({},e,{ref:this.saveTooltip,overlay:this.getOverlay()}))}}]),t}(Jo.Component),vf=hf;hf.defaultProps={prefixCls:"ant-popover",placement:"top",transitionName:"zoom-big",trigger:"hover",mouseEnterDelay:.1,mouseLeaveDelay:.1,overlayStyle:{}};var mf=function(e){return function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.componentDidUpdate=function(){if(this.path){var e=this.path.style;e.transitionDuration=".3s, .3s, .3s, .06s";var t=Date.now();this.prevTimeStamp&&t-this.prevTimeStamp<100&&(e.transitionDuration="0s, 0s"),this.prevTimeStamp=Date.now()}},t.prototype.render=function(){return e.prototype.render.call(this)},t}(e)},yf=mf,gf={className:"",percent:0,prefixCls:"rc-progress",strokeColor:"#2db7f5",strokeLinecap:"round",strokeWidth:1,style:{},trailColor:"#D9D9D9",trailWidth:1},bf={className:ni.a.string,percent:ni.a.oneOfType([ni.a.number,ni.a.string]),prefixCls:ni.a.string,strokeColor:ni.a.string,strokeLinecap:ni.a.oneOf(["butt","round","square"]),strokeWidth:ni.a.oneOfType([ni.a.number,ni.a.string]),style:ni.a.object,trailColor:ni.a.string,trailWidth:ni.a.oneOfType([ni.a.number,ni.a.string])},Cf=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.render=function(){var e=this,t=this.props,n=t.className,r=t.percent,o=t.prefixCls,i=t.strokeColor,a=t.strokeLinecap,s=t.strokeWidth,l=t.style,u=t.trailColor,c=t.trailWidth,p=$a()(t,["className","percent","prefixCls","strokeColor","strokeLinecap","strokeWidth","style","trailColor","trailWidth"]);delete p.gapPosition;var f={strokeDasharray:"100px, 100px",strokeDashoffset:100-r+"px",transition:"stroke-dashoffset 0.3s ease 0s, stroke 0.3s linear"},d=s/2,h=100-s/2,v="M "+("round"===a?d:0)+","+d+"\n L "+("round"===a?h:100)+","+d,m="0 0 100 "+s;return Zo.a.createElement("svg",Vo()({className:o+"-line "+n,viewBox:m,preserveAspectRatio:"none",style:l},p),Zo.a.createElement("path",{className:o+"-line-trail",d:v,strokeLinecap:a,stroke:u,strokeWidth:c||s,fillOpacity:"0"}),Zo.a.createElement("path",{className:o+"-line-path",d:v,strokeLinecap:a,stroke:i,strokeWidth:s,fillOpacity:"0",ref:function(t){e.path=t},style:f}))},t}(Jo.Component);Cf.propTypes=bf,Cf.defaultProps=gf;var wf=(yf(Cf),function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.getPathStyles=function(){var e=this.props,t=e.percent,n=e.strokeWidth,r=e.gapDegree,o=void 0===r?0:r,i=e.gapPosition,a=50-n/2,s=0,l=-a,u=0,c=-2*a;switch(i){case"left":s=-a,l=0,u=2*a,c=0;break;case"right":s=a,l=0,u=-2*a,c=0;break;case"bottom":l=a,c=2*a}var p="M 50,50 m "+s+","+l+"\n a "+a+","+a+" 0 1 1 "+u+","+-c+"\n a "+a+","+a+" 0 1 1 "+-u+","+c,f=2*Math.PI*a;return{pathString:p,trailPathStyle:{strokeDasharray:f-o+"px "+f+"px",strokeDashoffset:"-"+o/2+"px",transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s"},strokePathStyle:{strokeDasharray:t/100*(f-o)+"px "+f+"px",strokeDashoffset:"-"+o/2+"px",transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s"}}},t.prototype.render=function(){var e=this,t=this.props,n=t.prefixCls,r=t.strokeWidth,o=t.trailWidth,i=t.strokeColor,a=(t.percent,t.trailColor),s=t.strokeLinecap,l=t.style,u=t.className,c=$a()(t,["prefixCls","strokeWidth","trailWidth","strokeColor","percent","trailColor","strokeLinecap","style","className"]),p=this.getPathStyles(),f=p.pathString,d=p.trailPathStyle,h=p.strokePathStyle;return delete c.percent,delete c.gapDegree,delete c.gapPosition,Zo.a.createElement("svg",Vo()({className:n+"-circle "+u,viewBox:"0 0 100 100",style:l},c),Zo.a.createElement("path",{className:n+"-circle-trail",d:f,stroke:a,strokeWidth:o||r,fillOpacity:"0",style:d}),Zo.a.createElement("path",{className:n+"-circle-path",d:f,strokeLinecap:s,stroke:i,strokeWidth:0===this.props.percent?0:r,fillOpacity:"0",ref:function(t){e.path=t},style:h}))},t}(Jo.Component));wf.propTypes=Vo()({},bf,{gapPosition:ni.a.oneOf(["top","bottom","left","right"])}),wf.defaultProps=Vo()({},gf,{gapPosition:"top"});var Sf=yf(wf),xf=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},_f={normal:"#108ee9",exception:"#ff5500",success:"#87d068"},kf=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.percent,i=void 0===o?0:o,a=t.status,s=t.format,l=t.trailColor,u=t.size,c=t.successPercent,p=t.type,f=t.strokeWidth,d=t.width,h=t.showInfo,v=t.gapDegree,m=void 0===v?0:v,y=t.gapPosition,g=xf(t,["prefixCls","className","percent","status","format","trailColor","size","successPercent","type","strokeWidth","width","showInfo","gapDegree","gapPosition"]),b=parseInt(c?c.toString():i.toString(),10)>=100&&!("status"in t)?"success":a||"normal",C=void 0,w=void 0,S=s||function(e){return e+"%"};if(h){var x=void 0,_="circle"===p||"dashboard"===p?"":"-circle";x="exception"===b?s?S(i):Jo.createElement(Ni.a,{type:"cross"+_}):"success"===b?s?S(i):Jo.createElement(Ni.a,{type:"check"+_}):S(i),C=Jo.createElement("span",{className:n+"-text"},x)}if("line"===p){var k={width:i+"%",height:f||("small"===u?6:8)},E={width:c+"%",height:f||("small"===u?6:8)},O=void 0!==c?Jo.createElement("div",{className:n+"-success-bg",style:E}):null;w=Jo.createElement("div",null,Jo.createElement("div",{className:n+"-outer"},Jo.createElement("div",{className:n+"-inner"},Jo.createElement("div",{className:n+"-bg",style:k}),O)),C)}else if("circle"===p||"dashboard"===p){var T=d||120,N={width:T,height:T,fontSize:.15*T+6},P=f||6,M=y||"dashboard"===p&&"bottom"||"top",D=m||"dashboard"===p&&75;w=Jo.createElement("div",{className:n+"-inner",style:N},Jo.createElement(Sf,{percent:i,strokeWidth:P,trailWidth:P,strokeColor:_f[b],trailColor:l,prefixCls:n,gapDegree:D,gapPosition:M}),C)}var I=ii()(n,(e={},Ko()(e,n+"-"+("dashboard"===p&&"circle"||p),!0),Ko()(e,n+"-status-"+b,!0),Ko()(e,n+"-show-info",h),Ko()(e,n+"-"+u,u),e),r);return Jo.createElement("div",Vo()({},g,{className:I}),w)}}]),t}(Jo.Component),Ef=kf;kf.defaultProps={type:"line",percent:0,showInfo:!0,trailColor:"#f3f3f3",prefixCls:"ant-progress",size:"default"},kf.propTypes={status:ni.a.oneOf(["normal","exception","active","success"]),type:ni.a.oneOf(["line","circle","dashboard"]),showInfo:ni.a.bool,percent:ni.a.number,width:ni.a.number,strokeWidth:ni.a.number,trailColor:ni.a.string,format:ni.a.func,gapDegree:ni.a.number,default:ni.a.oneOf(["default","small"])};var Of=Ef,Tf=function(e){function t(){var n,r,o;Qn(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=er(this,e.call.apply(e,[this].concat(a))),r.onHover=function(e){var t=r.props;(0,t.onHover)(e,t.index)},r.onClick=function(e){var t=r.props;(0,t.onClick)(e,t.index)},o=n,er(r,o)}return tr(t,e),t.prototype.getClassName=function(){var e=this.props,t=e.prefixCls,n=e.index,r=e.value,o=e.allowHalf,i=e.focused,a=n+1,s=t;return 0===r&&0===n&&i?s+=" "+t+"-focused":o&&r+.5===a?(s+=" "+t+"-half "+t+"-active",i&&(s+=" "+t+"-focused")):(s+=a<=r?" "+t+"-full":" "+t+"-zero",a===r&&i&&(s+=" "+t+"-focused")),s},t.prototype.render=function(){var e=this.onHover,t=this.onClick,n=this.props,r=n.disabled,o=n.prefixCls,i=n.character;return Zo.a.createElement("li",{className:this.getClassName(),onClick:r?null:t,onMouseMove:r?null:e},Zo.a.createElement("div",{className:o+"-first"},i),Zo.a.createElement("div",{className:o+"-second"},i))},t}(Zo.a.Component);Tf.propTypes={value:ni.a.number,index:ni.a.number,prefixCls:ni.a.string,allowHalf:ni.a.bool,disabled:ni.a.bool,onHover:ni.a.func,onClick:ni.a.func,character:ni.a.node,focused:ni.a.bool};var Nf=Tf,Pf=function(e){function t(n){nr(this,t);var r=rr(this,e.call(this,n));Mf.call(r);var o=n.value;return void 0===o&&(o=n.defaultValue),r.stars={},r.state={value:o,focused:!1,cleanedValue:null},r}return or(t,e),t.prototype.componentDidMount=function(){this.props.autoFocus&&!this.props.disabled&&this.focus()},t.prototype.componentWillReceiveProps=function(e){if("value"in e){var t=e.value;void 0===t&&(t=e.defaultValue),this.setState({value:t})}},t.prototype.getStarDOM=function(e){return ei.a.findDOMNode(this.stars[e])},t.prototype.getStarValue=function(e,t){var n=e+1;if(this.props.allowHalf){var r=this.getStarDOM(e);t-Zn(r)<r.clientWidth/2&&(n-=.5)}return n},t.prototype.focus=function(){this.props.disabled||this.rate.focus()},t.prototype.blur=function(){this.props.disabled||this.rate.focus()},t.prototype.changeValue=function(e){"value"in this.props||this.setState({value:e}),this.props.onChange(e)},t.prototype.render=function(){for(var e=this.props,t=e.count,n=e.allowHalf,r=e.style,o=e.prefixCls,i=e.disabled,a=e.className,s=e.character,l=e.tabIndex,u=this.state,c=u.value,p=u.hoverValue,f=u.focused,d=[],h=i?o+"-disabled":"",v=0;v<t;v++)d.push(Zo.a.createElement(Nf,{ref:this.saveRef(v),index:v,disabled:i,prefixCls:o+"-star",allowHalf:n,value:void 0===p?c:p,onClick:this.onClick,onHover:this.onHover,key:v,character:s,focused:f}));return Zo.a.createElement("ul",{className:ii()(o,h,a),style:r,onMouseLeave:i?null:this.onMouseLeave,tabIndex:i?-1:l,onFocus:i?null:this.onFocus,onBlur:i?null:this.onBlur,onKeyDown:i?null:this.onKeyDown,ref:this.saveRate},d)},t}(Zo.a.Component);Pf.propTypes={disabled:ni.a.bool,value:ni.a.number,defaultValue:ni.a.number,count:ni.a.number,allowHalf:ni.a.bool,allowClear:ni.a.bool,style:ni.a.object,prefixCls:ni.a.string,onChange:ni.a.func,onHoverChange:ni.a.func,className:ni.a.string,character:ni.a.node,tabIndex:ni.a.number,onFocus:ni.a.func,onBlur:ni.a.func,onKeyDown:ni.a.func,autoFocus:ni.a.bool},Pf.defaultProps={defaultValue:0,count:5,allowHalf:!1,allowClear:!0,style:{},prefixCls:"rc-rate",onChange:ir,character:"\u2605",onHoverChange:ir,tabIndex:0};var Mf=function(){var e=this;this.onHover=function(t,n){var r=e.getStarValue(n,t.pageX);r!==e.state.cleanedValue&&e.setState({hoverValue:r,cleanedValue:null}),e.props.onHoverChange(r)},this.onMouseLeave=function(){e.setState({hoverValue:void 0,cleanedValue:null}),e.props.onHoverChange(void 0)},this.onClick=function(t,n){var r=e.getStarValue(n,t.pageX),o=!1;e.props.allowClear&&(o=r===e.state.value),e.onMouseLeave(!0),e.changeValue(o?0:r),e.setState({cleanedValue:o?r:null})},this.onFocus=function(){var t=e.props.onFocus;e.setState({focused:!0}),t&&t()},this.onBlur=function(){var t=e.props.onBlur;e.setState({focused:!1}),t&&t()},this.onKeyDown=function(t){var n=t.keyCode,r=e.props,o=r.count,i=r.allowHalf,a=r.onKeyDown,s=e.state.value;n===$s.a.RIGHT&&s<o?(s+=i?.5:1,e.changeValue(s),t.preventDefault()):n===$s.a.LEFT&&s>0&&(s-=i?.5:1,e.changeValue(s),t.preventDefault()),a&&a(t)},this.saveRef=function(t){return function(n){e.stars[t]=n}},this.saveRate=function(t){e.rate=t}},Df=Pf,If=Df,Af=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveRate=function(t){e.rcRate=t},e}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.rcRate.focus()}},{key:"blur",value:function(){this.rcRate.blur()}},{key:"render",value:function(){return Jo.createElement(If,Vo()({ref:this.saveRate},this.props))}}]),t}(Jo.Component),jf=Af;Af.propTypes={prefixCls:ni.a.string,character:ni.a.node},Af.defaultProps={prefixCls:"ant-rate",character:Jo.createElement(Ni.a,{type:"star"})};var Rf=yl,Lf=function(e){var t=e.className,n=e.included,r=e.vertical,o=e.offset,i=e.length,a=e.style,s=r?{bottom:o+"%",height:i+"%"}:{left:o+"%",width:i+"%"},l=Vo()({},a,s);return n?Zo.a.createElement("div",{className:t,style:l}):null},Kf=Lf,Ff=function(e,t,n,r,o,i){ps()(!n||r>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var a=Object.keys(t).map(parseFloat);if(n)for(var s=o;s<=i;s+=r)a.indexOf(s)>=0||a.push(s);return a},Vf=function(e){var t=e.prefixCls,n=e.vertical,r=e.marks,o=e.dots,i=e.step,a=e.included,s=e.lowerBound,l=e.upperBound,u=e.max,c=e.min,p=e.dotStyle,f=e.activeDotStyle,d=u-c,h=Ff(0,r,o,i,c,u).map(function(e){var r,o=Math.abs(e-c)/d*100+"%",i=!a&&e===l||a&&e<=l&&e>=s,u=n?Vo()({bottom:o},p):Vo()({left:o},p);i&&(u=Vo()({},u,f));var h=ii()((r={},r[t+"-dot"]=!0,r[t+"-dot-active"]=i,r));return Zo.a.createElement("span",{className:h,style:u,key:e})});return Zo.a.createElement("div",{className:t+"-step"},h)},zf=Vf,Bf=function(e){var t=e.className,n=e.vertical,r=e.marks,o=e.included,i=e.upperBound,a=e.lowerBound,s=e.max,l=e.min,u=Object.keys(r),c=u.length,p=c>1?100/(c-1):100,f=.9*p,d=s-l,h=u.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var s,u=r[e],c="object"==typeof u&&!Zo.a.isValidElement(u),p=c?u.label:u;if(!p&&0!==p)return null;var h=!o&&e===i||o&&e<=i&&e>=a,v=ii()((s={},s[t+"-text"]=!0,s[t+"-text-active"]=h,s)),m={marginBottom:"-50%",bottom:(e-l)/d*100+"%"},y={width:f+"%",marginLeft:-f/2+"%",left:(e-l)/d*100+"%"},g=n?m:y,b=c?Vo()({},g,u.style):g;return Zo.a.createElement("span",{className:v,style:b,key:e},p)});return Zo.a.createElement("div",{className:t},h)},Wf=Bf,Hf=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.focus=function(){this.handle.focus()},t.prototype.blur=function(){this.handle.blur()},t.prototype.render=function(){var e=this,t=this.props,n=t.className,r=t.vertical,o=t.offset,i=t.style,a=t.disabled,s=t.min,l=t.max,u=t.value,c=t.tabIndex,p=$a()(t,["className","vertical","offset","style","disabled","min","max","value","tabIndex"]),f=r?{bottom:o+"%"}:{left:o+"%"},d=Vo()({},i,f),h={};return void 0!==u&&(h=Vo()({},h,{"aria-valuemin":s,"aria-valuemax":l,"aria-valuenow":u,"aria-disabled":!!a})),Zo.a.createElement("div",Vo()({ref:function(t){return e.handle=t},role:"slider",tabIndex:c||0},h,p,{className:n,style:d}))},t}(Zo.a.Component),Uf=Hf;Hf.propTypes={className:ni.a.string,vertical:ni.a.bool,offset:ni.a.number,style:ni.a.object,disabled:ni.a.bool,min:ni.a.number,max:ni.a.number,value:ni.a.number,tabIndex:ni.a.number};var qf=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));r.onEnd=function(){r.setState({dragging:!1}),r.removeDocumentEvents(),r.props.onAfterChange(r.getValue())};var o=void 0!==n.defaultValue?n.defaultValue:n.min,i=void 0!==n.value?n.value:o;return r.state={value:r.trimAlignValue(i),dragging:!1},r}return Go()(t,e),t.prototype.componentDidMount=function(){var e=this.props,t=e.autoFocus,n=e.disabled;t&&!n&&this.focus()},t.prototype.componentWillReceiveProps=function(e){if("value"in e||"min"in e||"max"in e){var t=this.state.value,n=void 0!==e.value?e.value:t,r=this.trimAlignValue(n,e);r!==t&&(this.setState({value:r}),sr(n,e)&&this.props.onChange(r))}},t.prototype.onChange=function(e){var t=this.props;!("value"in t)&&this.setState(e);var n=e.value;t.onChange(n)},t.prototype.onStart=function(e){this.setState({dragging:!0});var t=this.props,n=this.getValue();t.onBeforeChange(n);var r=this.calcValueByPos(e);this.startValue=r,this.startPosition=e,r!==n&&this.onChange({value:r})},t.prototype.onMove=function(e,t){mr(e);var n=this.state.value,r=this.calcValueByPos(t);r!==n&&this.onChange({value:r})},t.prototype.onKeyboard=function(e){var t=yr(e);if(t){mr(e);var n=this.state,r=n.value,o=t(r,this.props),i=this.trimAlignValue(o);if(i===r)return;this.onChange({value:i})}},t.prototype.getValue=function(){return this.state.value},t.prototype.getLowerBound=function(){return this.props.min},t.prototype.getUpperBound=function(){return this.state.value},t.prototype.trimAlignValue=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Vo()({},this.props,t);return vr(hr(e,n),n)},t.prototype.render=function(){var e=this,t=this.props,n=t.prefixCls,r=t.vertical,o=t.included,i=t.disabled,a=t.minimumTrackStyle,s=t.trackStyle,l=t.handleStyle,u=t.tabIndex,c=t.min,p=t.max,f=t.handle,d=this.state,h=d.value,v=d.dragging,m=this.calcOffset(h),y=f({className:n+"-handle",vertical:r,offset:m,value:h,dragging:v,disabled:i,min:c,max:p,index:0,tabIndex:u,style:l[0]||l,ref:function(t){return e.saveHandle(0,t)}}),g=s[0]||s;return{tracks:Zo.a.createElement(Kf,{className:n+"-track",vertical:r,included:o,offset:0,length:m,style:Vo()({},a,g)}),handles:y}},t}(Zo.a.Component);qf.propTypes={defaultValue:ni.a.number,value:ni.a.number,disabled:ni.a.bool,autoFocus:ni.a.bool,tabIndex:ni.a.number};var Yf=br(qf),Gf=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));r.onEnd=function(){r.setState({handle:null}),r.removeDocumentEvents(),r.props.onAfterChange(r.getValue())};var o=n.count,i=n.min,a=n.max,s=Array.apply(null,Array(o+1)).map(function(){return i}),l="defaultValue"in n?n.defaultValue:s,u=void 0!==n.value?n.value:l,c=u.map(function(e,t){return r.trimAlignValue(e,t)}),p=c[0]===a?0:c.length-1;return r.state={handle:null,recent:p,bounds:c},r}return Go()(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this;if(("value"in e||"min"in e||"max"in e)&&(this.props.min!==e.min||this.props.max!==e.max||!si()(this.props.value,e.value))){var n=this.state.bounds,r=e.value||n,o=r.map(function(n,r){return t.trimAlignValue(n,r,e)});o.length===n.length&&o.every(function(e,t){return e===n[t]})||(this.setState({bounds:o}),n.some(function(t){return sr(t,e)})&&this.props.onChange(o))}},t.prototype.onChange=function(e){var t=this.props;"value"in t?void 0!==e.handle&&this.setState({handle:e.handle}):this.setState(e);var n=Vo()({},this.state,e),r=n.bounds;t.onChange(r)},t.prototype.onStart=function(e){var t=this.props,n=this.state,r=this.getValue();t.onBeforeChange(r);var o=this.calcValueByPos(e);this.startValue=o,this.startPosition=e;var i=this.getClosestBound(o),a=this.getBoundNeedMoving(o,i);if(this.setState({handle:a,recent:a}),o!==r[a]){var s=[].concat(n.bounds);s[a]=o,this.onChange({bounds:s})}},t.prototype.onMove=function(e,t){mr(e);var n=this.props,r=this.state,o=this.calcValueByPos(t);if(o!==r.bounds[r.handle]){var i=[].concat(r.bounds);i[r.handle]=o;var a=r.handle;!1!==n.pushable?this.pushSurroundingHandles(i,a):n.allowCross&&(i.sort(function(e,t){return e-t}),a=i.indexOf(o)),this.onChange({handle:a,bounds:i})}},t.prototype.onKeyboard=function(){ps()(!0,"Keyboard support is not yet supported for ranges.")},t.prototype.getValue=function(){return this.state.bounds},t.prototype.getClosestBound=function(e){for(var t=this.state.bounds,n=0,r=1;r<t.length-1;++r)e>t[r]&&(n=r);return Math.abs(t[n+1]-e)<Math.abs(t[n]-e)&&(n+=1),n},t.prototype.getBoundNeedMoving=function(e,t){var n=this.state,r=n.bounds,o=n.recent,i=t,a=r[t+1]===r[t];return a&&r[o]===r[t]&&(i=o),a&&e!==r[t+1]&&(i=e<r[t+1]?t:t+1),i},t.prototype.getLowerBound=function(){return this.state.bounds[0]},t.prototype.getUpperBound=function(){var e=this.state.bounds;return e[e.length-1]},t.prototype.getPoints=function(){var e=this.props,t=e.marks,n=e.step,r=e.min,o=e.max,i=this._getPointsCache;if(!i||i.marks!==t||i.step!==n){var a=Vo()({},t);if(null!==n)for(var s=r;s<=o;s+=n)a[s]=s;var l=Object.keys(a).map(parseFloat);l.sort(function(e,t){return e-t}),this._getPointsCache={marks:t,step:n,points:l}}return this._getPointsCache.points},t.prototype.pushSurroundingHandles=function(e,t){var n=e[t],r=this.props.pushable;r=Number(r);var o=0;if(e[t+1]-n<r&&(o=1),n-e[t-1]<r&&(o=-1),0!==o){var i=t+o,a=o*(e[i]-n);this.pushHandle(e,i,o,r-a)||(e[t]=e[i]-o*r)}},t.prototype.pushHandle=function(e,t,n,r){for(var o=e[t],i=e[t];n*(i-o)<r;){if(!this.pushHandleOnePoint(e,t,n))return e[t]=o,!1;i=e[t]}return!0},t.prototype.pushHandleOnePoint=function(e,t,n){var r=this.getPoints(),o=r.indexOf(e[t]),i=o+n;if(i>=r.length||i<0)return!1;var a=t+n,s=r[i],l=this.props.pushable,u=n*(e[a]-s);return!!this.pushHandle(e,a,n,l-u)&&(e[t]=s,!0)},t.prototype.trimAlignValue=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=Vo()({},this.props,n),o=hr(e,r);return vr(this.ensureValueNotConflict(t,o,r),r)},t.prototype.ensureValueNotConflict=function(e,t,n){var r=n.allowCross,o=n.pushable,i=this.state||{},a=i.bounds;if(e=void 0===e?i.handle:e,o=Number(o),!r&&null!=e&&void 0!==a){if(e>0&&t<=a[e-1]+o)return a[e-1]+o;if(e<a.length-1&&t>=a[e+1]-o)return a[e+1]-o}return t},t.prototype.render=function(){var e=this,t=this.state,n=t.handle,r=t.bounds,o=this.props,i=o.prefixCls,a=o.vertical,s=o.included,l=o.disabled,u=o.min,c=o.max,p=o.handle,f=o.trackStyle,d=o.handleStyle,h=o.tabIndex,v=r.map(function(t){return e.calcOffset(t)}),m=i+"-handle",y=r.map(function(t,r){var o;return p({className:ii()((o={},o[m]=!0,o[m+"-"+(r+1)]=!0,o)),vertical:a,offset:v[r],value:t,dragging:n===r,index:r,tabIndex:h[r]||0,min:u,max:c,disabled:l,style:d[r],ref:function(t){return e.saveHandle(r,t)}})});return{tracks:r.slice(0,-1).map(function(e,t){var n,r=t+1,o=ii()((n={},n[i+"-track"]=!0,n[i+"-track-"+r]=!0,n));return Zo.a.createElement(Kf,{className:o,vertical:a,included:s,offset:v[r-1],length:v[r]-v[r-1],style:f[t],key:r})}),handles:y}},t}(Zo.a.Component);Gf.displayName="Range",Gf.propTypes={defaultValue:ni.a.arrayOf(ni.a.number),value:ni.a.arrayOf(ni.a.number),count:ni.a.number,pushable:ni.a.oneOfType([ni.a.bool,ni.a.number]),allowCross:ni.a.bool,disabled:ni.a.bool,tabIndex:ni.a.arrayOf(ni.a.number)},Gf.defaultProps={count:1,allowCross:!0,pushable:!1,tabIndex:[]};var Xf=br(Gf),$f=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Jf=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.toggleTooltipVisible=function(e,t){n.setState(function(n){var r=n.visibles;return{visibles:Vo()({},r,Ko()({},e,t))}})},n.handleWithTooltip=function(e){var t=e.value,r=e.dragging,o=e.index,i=$f(e,["value","dragging","index"]),a=n.props,s=a.tooltipPrefixCls,l=a.tipFormatter,u=n.state.visibles,c=!!l&&(u[o]||r);return Jo.createElement(cf.a,{prefixCls:s,title:l?l(t):"",visible:c,placement:"top",transitionName:"zoom-down",key:o},Jo.createElement(Uf,Vo()({},i,{value:t,onMouseEnter:function(){return n.toggleTooltipVisible(o,!0)},onMouseLeave:function(){return n.toggleTooltipVisible(o,!1)}})))},n.saveSlider=function(e){n.rcSlider=e},n.state={visibles:{}},n}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.rcSlider.focus()}},{key:"blur",value:function(){this.rcSlider.focus()}},{key:"render",value:function(){var e=this.props,t=e.range,n=$f(e,["range"]);return t?Jo.createElement(Xf,Vo()({},n,{ref:this.saveSlider,handle:this.handleWithTooltip})):Jo.createElement(Yf,Vo()({},n,{ref:this.saveSlider,handle:this.handleWithTooltip}))}}]),t}(Jo.Component),Zf=Jf;Jf.defaultProps={prefixCls:"ant-slider",tooltipPrefixCls:"ant-tooltip",tipFormatter:function(e){return e.toString()}};var Qf=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.calcStepOffsetWidth=function(){if(!Cr()){var e=Object(Qo.findDOMNode)(n);e.children.length>0&&(n.calcTimeout&&clearTimeout(n.calcTimeout),n.calcTimeout=setTimeout(function(){var t=(e.lastChild.offsetWidth||0)+1;n.state.lastStepOffsetWidth===t||Math.abs(n.state.lastStepOffsetWidth-t)<=3||n.setState({lastStepOffsetWidth:t})}))}},n.state={flexSupported:!0,lastStepOffsetWidth:0},n.calcStepOffsetWidth=ls()(n.calcStepOffsetWidth,150),n}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.calcStepOffsetWidth(),Cr()||this.setState({flexSupported:!1})}},{key:"componentDidUpdate",value:function(){this.calcStepOffsetWidth()}},{key:"componentWillUnmount",value:function(){this.calcTimeout&&clearTimeout(this.calcTimeout),this.calcStepOffsetWidth&&this.calcStepOffsetWidth.cancel&&this.calcStepOffsetWidth.cancel()}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=void 0===r?{}:r,i=t.className,a=t.children,s=t.direction,l=t.labelPlacement,u=t.iconPrefix,c=t.status,p=t.size,f=t.current,d=t.progressDot,h=$a()(t,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size","current","progressDot"]),v=this.state,m=v.lastStepOffsetWidth,y=v.flexSupported,g=Zo.a.Children.toArray(a).filter(function(e){return!!e}),b=g.length-1,C=d?"vertical":l,w=ii()(n,n+"-"+s,i,(e={},Ko()(e,n+"-"+p,p),Ko()(e,n+"-label-"+C,"horizontal"===s),Ko()(e,n+"-dot",!!d),e));return Zo.a.createElement("div",Vo()({className:w,style:o},h),Jo.Children.map(g,function(e,t){if(!e)return null;var r=Vo()({stepNumber:""+(t+1),prefixCls:n,iconPrefix:u,wrapperStyle:o,progressDot:d},e.props);return y||"vertical"===s||t===b||(r.itemWidth=100/b+"%",r.adjustMarginRight=-Math.round(m/b+1)),"error"===c&&t===f-1&&(r.className=n+"-next-error"),e.props.status||(r.status=t===f?c:t<f?"finish":"wait"),Object(Jo.cloneElement)(e,r)}))}}]),t}(Jo.Component);Qf.propTypes={prefixCls:ni.a.string,className:ni.a.string,iconPrefix:ni.a.string,direction:ni.a.string,labelPlacement:ni.a.string,children:ni.a.any,status:ni.a.string,size:ni.a.string,progressDot:ni.a.oneOfType([ni.a.bool,ni.a.func]),style:ni.a.object,current:ni.a.number},Qf.defaultProps={prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",current:0,status:"process",size:"",progressDot:!1};var ed=Qf,td=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"renderIconNode",value:function(){var e,t=this.props,n=t.prefixCls,r=t.progressDot,o=t.stepNumber,i=t.status,a=t.title,s=t.description,l=t.icon,u=t.iconPrefix,c=ii()(n+"-icon",u+"icon",(e={},Ko()(e,u+"icon-"+l,l&&wr(l)),Ko()(e,u+"icon-check",!l&&"finish"===i),Ko()(e,u+"icon-cross",!l&&"error"===i),e)),p=Zo.a.createElement("span",{className:n+"-icon-dot"});return r?"function"==typeof r?Zo.a.createElement("span",{className:n+"-icon"},r(p,{index:o-1,status:i,title:a,description:s})):Zo.a.createElement("span",{className:n+"-icon"},p):l&&!wr(l)?Zo.a.createElement("span",{className:n+"-icon"},l):l||"finish"===i||"error"===i?Zo.a.createElement("span",{className:c}):Zo.a.createElement("span",{className:n+"-icon"},o)}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.prefixCls,r=e.style,o=e.itemWidth,i=e.status,a=void 0===i?"wait":i,s=(e.iconPrefix,e.icon),l=(e.wrapperStyle,e.adjustMarginRight),u=(e.stepNumber,e.description),c=e.title,p=(e.progressDot,e.tailContent),f=$a()(e,["className","prefixCls","style","itemWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepNumber","description","title","progressDot","tailContent"]),d=ii()(n+"-item",n+"-item-"+a,t,Ko()({},n+"-item-custom",s)),h=Vo()({},r);return o&&(h.width=o),l&&(h.marginRight=l),Zo.a.createElement("div",Vo()({},f,{className:d,style:h}),Zo.a.createElement("div",{className:n+"-item-tail"},p),Zo.a.createElement("div",{className:n+"-item-icon"},this.renderIconNode()),Zo.a.createElement("div",{className:n+"-item-content"},Zo.a.createElement("div",{className:n+"-item-title"},c),u&&Zo.a.createElement("div",{className:n+"-item-description"},u)))}}]),t}(Zo.a.Component);td.propTypes={className:ni.a.string,prefixCls:ni.a.string,style:ni.a.object,wrapperStyle:ni.a.object,itemWidth:ni.a.oneOfType([ni.a.number,ni.a.string]),status:ni.a.string,iconPrefix:ni.a.string,icon:ni.a.node,adjustMarginRight:ni.a.oneOfType([ni.a.number,ni.a.string]),stepNumber:ni.a.string,description:ni.a.any,title:ni.a.any,progressDot:ni.a.oneOfType([ni.a.bool,ni.a.func]),tailContent:ni.a.any};var nd=td;ed.Step=nd;var rd=ed,od=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){return Jo.createElement(rd,this.props)}}]),t}(Jo.Component),id=od;od.Step=rd.Step,od.defaultProps={prefixCls:"ant-steps",iconPrefix:"ant",current:0},od.propTypes={prefixCls:ni.a.string,iconPrefix:ni.a.string,current:ni.a.number};var ad=n(368),sd=n.n(ad),ld=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveSwitch=function(t){e.rcSwitch=t},e}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.rcSwitch.focus()}},{key:"blur",value:function(){this.rcSwitch.blur()}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.loading,i=t.className,a=void 0===i?"":i,s=ii()(a,(e={},Ko()(e,n+"-small","small"===r),Ko()(e,n+"-loading",o),e));return Jo.createElement(sd.a,Vo()({},Object(li.a)(this.props,["loading"]),{className:s,ref:this.saveSwitch}))}}]),t}(Jo.Component),ud=ld;ld.defaultProps={prefixCls:"ant-switch"},ld.propTypes={prefixCls:ni.a.string,size:ni.a.oneOf(["small","default","large"]),className:ni.a.string};var cd=n(370),pd=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleChange=function(t){var n=e.props.onChange;n&&n(t)},e.handleClear=function(t){t.preventDefault();var n=e.props.handleClear;n&&n(t)},e}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.placeholder,n=e.value,r=e.prefixCls,o=n&&n.length>0?Jo.createElement("a",{href:"#",className:r+"-action",onClick:this.handleClear},Jo.createElement(Ni.a,{type:"cross-circle"})):Jo.createElement("span",{className:r+"-action"},Jo.createElement(Ni.a,{type:"search"}));return Jo.createElement("div",null,Jo.createElement(Vi,{placeholder:t,className:r,value:n,ref:"input",onChange:this.handleChange}),o)}}]),t}(Jo.Component),fd=pd;pd.defaultProps={placeholder:""};var dd=n(413),hd=n.n(dd),vd=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"shouldComponentUpdate",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return _c.a.shouldComponentUpdate.apply(this,t)}},{key:"render",value:function(){var e,t=this.props,n=t.renderedText,r=t.renderedEl,o=t.item,i=t.lazy,a=t.checked,s=t.prefixCls,l=t.onClick,u=ii()((e={},Ko()(e,s+"-content-item",!0),Ko()(e,s+"-content-item-disabled",o.disabled),e)),c=Jo.createElement("li",{className:u,title:n,onClick:o.disabled?void 0:function(){return l(o)}},Jo.createElement(cl.a,{checked:a,disabled:o.disabled}),Jo.createElement("span",null,r)),p=null;if(i){var f=Vo()({height:32,offset:500,throttle:0,debounce:!1},i);p=Jo.createElement(hd.a,f,c)}else p=c;return p}}]),t}(Jo.Component),md=vd,yd=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleSelect=function(e){var t=n.props.checkedKeys,r=t.some(function(t){return t===e.key});n.props.handleSelect(e,!r)},n.handleFilter=function(e){n.props.handleFilter(e),e.target.value&&(n.triggerScrollTimer=window.setTimeout(function(){var e=Qo.findDOMNode(n).querySelectorAll(".ant-transfer-list-content")[0];e&&Sr(e,"scroll")},0))},n.handleClear=function(){n.props.handleClear()},n.matchFilter=function(e,t){var r=n.props,o=r.filter,i=r.filterOption;return i?i(o,t):e.indexOf(o)>=0},n.renderItem=function(e){var t=n.props.render,r=void 0===t?xr:t,o=r(e),i=_r(o);return{renderedText:i?o.value:o,renderedEl:i?o.label:o}},n.state={mounted:!1},n}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){var e=this;this.timer=window.setTimeout(function(){e.setState({mounted:!0})},0)}},{key:"componentWillUnmount",value:function(){clearTimeout(this.timer),clearTimeout(this.triggerScrollTimer)}},{key:"shouldComponentUpdate",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return _c.a.shouldComponentUpdate.apply(this,t)}},{key:"getCheckStatus",value:function(e){var t=this.props.checkedKeys;return 0===t.length?"none":e.every(function(e){return t.indexOf(e.key)>=0})?"all":"part"}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.dataSource,o=t.titleText,i=t.checkedKeys,a=t.lazy,s=t.body,l=void 0===s?xr:s,u=t.footer,c=void 0===u?xr:u,p=t.showSearch,f=t.style,d=t.filter,h=t.searchPlaceholder,v=t.notFoundContent,m=t.itemUnit,y=t.itemsUnit,g=t.onScroll,b=c(Vo()({},this.props)),C=l(Vo()({},this.props)),w=ii()(n,Ko()({},n+"-with-footer",!!b)),S=[],x=[],_=r.map(function(t){var r=e.renderItem(t),o=r.renderedText,s=r.renderedEl;if(d&&d.trim()&&!e.matchFilter(o,t))return null;x.push(t),t.disabled||S.push(t);var l=i.indexOf(t.key)>=0;return Jo.createElement(md,{key:t.key,item:t,lazy:a,renderedText:o,renderedEl:s,checked:l,prefixCls:n,onClick:e.handleSelect})}),k=r.length>1?y:m,E=p?Jo.createElement("div",{className:n+"-body-search-wrapper"},Jo.createElement(fd,{prefixCls:n+"-search",onChange:this.handleFilter,handleClear:this.handleClear,placeholder:h,value:d})):null,O=C||Jo.createElement("div",{className:p?n+"-body "+n+"-body-with-search":n+"-body"},E,Jo.createElement(Ui.a,{component:"ul",componentProps:{onScroll:g},className:n+"-content",transitionName:this.state.mounted?n+"-content-item-highlight":"",transitionLeave:!1},_),Jo.createElement("div",{className:n+"-body-not-found"},v)),T=b?Jo.createElement("div",{className:n+"-footer"},b):null,N=this.getCheckStatus(S),P="all"===N,M=Jo.createElement(cl.a,{ref:"checkbox",checked:P,indeterminate:"part"===N,onChange:function(){return e.props.handleSelectAll(S,P)}});return Jo.createElement("div",{className:w,style:f},Jo.createElement("div",{className:n+"-header"},M,Jo.createElement("span",{className:n+"-header-selected"},Jo.createElement("span",null,(i.length>0?i.length+"/":"")+x.length," ",k),Jo.createElement("span",{className:n+"-header-title"},o))),O,T)}}]),t}(Jo.Component),gd=yd;yd.defaultProps={dataSource:[],titleText:"",showSearch:!1,render:xr,lazy:{}};var bd=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.moveToLeft,n=void 0===t?kr:t,r=e.moveToRight,o=void 0===r?kr:r,i=e.leftArrowText,a=void 0===i?"":i,s=e.rightArrowText,l=void 0===s?"":s,u=e.leftActive,c=e.rightActive,p=e.className;return Jo.createElement("div",{className:p},Jo.createElement(Pi.a,{type:"primary",size:"small",disabled:!u,onClick:n,icon:"left"},a),Jo.createElement(Pi.a,{type:"primary",size:"small",disabled:!c,onClick:o,icon:"right"},l))}}]),t}(Jo.Component),Cd=bd,wd=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.moveTo=function(e){var t=n.props,r=t.targetKeys,o=void 0===r?[]:r,i=t.dataSource,a=void 0===i?[]:i,s=t.onChange,l=n.state,u=l.sourceSelectedKeys,c=l.targetSelectedKeys,p="right"===e?u:c,f=p.filter(function(e){return!a.some(function(t){return!(e!==t.key||!t.disabled)})}),d="right"===e?f.concat(o):o.filter(function(e){return-1===f.indexOf(e)}),h="right"===e?"left":"right";n.setState(Ko()({},n.getSelectedKeysName(h),[])),n.handleSelectChange(h,[]),s&&s(d,e,f)},n.moveToLeft=function(){return n.moveTo("left")},n.moveToRight=function(){return n.moveTo("right")},n.handleSelectAll=function(e,t,r){var o=n.state[n.getSelectedKeysName(e)]||[],i=t.map(function(e){return e.key}),a=o.filter(function(e){return-1===i.indexOf(e)}),s=[].concat(ci()(o));i.forEach(function(e){-1===s.indexOf(e)&&s.push(e)});var l=r?a:s;n.handleSelectChange(e,l),n.props.selectedKeys||n.setState(Ko()({},n.getSelectedKeysName(e),l))},n.handleLeftSelectAll=function(e,t){return n.handleSelectAll("left",e,t)},n.handleRightSelectAll=function(e,t){return n.handleSelectAll("right",e,t)},n.handleFilter=function(e,t){n.setState(Ko()({},e+"Filter",t.target.value)),n.props.onSearchChange&&n.props.onSearchChange(e,t)},n.handleLeftFilter=function(e){return n.handleFilter("left",e)},n.handleRightFilter=function(e){return n.handleFilter("right",e)},n.handleClear=function(e){n.setState(Ko()({},e+"Filter",""))},n.handleLeftClear=function(){return n.handleClear("left")},n.handleRightClear=function(){return n.handleClear("right")},n.handleSelect=function(e,t,r){var o=n.state,i=o.sourceSelectedKeys,a=o.targetSelectedKeys,s=[].concat("left"===e?ci()(i):ci()(a)),l=s.indexOf(t.key);l>-1&&s.splice(l,1),r&&s.push(t.key),n.handleSelectChange(e,s),n.props.selectedKeys||n.setState(Ko()({},n.getSelectedKeysName(e),s))},n.handleLeftSelect=function(e,t){return n.handleSelect("left",e,t)},n.handleRightSelect=function(e,t){return n.handleSelect("right",e,t)},n.handleScroll=function(e,t){var r=n.props.onScroll;r&&r(e,t)},n.handleLeftScroll=function(e){return n.handleScroll("left",e)},n.handleRightScroll=function(e){return n.handleScroll("right",e)},n.renderTransfer=function(e){var t=n.props,r=t.prefixCls,o=void 0===r?"ant-transfer":r,i=t.className,a=t.operations,s=void 0===a?[]:a,l=t.showSearch,u=t.notFoundContent,c=t.searchPlaceholder,p=t.body,f=t.footer,d=t.listStyle,h=t.filterOption,v=t.render,m=t.lazy,y=n.state,g=y.leftFilter,b=y.rightFilter,C=y.sourceSelectedKeys,w=y.targetSelectedKeys,S=n.splitDataSource(n.props),x=S.leftDataSource,_=S.rightDataSource,k=w.length>0,E=C.length>0,O=ii()(i,o),T=n.getTitles(e);return Jo.createElement("div",{className:O},Jo.createElement(gd,{prefixCls:o+"-list",titleText:T[0],dataSource:x,filter:g,filterOption:h,style:d,checkedKeys:C,handleFilter:n.handleLeftFilter,handleClear:n.handleLeftClear,handleSelect:n.handleLeftSelect,handleSelectAll:n.handleLeftSelectAll,render:v,showSearch:l,searchPlaceholder:c||e.searchPlaceholder,notFoundContent:u||e.notFoundContent,itemUnit:e.itemUnit,itemsUnit:e.itemsUnit,body:p,footer:f,lazy:m,onScroll:n.handleLeftScroll}),Jo.createElement(Cd,{className:o+"-operation",rightActive:E,rightArrowText:s[0],moveToRight:n.moveToRight,leftActive:k,leftArrowText:s[1],moveToLeft:n.moveToLeft}),Jo.createElement(gd,{prefixCls:o+"-list",titleText:T[1],dataSource:_,filter:b,filterOption:h,style:d,checkedKeys:w,handleFilter:n.handleRightFilter,handleClear:n.handleRightClear,handleSelect:n.handleRightSelect,handleSelectAll:n.handleRightSelectAll,render:v,showSearch:l,searchPlaceholder:c||e.searchPlaceholder,notFoundContent:u||e.notFoundContent,itemUnit:e.itemUnit,itemsUnit:e.itemsUnit,body:p,footer:f,lazy:m,onScroll:n.handleRightScroll}))};var r=e.selectedKeys,o=void 0===r?[]:r,i=e.targetKeys,a=void 0===i?[]:i;return n.state={leftFilter:"",rightFilter:"",sourceSelectedKeys:o.filter(function(e){return-1===a.indexOf(e)}),targetSelectedKeys:o.filter(function(e){return a.indexOf(e)>-1})},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){var t=this.state,n=t.sourceSelectedKeys,r=t.targetSelectedKeys;if((e.targetKeys!==this.props.targetKeys||e.dataSource!==this.props.dataSource)&&(this.splitedDataSource=null,!e.selectedKeys)){var o=e.dataSource,i=e.targetKeys,a=void 0===i?[]:i,s=[],l=[];o.forEach(function(e){var t=e.key;n.includes(t)&&!a.includes(t)&&s.push(t),r.includes(t)&&a.includes(t)&&l.push(t)}),this.setState({sourceSelectedKeys:s,targetSelectedKeys:l})}if(e.selectedKeys){var u=e.targetKeys||[];this.setState({sourceSelectedKeys:e.selectedKeys.filter(function(e){return!u.includes(e)}),targetSelectedKeys:e.selectedKeys.filter(function(e){return u.includes(e)})})}}},{key:"splitDataSource",value:function(e){if(this.splitedDataSource)return this.splitedDataSource;var t=e.dataSource,n=e.rowKey,r=e.targetKeys,o=void 0===r?[]:r,i=[],a=new Array(o.length);return t.forEach(function(e){n&&(e.key=n(e));var t=o.indexOf(e.key);-1!==t?a[t]=e:i.push(e)}),this.splitedDataSource={leftDataSource:i,rightDataSource:a},this.splitedDataSource}},{key:"handleSelectChange",value:function(e,t){var n=this.state,r=n.sourceSelectedKeys,o=n.targetSelectedKeys,i=this.props.onSelectChange;i&&("left"===e?i(t,o):i(r,t))}},{key:"getTitles",value:function(e){var t=this.props;return t.titles?t.titles:e.titles}},{key:"getSelectedKeysName",value:function(e){return"left"===e?"sourceSelectedKeys":"targetSelectedKeys"}},{key:"render",value:function(){return Jo.createElement(La.a,{componentName:"Transfer",defaultLocale:np.a.Transfer},this.renderTransfer)}}]),t}(Jo.Component),Sd=wd;wd.List=gd,wd.Operation=Cd,wd.Search=fd,wd.defaultProps={dataSource:[],render:Er,showSearch:!1},wd.propTypes={prefixCls:ni.a.string,dataSource:ni.a.array,render:ni.a.func,targetKeys:ni.a.array,onChange:ni.a.func,height:ni.a.number,listStyle:ni.a.object,className:ni.a.string,titles:ni.a.array,operations:ni.a.array,showSearch:ni.a.bool,filterOption:ni.a.func,searchPlaceholder:ni.a.string,notFoundContent:ni.a.node,body:ni.a.func,footer:ni.a.func,rowKey:ni.a.func,lazy:ni.a.oneOfType([ni.a.object,ni.a.bool])};var xd={rcTree:ni.a.shape({selectable:ni.a.bool})},_d=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));kd.call(r);var o=r.calcCheckedKeys(n);return r.state={expandedKeys:r.calcExpandedKeys(n),checkedKeys:o.checkedKeys,halfCheckedKeys:o.halfCheckedKeys,selectedKeys:r.calcSelectedKeys(n),dragNodesKeys:"",dragOverNodeKey:"",dropNodeKey:""},r}return Go()(t,e),t.prototype.getChildContext=function(){return{rcTree:{selectable:this.props.selectable}}},t.prototype.componentWillReceiveProps=function(e){var t=this.props,n={},r=e.expandedKeys!==t.expandedKeys?this.calcExpandedKeys(e,!0):void 0;r&&(n.expandedKeys=r);var o=e.checkedKeys!==t.checkedKeys||t.loadData?this.calcCheckedKeys(e,!0):void 0;o&&(n.checkedKeys=o.checkedKeys,n.halfCheckedKeys=o.halfCheckedKeys);var i=e.selectedKeys!==t.selectedKeys?this.calcSelectedKeys(e,!0):void 0;i&&(n.selectedKeys=i),this.setState(n)},t.prototype.onDragStart=function(e,t){this.dragNode=t;var n={dragNodesKeys:this.getDragNodesKeys(t)},r=this.getExpandedKeys(t,!1);r&&(n.expandedKeys=r),this.setState(n),this.props.onDragStart({event:e,node:t})},t.prototype.onDragEnter=function(e,t){var n=this,r=this.calcDropPosition(e,t);if(this.dragNode.props.eventKey===t.props.eventKey&&0===r)return void this.setState({dragOverNodeKey:"",dropPosition:null});this.setState({dragOverNodeKey:t.props.eventKey,dropPosition:r}),this.delayedDragEnterLogic||(this.delayedDragEnterLogic={}),Object.keys(this.delayedDragEnterLogic).forEach(function(e){clearTimeout(n.delayedDragEnterLogic[e])}),this.delayedDragEnterLogic[t.props.pos]=setTimeout(function(){var r=n.getExpandedKeys(t,!0);r&&n.setState({expandedKeys:r}),n.props.onDragEnter({event:e,node:t,expandedKeys:r&&[].concat(r)||[].concat(n.state.expandedKeys)})},400)},t.prototype.onDragOver=function(e,t){this.props.onDragOver({event:e,node:t})},t.prototype.onDragLeave=function(e,t){this.props.onDragLeave({event:e,node:t})},t.prototype.onDrop=function(e,t){var n=this.state,r=t.props.eventKey;if(this.setState({dragOverNodeKey:"",dropNodeKey:r}),n.dragNodesKeys.indexOf(r)>-1)return void ps()(!1,"Can not drop to dragNode(include it's children node)");var o=t.props.pos.split("-"),i={event:e,node:t,dragNode:this.dragNode,dragNodesKeys:[].concat(n.dragNodesKeys),dropPosition:n.dropPosition+Number(o[o.length-1])};0!==n.dropPosition&&(i.dropToGap=!0),this.props.onDrop(i)},t.prototype.onDragEnd=function(e,t){this.setState({dragOverNodeKey:""}),this.props.onDragEnd({event:e,node:t})},t.prototype.onExpand=function(e){var t=this,n=this.props,r=this.state,o=!e.props.expanded,i=[].concat(r.expandedKeys),a=e.props.eventKey,s=i.indexOf(a);o&&-1===s?i.push(a):!o&&s>-1&&i.splice(s,1);var l="expandedKeys"in n;if(l||this.setState({expandedKeys:i}),n.onExpand(i,{node:e,expanded:o}),o&&n.loadData)return n.loadData(e).then(function(){l||t.setState({expandedKeys:i})})},t.prototype.onSelect=function(e){var t=this.props,n=this.state,r=e.props.eventKey,o=!e.props.selected,i=[].concat(n.selectedKeys);if(o)t.multiple?i.push(r):i=[r];else{var a=i.indexOf(r);i.splice(a,1)}var s=[];i.length&&Tr(t.children,function(e){-1!==i.indexOf(e.key)&&s.push(e)}),"selectedKeys"in t||this.setState({selectedKeys:i});var l={event:"select",selected:o,node:e,selectedNodes:s};t.onSelect(i,l)},t.prototype.onMouseEnter=function(e,t){this.props.onMouseEnter({event:e,node:t})},t.prototype.onMouseLeave=function(e,t){this.props.onMouseLeave({event:e,node:t})},t.prototype.onContextMenu=function(e,t){this.props.onRightClick&&(e.preventDefault(),this.props.onRightClick({event:e,node:t}))},t.prototype.getOpenTransitionName=function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n?t:e.prefixCls+"-open-"+n},t.prototype.getDragNodesKeys=function(e){var t=[];return Tr(e.props.children,function(n,r,o,i){Dr(e.props.pos,o)&&t.push(i)}),t.push(e.props.eventKey||e.props.pos),t},t.prototype.getExpandedKeys=function(e,t){var n=e.props.eventKey,r=this.state.expandedKeys,o=r.indexOf(n);if(!t&&o>-1){var i=[].concat(r);return i.splice(o,1),i}if(t&&-1===r.indexOf(n))return r.concat([n])},t.prototype.generateTreeNodesStates=function(e,t){var n=[],r={};return Tr(e,function(e,o,i,a,s,l){r[i]={node:e,key:a,checked:!1,halfChecked:!1,disabled:e.props.disabled,disableCheckbox:e.props.disableCheckbox,childrenPos:s,parentPos:l},-1!==t.indexOf(a)&&(r[i].checked=!0,n.push(i))}),n.forEach(function(e){Nr(r,e,!0)}),r},t.prototype.calcExpandedKeys=function(e,t){var n=e.expandedKeys||(t?void 0:e.defaultExpandedKeys);if(n){var r=!t&&e.defaultExpandAll;if(!r&&!e.autoExpandParent)return n;var o=[];e.autoExpandParent&&Tr(e.children,function(e,t,r,i){n.indexOf(i)>-1&&o.push(r)});var i={};Tr(e.children,function(t,n,a,s){if(r)i[s]=!0;else if(e.autoExpandParent){var l=o.some(function(e){return Dr(a,e)});l&&(i[s]=!0)}});var a=Object.keys(i);return a.length?a:n}},t.prototype.calcCheckedKeys=function(e,t){if(!e.checkable)return{checkedKeys:[],halfCheckedKeys:[]};var n=e.checkedKeys||(t&&!e.loadData?void 0:e.defaultCheckedKeys);if(n){if(Array.isArray(n)?n={checkedKeys:n,halfCheckedKeys:[]}:"object"==typeof n&&(n={checkedKeys:n.checked,halfCheckedKeys:n.halfChecked}),!e.checkStrictly){var r=n.checkedKeys||[];return Pr(this.generateTreeNodesStates(e.children,r))}return n}},t.prototype.calcSelectedKeys=function(e,t){var n=e.selectedKeys||(t?void 0:e.defaultSelectedKeys);if(n)return e.multiple?[].concat(n):n.length?[n[0]]:n},t.prototype.calcDropPosition=function(e,t){var n=Or(t.selectHandle).top,r=t.selectHandle.offsetHeight,o=e.pageY;return o>n+r-2?1:o<n+2?-1:0},t.prototype.renderTreeNode=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=this.state,o=this.props,i=n+"-"+t,a=e.key||i,s={root:this,eventKey:a,pos:i,loadData:o.loadData,prefixCls:o.prefixCls,showIcon:o.showIcon,draggable:o.draggable,dragOver:r.dragOverNodeKey===a&&0===r.dropPosition,dragOverGapTop:r.dragOverNodeKey===a&&-1===r.dropPosition,dragOverGapBottom:r.dragOverNodeKey===a&&1===r.dropPosition,expanded:-1!==r.expandedKeys.indexOf(a),selected:-1!==r.selectedKeys.indexOf(a),openTransitionName:this.getOpenTransitionName(),openAnimation:o.openAnimation,filterTreeNode:this.filterTreeNode};return o.checkable&&(s.checkable=o.checkable,s.checked=-1!==r.checkedKeys.indexOf(a),s.halfChecked=-1!==r.halfCheckedKeys.indexOf(a)),Zo.a.cloneElement(e,s)},t.prototype.render=function(){var e,t=this.props,n=ii()(t.prefixCls,t.className,(e={},e[t.prefixCls+"-show-line"]=t.showLine,e)),r={};return t.focusable&&(r.tabIndex="0",r.onKeyDown=this.onKeyDown),Zo.a.createElement("ul",Vo()({},r,{className:n,role:"tree-node",unselectable:"on"}),Zo.a.Children.map(t.children,this.renderTreeNode,this))},t}(Zo.a.Component);_d.propTypes={prefixCls:ni.a.string,children:ni.a.any,showLine:ni.a.bool,showIcon:ni.a.bool,selectable:ni.a.bool,multiple:ni.a.bool,checkable:ni.a.oneOfType([ni.a.bool,ni.a.node]),checkStrictly:ni.a.bool,draggable:ni.a.bool,autoExpandParent:ni.a.bool,defaultExpandAll:ni.a.bool,defaultExpandedKeys:ni.a.arrayOf(ni.a.string),expandedKeys:ni.a.arrayOf(ni.a.string),defaultCheckedKeys:ni.a.arrayOf(ni.a.string),checkedKeys:ni.a.oneOfType([ni.a.arrayOf(ni.a.string),ni.a.object]),defaultSelectedKeys:ni.a.arrayOf(ni.a.string),selectedKeys:ni.a.arrayOf(ni.a.string),onExpand:ni.a.func,onCheck:ni.a.func,onSelect:ni.a.func,loadData:ni.a.func,onMouseEnter:ni.a.func,onMouseLeave:ni.a.func,onRightClick:ni.a.func,onDragStart:ni.a.func,onDragEnter:ni.a.func,onDragOver:ni.a.func,onDragLeave:ni.a.func,onDrop:ni.a.func,onDragEnd:ni.a.func,filterTreeNode:ni.a.func,openTransitionName:ni.a.string,openAnimation:ni.a.oneOfType([ni.a.string,ni.a.object])},_d.childContextTypes=xd,_d.defaultProps={prefixCls:"rc-tree",showLine:!1,showIcon:!0,selectable:!0,multiple:!1,checkable:!1,checkStrictly:!1,draggable:!1,autoExpandParent:!0,defaultExpandAll:!1,defaultExpandedKeys:[],defaultCheckedKeys:[],defaultSelectedKeys:[],onExpand:Ir,onCheck:Ir,onSelect:Ir,onDragStart:Ir,onDragEnter:Ir,onDragOver:Ir,onDragLeave:Ir,onDrop:Ir,onDragEnd:Ir,onMouseEnter:Ir,onMouseLeave:Ir};var kd=function(){var e=this;this.onCheck=function(t){var n=e.props,r=e.state,o=!t.props.checked||t.props.halfChecked,i={event:"check",node:t,checked:o};if(n.checkStrictly){var a=t.props.eventKey,s=[].concat(r.checkedKeys),l=s.indexOf(a);o&&-1===l&&s.push(a),!o&&l>-1&&s.splice(l,1),i.checkedNodes=[],Tr(n.children,function(e){-1!==s.indexOf(e.key)&&i.checkedNodes.push(e)}),"checkedKeys"in n||e.setState({checkedKeys:s}),n.onCheck(Mr(s,r.halfCheckedKeys),i)}else{var u=e.generateTreeNodesStates(n.children,r.checkedKeys);u[t.props.pos].checked=o,u[t.props.pos].halfChecked=!1,Nr(u,t.props.pos,o);var c=Pr(u);i.checkedNodes=c.checkedNodes,i.checkedNodesPositions=c.checkedNodesPositions,i.halfCheckedKeys=c.halfCheckedKeys,"checkedKeys"in n||e.setState({checkedKeys:c.checkedKeys,halfCheckedKeys:c.halfCheckedKeys}),n.onCheck(c.checkedKeys,i)}},this.onKeyDown=function(e){e.preventDefault()},this.filterTreeNode=function(t){var n=e.props.filterTreeNode;return"function"==typeof n&&!t.props.disabled&&n.call(e,t)}},Ed=_d,Od=n(88),Td=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));return r.onCheck=function(){r.props.root.onCheck(r)},r.onMouseEnter=function(e){e.preventDefault(),r.props.root.onMouseEnter(e,r)},r.onMouseLeave=function(e){e.preventDefault(),r.props.root.onMouseLeave(e,r)},r.onContextMenu=function(e){r.props.root.onContextMenu(e,r)},r.onDragStart=function(e){e.stopPropagation(),r.setState({dragNodeHighlight:!0}),r.props.root.onDragStart(e,r);try{e.dataTransfer.setData("text/plain","")}catch(e){}},r.onDragEnter=function(e){e.preventDefault(),e.stopPropagation(),r.props.root.onDragEnter(e,r)},r.onDragOver=function(e){e.preventDefault(),e.stopPropagation(),r.props.root.onDragOver(e,r)},r.onDragLeave=function(e){e.stopPropagation(),r.props.root.onDragLeave(e,r)},r.onDrop=function(e){e.preventDefault(),e.stopPropagation(),r.setState({dragNodeHighlight:!1}),r.props.root.onDrop(e,r)},r.onDragEnd=function(e){e.stopPropagation(),r.setState({dragNodeHighlight:!1}),r.props.root.onDragEnd(e,r)},r.onExpand=function(){var e=r.props.root.onExpand(r);if(e&&"object"==typeof e){var t=function(e){r.setState({dataLoading:e})};t(!0),e.then(function(){t(!1)},function(){t(!1)})}},r.saveSelectHandle=function(e){r.selectHandle=e},r.state={dataLoading:!1,dragNodeHighlight:!1},r}return Go()(t,e),t.prototype.onSelect=function(){this.props.root.onSelect(this)},t.prototype.onKeyDown=function(e){e.preventDefault()},t.prototype.isSelectable=function(){var e=this.props,t=this.context;return"selectable"in e?e.selectable:t.rcTree.selectable},t.prototype.renderSwitcher=function(e,t){var n=e.prefixCls,r=ii()(n+"-switcher",n+"-switcher_"+t);return Zo.a.createElement("span",{className:r,onClick:this.onExpand})},t.prototype.renderCheckbox=function(e){var t,n=e.prefixCls,r=(t={},t[n+"-checkbox"]=!0,t);e.checked?r[n+"-checkbox-checked"]=!0:e.halfChecked&&(r[n+"-checkbox-indeterminate"]=!0);var o=null;return"boolean"!=typeof e.checkable&&(o=e.checkable),e.disabled||e.disableCheckbox?(r[n+"-checkbox-disabled"]=!0,Zo.a.createElement("span",{className:ii()(r)},o)):Zo.a.createElement("span",{className:ii()(r),onClick:this.onCheck},o)},t.prototype.renderChildren=function(e){var t=this.renderFirst;this.renderFirst=1;var n=!0;!t&&e.expanded&&(n=!1);var r=null;e.children&&(r=Object(Od.a)(e.children).filter(function(e){return!!e}));var o=r;if(r&&(Array.isArray(r)&&r.length&&r.every(function(e){return e.type&&e.type.isTreeNode})||r.type&&r.type.isTreeNode)){var i,a={};e.openTransitionName?a.transitionName=e.openTransitionName:"object"==typeof e.openAnimation&&(a.animation=Vo()({},e.openAnimation),n||delete a.animation.appear);var s=ii()(e.prefixCls+"-child-tree",(i={},i[e.prefixCls+"-child-tree-open"]=e.expanded,i));o=Zo.a.createElement(Ui.a,Vo()({},a,{showProp:"data-expanded",transitionAppear:n,component:""}),e.expanded?Zo.a.createElement("ul",{className:s,"data-expanded":e.expanded},Zo.a.Children.map(r,function(t,n){return e.root.renderTreeNode(t,n,e.pos)},e.root)):null)}return o},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.expanded?"open":"close",i=o,a=!0,s=n.title,l=this.renderChildren(n);l&&l!==n.children||(l=null,n.loadData&&!n.isLeaf||(a=!1,i="docu"));var u=(e={},e[r+"-iconEle"]=!0,e[r+"-icon_loading"]=this.state.dataLoading,e[r+"-icon__"+i]=!0,e),c={};n.draggable&&(c.onDragEnter=this.onDragEnter,c.onDragOver=this.onDragOver,c.onDragLeave=this.onDragLeave,c.onDrop=this.onDrop,c.onDragEnd=this.onDragEnd);var p="",f="";n.disabled?p=r+"-treenode-disabled":n.dragOver?f="drag-over":n.dragOverGapTop?f="drag-over-gap-top":n.dragOverGapBottom&&(f="drag-over-gap-bottom");var d=n.filterTreeNode(this)?"filter-node":"";return Zo.a.createElement("li",Vo()({},c,{className:ii()(n.className,p,f,d)}),a?this.renderSwitcher(n,o):function(){return Zo.a.createElement("span",{className:r+"-switcher "+r+"-switcher-noop"})}(),n.checkable?this.renderCheckbox(n):null,function(){var e=n.showIcon||n.loadData&&t.state.dataLoading?Zo.a.createElement("span",{className:ii()(u)}):null,a=Zo.a.createElement("span",{className:r+"-title"},s),l=r+"-node-content-wrapper",c={className:l+" "+l+"-"+(i===o?i:"normal"),onMouseEnter:t.onMouseEnter,onMouseLeave:t.onMouseLeave,onContextMenu:t.onContextMenu};return n.disabled||((n.selected||t.state.dragNodeHighlight)&&(c.className+=" "+r+"-node-selected"),c.onClick=function(e){t.isSelectable()?(e.preventDefault(),t.onSelect()):n.checkable&&!n.disableCheckbox&&(e.preventDefault(),t.onCheck())},n.draggable&&(c.className+=" draggable",c.draggable=!0,c["aria-grabbed"]=!0,c.onDragStart=t.onDragStart)),Zo.a.createElement("span",Vo()({ref:t.saveSelectHandle,title:"string"==typeof s?s:""},c),e,a)}(),l)},t}(Zo.a.Component);Td.propTypes={prefixCls:ni.a.string,disabled:ni.a.bool,disableCheckbox:ni.a.bool,expanded:ni.a.bool,isLeaf:ni.a.bool,root:ni.a.object,onSelect:ni.a.func},Td.contextTypes=xd,Td.defaultProps={title:"---"},Td.isTreeNode=1;var Nd=Td;Ed.TreeNode=Nd;var Pd=Ed,Md=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.checkable;return Jo.createElement(Pd,Vo()({},e,{className:n,checkable:r?Jo.createElement("span",{className:t+"-checkbox-inner"}):r}),this.props.children)}}]),t}(Jo.Component),Dd=Md;Md.TreeNode=Nd,Md.defaultProps={prefixCls:"ant-tree",checkable:!1,showIcon:!1,openAnimation:As.a};var Id=n(16),Ad=n.n(Id),jd={userSelect:"none",WebkitUserSelect:"none"},Rd={unselectable:"unselectable"},Ld={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},Kd=function(e){function t(){var n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,e.call.apply(e,[this].concat(a))),r.state={_expandedKeys:[],fireOnExpand:!1,dropdownWidth:null},r.onExpand=function(e){r.setState({_expandedKeys:e,fireOnExpand:!0},function(){r.trigger&&r.trigger.forcePopupAlign&&r.trigger.forcePopupAlign()})},r.highlightTreeNode=function(e){var t=r.props,n=e.props[Br(t.treeNodeFilterProp)];return"string"==typeof n&&(t.inputValue&&n.indexOf(t.inputValue)>-1)},r.filterTreeNode=function(e,t){if(!e)return!0;var n=r.props.filterTreeNode;return!n||!t.props.disabled&&n.call(r,e,t)},o=n,qo()(r,o)}return Go()(t,e),t.prototype.componentDidMount=function(){this.setDropdownWidth()},t.prototype.componentWillReceiveProps=function(e){e.inputValue&&e.inputValue!==this.props.inputValue&&this.setState({_expandedKeys:[],fireOnExpand:!1})},t.prototype.componentDidUpdate=function(){this.setDropdownWidth()},t.prototype.setDropdownWidth=function(){var e=ei.a.findDOMNode(this).offsetWidth;e!==this.state.dropdownWidth&&this.setState({dropdownWidth:e})},t.prototype.getPopupEleRefs=function(){return this.popupEle},t.prototype.getPopupDOMNode=function(){return this.trigger.getPopupDomNode()},t.prototype.getDropdownTransitionName=function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},t.prototype.getDropdownPrefixCls=function(){return this.props.prefixCls+"-dropdown"},t.prototype.processTreeNode=function(e){var t=this,n=[];this._expandedKeys=[],Yr(e,function(e,r,o){t.filterTreeNode(t.props.inputValue,e)&&(n.push(o),t._expandedKeys.push(e.key))});var r=[];n.forEach(function(e){e.split("-").reduce(function(e,t){var n=e+"-"+t;return r.indexOf(n)<0&&r.push(n),n})});var o=[];Yr(e,function(e,t,n){r.indexOf(n)>-1&&o.push({node:e,pos:n})});var i=Gr(o);return function e(t){return t.map(function(t){return t.children?Zo.a.cloneElement(t.node,{},e(t.children)):t.node})}(i)},t.prototype.renderTree=function(e,t,n,r){var o=this.props,i={multiple:r,prefixCls:o.prefixCls+"-tree",showIcon:o.treeIcon,showLine:o.treeLine,defaultExpandAll:o.treeDefaultExpandAll,defaultExpandedKeys:o.treeDefaultExpandedKeys,filterTreeNode:this.highlightTreeNode};return o.treeCheckable?(i.selectable=!1,i.checkable=o.treeCheckable,i.onCheck=o.onSelect,i.checkStrictly=o.treeCheckStrictly,o.inputValue?i.checkStrictly=!0:i._treeNodesStates=o._treeNodesStates,i.treeCheckStrictly&&t.length?i.checkedKeys={checked:e,halfChecked:t}:i.checkedKeys=e):(i.selectedKeys=e,i.onSelect=o.onSelect),i.defaultExpandAll||i.defaultExpandedKeys||o.loadData||(i.expandedKeys=e),i.autoExpandParent=!0,i.onExpand=this.onExpand,this._expandedKeys&&this._expandedKeys.length&&(i.expandedKeys=this._expandedKeys),this.state.fireOnExpand&&(i.expandedKeys=this.state._expandedKeys,i.autoExpandParent=!1),o.loadData&&(i.loadData=o.loadData),Zo.a.createElement(Pd,Vo()({ref:io(this,"popupEle")},i),n)},t.prototype.render=function(){var e,t=this.props,n=t.multiple,r=this.getDropdownPrefixCls(),o=(e={},e[t.dropdownClassName]=!!t.dropdownClassName,e[r+"--"+(n?"multiple":"single")]=1,e),i=t.visible,a=n||t.combobox||!t.showSearch?null:Zo.a.createElement("span",{className:r+"-search"},t.inputElement),s=void 0;t._cachetreeData&&this.treeNodes?s=this.treeNodes:(s=function e(t){return Object(Od.a)(t).map(function(t){return t?t&&t.props.children?Zo.a.createElement(Nd,Vo()({},t.props,{key:t.key}),e(t.props.children)):Zo.a.createElement(Nd,Vo()({},t.props,{key:t.key})):null})}(t.treeData||t.treeNodes),this.treeNodes=s),t.inputValue&&(s=this.processTreeNode(s));var l=[],u=[];Yr(s,function(e){t.value.some(function(t){return t.value===Ar(e)})&&l.push(e.key),t.halfCheckedValues&&t.halfCheckedValues.some(function(t){return t.value===Ar(e)})&&u.push(e.key)});var c=void 0;s.length||(t.notFoundContent?c=Zo.a.createElement("span",{className:t.prefixCls+"-not-found"},t.notFoundContent):a||(i=!1));var p=Zo.a.createElement("div",null,a,c||this.renderTree(l,u,s,n)),f=Vo()({},t.dropdownStyle),d=t.dropdownMatchSelectWidth?"width":"minWidth";return this.state.dropdownWidth&&(f[d]=this.state.dropdownWidth+"px"),Zo.a.createElement(Hs.a,{action:t.disabled?[]:["click"],ref:io(this,"trigger"),popupPlacement:"bottomLeft",builtinPlacements:Ld,popupAlign:t.dropdownPopupAlign,prefixCls:r,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:t.onDropdownVisibleChange,popup:p,popupVisible:i,getPopupContainer:t.getPopupContainer,popupClassName:ii()(o),popupStyle:f},this.props.children)},t}(Jo.Component);Kd.propTypes={dropdownMatchSelectWidth:ni.a.bool,dropdownPopupAlign:ni.a.object,visible:ni.a.bool,filterTreeNode:ni.a.any,treeNodes:ni.a.any,inputValue:ni.a.string,prefixCls:ni.a.string,popupClassName:ni.a.string,children:ni.a.any};var Fd=Kd,Vd=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t}(Zo.a.Component);Vd.propTypes={value:ni.a.string};var zd=Vd,Bd={className:ni.a.string,prefixCls:ni.a.string,multiple:ni.a.bool,filterTreeNode:ni.a.any,showSearch:ni.a.bool,disabled:ni.a.bool,showArrow:ni.a.bool,allowClear:ni.a.bool,defaultOpen:ni.a.bool,open:ni.a.bool,transitionName:ni.a.string,animation:ni.a.string,choiceTransitionName:ni.a.string,onClick:ni.a.func,onChange:ni.a.func,onSelect:ni.a.func,onDeselect:ni.a.func,onSearch:ni.a.func,searchPlaceholder:ni.a.string,placeholder:ni.a.any,inputValue:ni.a.any,value:so,defaultValue:so,label:ni.a.node,defaultLabel:ni.a.any,labelInValue:ni.a.bool,dropdownStyle:ni.a.object,drodownPopupAlign:ni.a.object,onDropdownVisibleChange:ni.a.func,maxTagTextLength:ni.a.number,showCheckedStrategy:ni.a.oneOf(["SHOW_ALL","SHOW_PARENT","SHOW_CHILD"]),treeCheckStrictly:ni.a.bool,treeIcon:ni.a.bool,treeLine:ni.a.bool,treeDefaultExpandAll:ni.a.bool,treeCheckable:ni.a.oneOfType([ni.a.bool,ni.a.node]),treeNodeLabelProp:ni.a.string,treeNodeFilterProp:ni.a.string,treeData:ni.a.array,treeDataSimpleMode:ni.a.oneOfType([ni.a.bool,ni.a.object]),loadData:ni.a.func},Wd=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));Hd.call(r);var o=[];o=Vr("value"in n?n.value:n.defaultValue),r.renderedTreeData=r.renderTreeData(),o=r.addLabelToValue(n,o),o=r.getValue(n,o,!n.inputValue||"__strict");var i=n.inputValue||"";return r.state={value:o,inputValue:i,open:n.open||n.defaultOpen,focused:!1},r}return Go()(t,e),t.prototype.componentDidMount=function(){var e=this.props,t=e.autoFocus,n=e.disabled;if(Lr(this.props)){var r=this.getInputDOMNode();r.value?(r.style.width="",r.style.width=this.inputMirrorInstance.clientWidth+"px"):r.style.width=""}t&&!n&&this.focus()},t.prototype.componentWillReceiveProps=function(e){if(this.renderedTreeData=this.renderTreeData(e),this._cacheTreeNodesStates="no"!==this._cacheTreeNodesStates&&this._savedValue&&e.value===this._savedValue,this.props.treeData===e.treeData&&this.props.children===e.children||(this._treeNodesStates=eo(this.renderedTreeData||e.children,this.state.value.map(function(e){return e.value}))),"value"in e){var t=Vr(e.value);t=this.addLabelToValue(e,t),t=this.getValue(e,t),this.setState({value:t})}e.inputValue!==this.props.inputValue&&this.setState({inputValue:e.inputValue}),"open"in e&&this.setState({open:e.open})},t.prototype.componentWillUpdate=function(e){this._savedValue&&e.value&&e.value!==this._savedValue&&e.value===this.props.value&&(this._cacheTreeNodesStates=!1,this.getValue(e,this.addLabelToValue(e,Vr(e.value))))},t.prototype.componentDidUpdate=function(){var e=this.state,t=this.props;if(e.open&&Lr(t)){var n=this.getInputDOMNode();n.value?(n.style.width="",n.style.width=this.inputMirrorInstance.clientWidth+"px"):n.style.width=""}},t.prototype.componentWillUnmount=function(){this.clearDelayTimer(),this.dropdownContainer&&(ei.a.unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},t.prototype.getLabelFromNode=function(e){return jr(e,this.props.treeNodeLabelProp)},t.prototype.getLabelFromProps=function(e,t){var n=this;if(void 0===t)return null;var r=null;return Yr(this.renderedTreeData||e.children,function(e){Ar(e)===t&&(r=n.getLabelFromNode(e))}),null===r?t:r},t.prototype.getDropdownContainer=function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},t.prototype.getSearchPlaceholderElement=function(e){var t=this.props,n=void 0;return n=Kr(t)?t.placeholder||t.searchPlaceholder:t.searchPlaceholder,n?Zo.a.createElement("span",{style:{display:e?"none":"block"},onClick:this.onPlaceholderClick,className:t.prefixCls+"-search__field__placeholder"},n):null},t.prototype.getInputElement=function(){var e=this.state.inputValue,t=this.props,n=t.prefixCls,r=t.disabled;return Zo.a.createElement("span",{className:n+"-search__field__wrap"},Zo.a.createElement("input",{ref:io(this,"inputInstance"),onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:e,disabled:r,className:n+"-search__field",role:"textbox"}),Zo.a.createElement("span",{ref:io(this,"inputMirrorInstance"),className:n+"-search__field__mirror"},e,"\xa0"),Lr(this.props)?null:this.getSearchPlaceholderElement(!!e))},t.prototype.getInputDOMNode=function(){return this.inputInstance},t.prototype.getPopupDOMNode=function(){return this.trigger.getPopupDOMNode()},t.prototype.getPopupComponentRefs=function(){return this.trigger.getPopupEleRefs()},t.prototype.getValue=function(e,t){var n=this,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=t,i="__strict"===r||r&&(this.state&&this.state.inputValue||this.props.inputValue!==e.inputValue);if(e.treeCheckable&&(e.treeCheckStrictly||i)&&(this.halfCheckedValues=[],o=[],t.forEach(function(e){e.halfChecked?n.halfCheckedValues.push(e):o.push(e)})),!e.treeCheckable||e.treeCheckable&&(e.treeCheckStrictly||i))return o;var a=void 0;this._cachetreeData&&this._cacheTreeNodesStates&&this._checkedNodes&&this.state&&!this.state.inputValue?this.checkedTreeNodes=a=this._checkedNodes:(this._treeNodesStates=eo(this.renderedTreeData||e.children,o.map(function(e){return e.value})),this.checkedTreeNodes=a=this._treeNodesStates.checkedNodes);var s=function(t){return t.map(function(t){return{value:Ar(t.node),label:jr(t.node,e.treeNodeLabelProp)}})},l=this.props,u=[];if("SHOW_ALL"===l.showCheckedStrategy)u=s(a);else if("SHOW_PARENT"===l.showCheckedStrategy){var c=Xr(a.map(function(e){return e.pos}));u=s(a.filter(function(e){return-1!==c.indexOf(e.pos)}))}else u=s(a.filter(function(e){return!e.node.props.children}));return u},t.prototype.getCheckedNodes=function(e,t){var n=e.checkedNodes;if(t.treeCheckStrictly||this.state.inputValue)return n;var r=e.checkedNodesPositions;if("SHOW_ALL"===t.showCheckedStrategy)n=n;else if("SHOW_PARENT"===t.showCheckedStrategy){var o=Xr(r.map(function(e){return e.pos}));n=r.filter(function(e){return-1!==o.indexOf(e.pos)}).map(function(e){return e.node})}else n=n.filter(function(e){return!e.props.children});return n},t.prototype.getDeselectedValue=function(e){var t=this.checkedTreeNodes,n=void 0;t.forEach(function(t){t.node.props.value===e&&(n=t.pos)});var r=[],o=[];t.forEach(function(e){Hr(e.pos,n)||Hr(n,e.pos)||(o.push(e),r.push(e.node.props.value))}),this.checkedTreeNodes=this._checkedNodes=o;var i=this.state.value.filter(function(e){return-1!==r.indexOf(e.value)});this.fireChange(i,{triggerValue:e,clear:!0})},t.prototype.setOpenState=function(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.clearDelayTimer();var o=this.props;this.props.onDropdownVisibleChange(e,{documentClickClose:r})&&this.setState({open:e},function(){if(t||e)if(e||Kr(o)){var r=n.getInputDOMNode();r&&document.activeElement!==r&&r.focus()}else n.selection&&n.selection.focus()})},t.prototype.clearSearchInput=function(){this.getInputDOMNode().focus(),"inputValue"in this.props||this.setState({inputValue:""})},t.prototype.addLabelToValue=function(e,t){var n=this,r=t;return this.isLabelInValue()?r.forEach(function(t,o){if("[object Object]"!==Object.prototype.toString.call(r[o]))return void(r[o]={value:"",label:""});t.label=t.label||n.getLabelFromProps(e,t.value)}):r=r.map(function(t){return{value:t,label:n.getLabelFromProps(e,t)}}),r},t.prototype.clearDelayTimer=function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},t.prototype.removeSelected=function(e){var t=this.props;if(!t.disabled){if(this._cacheTreeNodesStates="no",t.treeCheckable&&("SHOW_ALL"===t.showCheckedStrategy||"SHOW_PARENT"===t.showCheckedStrategy)&&!t.treeCheckStrictly&&!this.state.inputValue)return void this.getDeselectedValue(e);var n=void 0,r=this.state.value.filter(function(t){return t.value===e&&(n=t.label),t.value!==e});if(Lr(t)){var o=e;this.isLabelInValue()&&(o={value:e,label:n}),t.onDeselect(o)}t.treeCheckable&&this.checkedTreeNodes&&this.checkedTreeNodes.length&&(this.checkedTreeNodes=this._checkedNodes=this.checkedTreeNodes.filter(function(e){return r.some(function(t){return t.value===e.node.props.value})})),this.fireChange(r,{triggerValue:e,clear:!0})}},t.prototype.openIfHasChildren=function(){var e=this.props;(Zo.a.Children.count(e.children)||Fr(e))&&this.setOpenState(!0)},t.prototype.fireChange=function(e,t){var n=this,r=this.props,o=e.map(function(e){return e.value}),i=this.state.value.map(function(e){return e.value});if(o.length!==i.length||!o.every(function(e,t){return i[t]===e})){var a={preValue:[].concat(this.state.value)};t&&Ad()(a,t);var s=null,l=e;if(this.isLabelInValue()?this.halfCheckedValues&&this.halfCheckedValues.length&&this.halfCheckedValues.forEach(function(e){l.some(function(t){return t.value===e.value})||l.push(e)}):(s=e.map(function(e){return e.label}),l=l.map(function(e){return e.value})),r.treeCheckable&&a.clear){var u=this.renderedTreeData||r.children;a.allCheckedNodes=Gr(ro(o,u))}if(r.treeCheckable&&this.state.inputValue){var c=[].concat(this.state.value);if(a.checked)e.forEach(function(e){c.every(function(t){return t.value!==e.value})&&c.push(Vo()({},e))});else{var p=void 0;c.some(function(e,t){if(e.value===a.triggerValue)return p=t,!0})&&c.splice(p,1)}l=c,this.isLabelInValue()||(s=c.map(function(e){return e.label}),l=c.map(function(e){return e.value}))}this._savedValue=Lr(r)?l:l[0],r.onChange(this._savedValue,s,a),"value"in r||(this._cacheTreeNodesStates=!1,this.setState({value:this.getValue(r,Vr(this._savedValue).map(function(e,t){return n.isLabelInValue()?e:{value:e,label:s&&s[t]}}))}))}},t.prototype.isLabelInValue=function(){var e=this.props,t=e.treeCheckable,n=e.treeCheckStrictly,r=e.labelInValue;return!(!t||!n)||(r||!1)},t.prototype.focus=function(){Fr(this.props)?this.selection.focus():this.getInputDOMNode().focus()},t.prototype.blur=function(){Fr(this.props)?this.selection.blur():this.getInputDOMNode().blur()},t.prototype.renderTopControlNode=function(){var e=this,t=this.state.value,n=this.props,r=n.choiceTransitionName,o=n.prefixCls,i=n.maxTagTextLength;if(Fr(n)){var a=Zo.a.createElement("span",{key:"placeholder",className:o+"-selection__placeholder"},n.placeholder);return t.length&&(a=Zo.a.createElement("span",{key:"value",title:t[0].label,className:o+"-selection-selected-value"},t[0].label)),Zo.a.createElement("span",{className:o+"-selection__rendered"},a)}var s=[];Lr(n)&&(s=t.map(function(t){var n=t.label,r=n;return i&&"string"==typeof n&&n.length>i&&(n=n.slice(0,i)+"..."),Zo.a.createElement("li",Vo()({style:jd},Rd,{onMouseDown:zr,className:o+"-selection__choice",key:t.value,title:r}),Zo.a.createElement("span",{className:o+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.value)}),Zo.a.createElement("span",{className:o+"-selection__choice__content"},n))})),s.push(Zo.a.createElement("li",{className:o+"-search "+o+"-search--inline",key:"__input"},this.getInputElement()));var l=o+"-selection__rendered";return Lr(n)&&r?Zo.a.createElement(Ui.a,{className:l,component:"ul",transitionName:r,onLeave:this.onChoiceAnimationLeave},s):Zo.a.createElement("ul",{className:l},s)},t.prototype.renderTreeData=function(e){var t=e||this.props;if(t.treeData){if(e&&e.treeData===this.props.treeData&&this.renderedTreeData)return this._cachetreeData=!0,this.renderedTreeData;this._cachetreeData=!1;var n=[].concat(t.treeData);if(t.treeDataSimpleMode){var r={id:"id",pId:"pId",rootPId:null};"[object Object]"===Object.prototype.toString.call(t.treeDataSimpleMode)&&Ad()(r,t.treeDataSimpleMode),n=oo(n,r)}return co(n,void 0,this.props.treeCheckable)}},t.prototype.render=function(){var e,t=this.props,n=Lr(t),r=this.state,o=t.className,i=t.disabled,a=t.allowClear,s=t.prefixCls,l=this.renderTopControlNode(),u={};Kr(t)||(u={onKeyDown:this.onKeyDown,tabIndex:0});var c=(e={},e[o]=!!o,e[s]=1,e[s+"-open"]=r.open,e[s+"-focused"]=r.open||r.focused,e[s+"-disabled"]=i,e[s+"-enabled"]=!i,e[s+"-allow-clear"]=!!t.allowClear,e),p=Zo.a.createElement("span",{key:"clear",className:s+"-selection__clear",onClick:this.onClearSelection});return Zo.a.createElement(Fd,Vo()({},t,{treeNodes:t.children,treeData:this.renderedTreeData,_cachetreeData:this._cachetreeData,_treeNodesStates:this._treeNodesStates,halfCheckedValues:this.halfCheckedValues,multiple:n,disabled:i,visible:r.open,inputValue:r.inputValue,inputElement:this.getInputElement(),value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,getPopupContainer:t.getPopupContainer,onSelect:this.onSelect,ref:io(this,"trigger")}),Zo.a.createElement("span",{style:t.style,onClick:t.onClick,className:ii()(c),onBlur:t.onBlur,onFocus:t.onFocus},Zo.a.createElement("span",Vo()({ref:io(this,"selection"),key:"selection",className:s+"-selection\n "+s+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":r.open},u),l,a&&this.state.value.length&&this.state.value[0].value?p:null,n||!t.showArrow?null:Zo.a.createElement("span",{key:"arrow",className:s+"-arrow",style:{outline:"none"}},Zo.a.createElement("b",null)),n?this.getSearchPlaceholderElement(!!this.state.inputValue||this.state.value.length):null)))},t}(Jo.Component);Wd.propTypes=Bd,Wd.defaultProps={prefixCls:"rc-tree-select",filterTreeNode:uo,showSearch:!0,allowClear:!1,placeholder:"",searchPlaceholder:"",labelInValue:!1,onClick:lo,onChange:lo,onSelect:lo,onDeselect:lo,onSearch:lo,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},onDropdownVisibleChange:function(){return!0},notFoundContent:"Not Found",showCheckedStrategy:"SHOW_CHILD",treeCheckStrictly:!1,treeIcon:!1,treeLine:!1,treeDataSimpleMode:!1,treeDefaultExpandAll:!1,treeCheckable:!1,treeNodeFilterProp:"value",treeNodeLabelProp:"title"};var Hd=function(){var e=this;this.onInputChange=function(t){var n=t.target.value,r=e.props;e.setState({inputValue:n,open:!0}),r.treeCheckable&&!n&&e.setState({value:e.getValue(r,[].concat(e.state.value),!1)}),r.onSearch(n)},this.onDropdownVisibleChange=function(t){!t&&(document.activeElement,e.getInputDOMNode()),setTimeout(function(){e.setOpenState(t,void 0,!t)},10)},this.onKeyDown=function(t){if(!e.props.disabled){var n=t.keyCode;e.state.open&&!e.getInputDOMNode()?e.onInputKeyDown(t):n!==$s.a.ENTER&&n!==$s.a.DOWN||(e.setOpenState(!0),t.preventDefault())}},this.onInputKeyDown=function(t){var n=e.props;if(!n.disabled){var r=e.state,o=t.keyCode;if(!Lr(n)||t.target.value||o!==$s.a.BACKSPACE){if(o===$s.a.DOWN){if(!r.open)return e.openIfHasChildren(),t.preventDefault(),void t.stopPropagation()}else if(o===$s.a.ESC)return void(r.open&&(e.setOpenState(!1),t.preventDefault(),t.stopPropagation()))}else{var i=r.value.concat();if(i.length){var a=i.pop();e.removeSelected(e.isLabelInValue()?a:a.value)}}}},this.onSelect=function(t,n){var r=n.node,o=e.state.value,i=e.props,a=Ar(r),s=e.getLabelFromNode(r),l=i.treeCheckable&&"select"===n.event,u=a;if(e.isLabelInValue()&&(u={value:u,label:s}),!1!==n.selected||(e.onDeselect(n),l)){i.onSelect(u,r,n);var c="check"===n.event;if(Lr(i))if(e.clearSearchInput(),c)o=e.getCheckedNodes(n,i).map(function(t){return{value:Ar(t),label:e.getLabelFromNode(t)}});else{if(o.some(function(e){return e.value===a}))return;o=o.concat([{value:a,label:s}])}else{if(o.length&&o[0].value===a)return void e.setOpenState(!1);o=[{value:a,label:s}],e.setOpenState(!1)}var p={triggerValue:a,triggerNode:r};if(c){p.checked=n.checked,p.allCheckedNodes=i.treeCheckStrictly||e.state.inputValue?n.checkedNodes:Gr(n.checkedNodesPositions),e._checkedNodes=n.checkedNodesPositions;var f=e.trigger.popupEle;e._treeNodesStates=f.checkKeys}else p.selected=n.selected;e.fireChange(o,p),null===i.inputValue&&e.setState({inputValue:""})}},this.onDeselect=function(t){e.removeSelected(Ar(t.node)),Lr(e.props)?e.clearSearchInput():e.setOpenState(!1)},this.onPlaceholderClick=function(){e.getInputDOMNode().focus()},this.onClearSelection=function(t){var n=e.props,r=e.state;n.disabled||(t.stopPropagation(),e._cacheTreeNodesStates="no",e._checkedNodes=[],(r.inputValue||r.value.length)&&(e.setOpenState(!1),void 0===n.inputValue?e.setState({inputValue:""},function(){e.fireChange([])}):e.fireChange([])))},this.onChoiceAnimationLeave=function(){e.trigger.trigger.forcePopupAlign()}};Wd.SHOW_ALL="SHOW_ALL",Wd.SHOW_PARENT="SHOW_PARENT",Wd.SHOW_CHILD="SHOW_CHILD";var Ud=Wd;Ud.TreeNode=zd;var qd=Ud,Yd=(n(420),this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n}),Gd=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.saveTreeSelect=function(e){n.rcTreeSelect=e},n.renderTreeSelect=function(e){var t,r=n.props,o=r.prefixCls,i=r.className,a=r.size,s=r.notFoundContent,l=r.dropdownStyle,u=r.dropdownClassName,c=Yd(r,["prefixCls","className","size","notFoundContent","dropdownStyle","dropdownClassName"]),p=ii()((t={},Ko()(t,o+"-lg","large"===a),Ko()(t,o+"-sm","small"===a),t),i),f=c.treeCheckable;return f&&(f=Jo.createElement("span",{className:o+"-tree-checkbox-inner"})),Jo.createElement(qd,Vo()({},c,{dropdownClassName:ii()(u,o+"-tree-dropdown"),prefixCls:o,className:p,dropdownStyle:Vo()({maxHeight:"100vh",overflow:"auto"},l),treeCheckable:f,notFoundContent:s||e.notFoundContent,ref:n.saveTreeSelect}))},Object(aa.a)(!1!==e.multiple||!e.treeCheckable,"`multiple` will alway be `true` when `treeCheckable` is true"),n}return Go()(t,e),Ho()(t,[{key:"focus",value:function(){this.rcTreeSelect.focus()}},{key:"blur",value:function(){this.rcTreeSelect.blur()}},{key:"render",value:function(){return Jo.createElement(La.a,{componentName:"Select",defaultLocale:{}},this.renderTreeSelect)}}]),t}(Jo.Component),Xd=Gd;Gd.TreeNode=zd,Gd.SHOW_ALL="SHOW_ALL",Gd.SHOW_PARENT="SHOW_PARENT",Gd.SHOW_CHILD="SHOW_CHILD",Gd.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1};var $d=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Jd=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleClick=function(){var t=e.props,n=t.checked,r=t.onChange;r&&r(!n)},e}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=void 0===n?"ant-tag":n,o=t.className,i=t.checked,a=$d(t,["prefixCls","className","checked"]),s=ii()(r,(e={},Ko()(e,r+"-checkable",!0),Ko()(e,r+"-checkable-checked",i),e),o);return delete a.onChange,Jo.createElement("div",Vo()({},a,{className:s,onClick:this.handleClick}))}}]),t}(Jo.Component),Zd=Jd,Qd=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},eh=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.close=function(e){var t=n.props.onClose;if(t&&t(e),!e.defaultPrevented){var r=Qo.findDOMNode(n);r.style.width=r.getBoundingClientRect().width+"px",r.style.width=r.getBoundingClientRect().width+"px",n.setState({closing:!0})}},n.animationEnd=function(e,t){if(!t&&!n.state.closed){n.setState({closed:!0,closing:!1});var r=n.props.afterClose;r&&r()}},n.state={closing:!1,closed:!1},n}return Go()(t,e),Ho()(t,[{key:"isPresetColor",value:function(e){return!!e&&/^(pink|red|yellow|orange|cyan|green|blue|purple|geekblue|magenta|volcano|gold|lime)(-inverse)?$/.test(e)}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.closable,o=t.color,i=t.className,a=t.children,s=t.style,l=Qd(t,["prefixCls","closable","color","className","children","style"]),u=r?Jo.createElement(Ni.a,{type:"cross",onClick:this.close}):"",c=this.isPresetColor(o),p=ii()(n,(e={},Ko()(e,n+"-"+o,c),Ko()(e,n+"-has-color",o&&!c),Ko()(e,n+"-close",this.state.closing),e),i),f=Object(li.a)(l,["onClose","afterClose"]),d=Vo()({backgroundColor:o&&!c?o:null},s),h=this.state.closed?null:Jo.createElement("div",Vo()({"data-show":!this.state.closing},f,{className:p,style:d}),a,u);return Jo.createElement(Ui.a,{component:"",showProp:"data-show",transitionName:n+"-zoom",transitionAppear:!0,onEnd:this.animationEnd},h)}}]),t}(Jo.Component),th=eh;eh.CheckableTag=Zd,eh.defaultProps={prefixCls:"ant-tag",closable:!1};var nh=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},rh=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e,t,n=this.props,r=n.prefixCls,o=n.className,i=n.color,a=void 0===i?"":i,s=n.last,l=n.children,u=n.pending,c=n.dot,p=nh(n,["prefixCls","className","color","last","children","pending","dot"]),f=ii()((e={},Ko()(e,r+"-item",!0),Ko()(e,r+"-item-last",s),Ko()(e,r+"-item-pending",u),e),o),d=ii()((t={},Ko()(t,r+"-item-head",!0),Ko()(t,r+"-item-head-custom",c),Ko()(t,r+"-item-head-"+a,!0),t));return Jo.createElement("li",Vo()({},p,{className:f}),Jo.createElement("div",{className:r+"-item-tail"}),Jo.createElement("div",{className:d,style:{borderColor:/blue|red|green/.test(a)?null:a}},c),Jo.createElement("div",{className:r+"-item-content"},l))}}]),t}(Jo.Component),oh=rh;rh.defaultProps={prefixCls:"ant-timeline",color:"blue",last:!1,pending:!1};var ih=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},ah=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.children,r=e.pending,o=e.pendingDot,i=e.className,a=ih(e,["prefixCls","children","pending","pendingDot","className"]),s="boolean"==typeof r?null:r,l=ii()(t,Ko()({},t+"-pending",!!r),i),u=Jo.Children.toArray(n).filter(function(e){return!!e}),c=Jo.Children.map(u,function(e,t){return Jo.cloneElement(e,{last:t===Jo.Children.count(u)-1})}),p=r?Jo.createElement(oh,{pending:!!r,dot:o||Jo.createElement(Ni.a,{type:"loading"})},s):null;return Jo.createElement("ul",Vo()({},a,{className:l}),c,p)}}]),t}(Jo.Component),sh=ah;ah.Item=oh,ah.defaultProps={prefixCls:"ant-timeline"};var lh=sh,uh=n(44),ch=n(510),ph=ch.a.GetText,fh=ch.a.GetHTML,dh=ch.a.ToEditorState,hh=(ch.a,n(80)),vh=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.render=function(){var e=this.props;return Zo.a.createElement("div",e)},t}(Jo.Component),mh=vh,yh=!!Qo.createPortal,gh=function(e){function t(){return Bo()(this,t),qo()(this,e.apply(this,arguments))}return Go()(t,e),t.prototype.componentDidMount=function(){this.renderOrReady()},t.prototype.componentDidUpdate=function(){this.renderOrReady()},t.prototype.renderOrReady=function(){yh?this.props.renderReady():this.renderComponent()},t.prototype.renderComponent=function(){var e=this.props,t=e.children,n=e.container,r=e.renderReady;Object(Qo.unstable_renderSubtreeIntoContainer)(this,t,n,function(){r&&r.call(this)})},t.prototype.render=function(){if(yh){var e=this.props,t=e.children,n=e.container;return Object(Qo.createPortal)(t,n)}return null},t}(Zo.a.Component),bh=gh;gh.propTypes={children:ni.a.any,renderReady:ni.a.func,container:ni.a.any};var Ch=function(e){return!1!==e},wh=function(e){function t(){Bo()(this,t);var n=qo()(this,e.call(this));return n.onEditorStateChange=function(e){var t=n.props.store.getOffset();if(0===t.size)return n.closeDropDown(),e;var r=e.getSelection();if(!n.props.callbacks.getEditorState().getSelection().getHasFocus()&&r.getHasFocus())return e;var o=fo(e,r),i=o.word;if(!i)return n.closeDropDown(),e;var a=t.map(function(t){var n=t.offsetKey,o=Object(hh.decode)(n),a=o.blockKey,s=o.decoratorKey,l=o.leafKey;if(a!==r.anchorKey)return!1;var u=e.getBlockTree(a).getIn([s,"leaves",l]);if(!u)return!1;var c=u.get("start"),p=u.get("end");return!!i&&(c===p-1?r.anchorOffset>=c+1&&r.anchorOffset<=p&&n:r.anchorOffset>c+1&&r.anchorOffset<=p&&n)}),s=a.some(Ch);n.activeOffsetKey=a.find(Ch);var l=n.props.store.getTrigger(n.activeOffsetKey);if(!s||!r.getHasFocus())return n.closeDropDown(),e;var u=i.substring(l.length,i.length);return n.lastSearchValue===u&&n.lastTrigger===l||(n.lastSearchValue=u,n.lastTrigger=l,n.props.onSearchChange(u,l)),n.state.active||l&&-1===i.indexOf(l)||n.openDropDown(),e},n.onUpArrow=function(e){if(e.preventDefault(),n.props.suggestions.length>0){var t=n.state.focusedIndex-1;n.setState({focusedIndex:Math.max(t,0)})}},n.onBlur=function(e){e.preventDefault(),n.closeDropDown()},n.onDownArrow=function(e){e.preventDefault();var t=n.state.focusedIndex+1;n.setState({focusedIndex:t>=n.props.suggestions.length?0:t})},n.getContainer=function(){var e=document.createElement("div"),t=void 0;return n.props.getSuggestionContainer?(t=n.props.getSuggestionContainer(),e.style.position="relative"):t=document.body,t.appendChild(e),e},n.handleKeyBinding=function(e){return"split-block"===e},n.handleReturn=function(e){e.preventDefault();var t=n.props.suggestions[n.state.focusedIndex];return!!t&&(Zo.a.isValidElement(t)?n.onMentionSelect(t.props.value,t.props.data):n.onMentionSelect(t),n.lastSearchValue=null,n.lastTrigger=null,!0)},n.renderReady=function(){var e=n.dropdownContainer;if(e){var t=n.state.active,r=n.activeOffsetKey,o=n.props.store.getOffset(),i=o.get(r);if(t&&i){var a=n.props.placement,s=n.getPositionStyle(!0,i.position()),l=parseFloat(s.top)-window.scrollY-e.offsetHeight<0,u=(window.innerHeight||document.documentElement.clientHeight)-(parseFloat(s.top)-window.scrollY)-e.offsetHeight<0;"top"!==a||l||(s.top=(parseFloat(s.top)-e.offsetHeight||0)+"px"),"bottom"===a&&u&&!l&&(s.top=(parseFloat(s.top)-e.offsetHeight||0)+"px"),Object.keys(s).forEach(function(t){e.style[t]=s[t]})}n.focusItem&&Pu()(ei.a.findDOMNode(n.focusItem),e,{onlyScrollIfNeeded:!0})}},n.getNavigations=function(){var e=n.props,t=e.prefixCls,r=e.suggestions,o=n.state.focusedIndex;return r.length?Zo.a.Children.map(r,function(e,r){var i=r===o,a=i?function(e){n.focusItem=e}:null,s=ii()(t+"-dropdown-item",{focus:i});return Zo.a.isValidElement(e)?Zo.a.cloneElement(e,{className:s,onMouseDown:function(){return n.onMentionSelect(e.props.value,e.props.data)},ref:a}):Zo.a.createElement(mh,{ref:a,className:s,onMouseDown:function(){return n.onMentionSelect(e)}},e)},n):Zo.a.createElement("div",{className:t+"-dropdown-notfound "+t+"-dropdown-item"},n.props.notFoundContent)},n.state={isActive:!1,focusedIndex:0,container:!1},n}return Go()(t,e),t.prototype.componentDidMount=function(){this.props.callbacks.onChange=this.onEditorStateChange},t.prototype.componentWillReceiveProps=function(e){e.suggestions.length!==this.props.suggestions.length&&this.setState({focusedIndex:0})},t.prototype.onMentionSelect=function(e,t){var n=this.props.callbacks.getEditorState(),r=this.props,o=r.store,i=r.onSelect,a=o.getTrigger(this.activeOffsetKey);if(i&&i(e,t||e),this.props.noRedup){if(-1!==go(n.getCurrentContent(),a).indexOf(""+a+e))return console.warn("you have specified `noRedup` props but have duplicated mentions."),this.closeDropDown(),void this.props.callbacks.setEditorState(vo(n))}this.props.callbacks.setEditorState(ho(n,""+a+e,t,this.props.mode),!0),this.closeDropDown()},t.prototype.getPositionStyle=function(e,t){if(this.props.getSuggestionStyle)return this.props.getSuggestionStyle(e,t);var n=this.props.getSuggestionContainer?this.state.container:document.body,r=mo(n);return t?Vo()({position:"absolute",left:t.left-r.left+"px",top:t.top-r.top+"px"},this.props.style):{}},t.prototype.openDropDown=function(){this.props.callbacks.onUpArrow=this.onUpArrow,this.props.callbacks.handleReturn=this.handleReturn,this.props.callbacks.handleKeyBinding=this.handleKeyBinding,this.props.callbacks.onDownArrow=this.onDownArrow,this.props.callbacks.onBlur=this.onBlur,this.setState({active:!0,container:this.state.container||this.getContainer()})},t.prototype.closeDropDown=function(){this.props.callbacks.onUpArrow=null,this.props.callbacks.handleReturn=null,this.props.callbacks.handleKeyBinding=null,this.props.callbacks.onDownArrow=null,this.props.callbacks.onBlur=null,this.setState({active:!1})},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.className,i=n.placement,a=this.state,s=a.container,l=a.active,u=ii()(Vo()((e={},e[r+"-dropdown"]=!0,e[r+"-dropdown-placement-"+i]=!0,e),o)),c="top"===i?"slide-down":"slide-up",p=this.getNavigations();return s?Zo.a.createElement(bh,{renderReady:this.renderReady,container:s},Zo.a.createElement(Ui.a,{transitionName:c},l?Zo.a.createElement("div",{className:u,ref:function(e){t.dropdownContainer=e}},p):null)):null},t}(Zo.a.Component),Sh=wh;wh.propTypes={callbacks:ni.a.object,suggestions:ni.a.array,store:ni.a.object,onSearchChange:ni.a.func,prefixCls:ni.a.string,mode:ni.a.string,style:ni.a.object,onSelect:ni.a.func,getSuggestionContainer:ni.a.func,notFoundContent:ni.a.any,getSuggestionStyle:ni.a.func,className:ni.a.string,noRedup:ni.a.bool,placement:ni.a.string};var xh=function(e){function t(){var n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,e.call.apply(e,[this].concat(a))),r.matchDecorates=function(e){var t=e.callbacks,n=e.suggestionRegex,o=e.decoratedText,i=n.exec(o);r.trigger=i[2],r.updatePortalPosition(r.props),t.setEditorState(t.getEditorState())},o=n,qo()(r,o)}return Go()(t,e),t.prototype.componentWillMount=function(){this.matchDecorates(this.props)},t.prototype.componentWillReceiveProps=function(e){e.decoratedText!==this.props.decoratedText&&this.matchDecorates(e),this.updatePortalPosition(e)},t.prototype.componentWillUnmount=function(){var e=this.props,t=e.offsetKey;e.mentionStore.inActiveSuggestion({offsetKey:t})},t.prototype.updatePortalPosition=function(e){var t=this,n=e.offsetKey;e.mentionStore.updateSuggestion({offsetKey:n,trigger:this.trigger,position:function(){var e=t.searchPortal,n=mo(e);return{left:n.left,top:n.top,width:e.offsetWidth,height:e.offsetHeight}}})},t.prototype.render=function(){var e=this;return Zo.a.createElement("span",{ref:function(t){e.searchPortal=t},style:this.props.style},this.props.children)},t}(Zo.a.Component);xh.propTypes={offsetKey:ni.a.any,mentionStore:ni.a.object,decoratedText:ni.a.string,children:ni.a.any,callbacks:ni.a.any,suggestionRegex:ni.a.any};var _h=xh,kh=function(e){var t=e.children;return Zo.a.createElement("span",{style:{backgroundColor:"#e6f3ff"}},t)},Eh=kh,Oh=n(67),Th=Object(Oh.Map)(),Nh={offset:Object(Oh.Map)(),getOffset:function(){return Th},getTrigger:function(e){var t=Th.get(e);return t&&t.trigger},activeSuggestion:function(e){var t=e.offsetKey;Th=Th.set(t,{offsetKey:t})},inActiveSuggestion:function(e){var t=e.offsetKey;Th=Th.delete(t)},updateSuggestion:function(e){var t=e.offsetKey,n=e.position,r=e.trigger;Th=Th.set(t,{offsetKey:t,position:n,trigger:r})}},Ph=Nh,Mh=function(){function e(t,n){Bo()(this,e),this.contentState=t,this.options=n}return e.prototype.generate=function(){var e=Object(uh.convertToRaw)(this.contentState);return this.processContent(e)},e.prototype.processContent=function(e){var t=e.blocks,n=this.options.encode;return t.map(function(e){return n?bo(e.text):e.text}).join(n?"<br />\n":"\n")},e}(),Dh=function(e){var t=e.entityKey,n=e.tag,r=e.callbacks,o=r.getEditorState().getCurrentContent(),i=o.getEntity(t).getData();return Zo.a.createElement(n,Vo()({},e,{data:i}))},Ih=function(e){function t(n){Bo()(this,t);var r=qo()(this,e.call(this,n));return r.onEditorChange=function(e){var t=e.getSelection();r._decorator=e.getDecorator();var n=e.getCurrentContent();r.props.onChange?r.setState({selection:t},function(){r.props.onChange(n,Co(n))}):r.setState({editorState:e,selection:t})},r.onFocus=function(e){r.props.onFocus&&r.props.onFocus(e)},r.onBlur=function(e){r.props.onBlur&&r.props.onBlur(e)},r.reset=function(){r._editor.Reset()},r.mention=_o({prefix:r.getPrefix(n),tag:n.tag,mode:n.mode,mentionStyle:n.mentionStyle}),r.Suggestions=r.mention.Suggestions,r.plugins=[r.mention],r.state={suggestions:n.suggestions,value:n.value&&uh.EditorState.createWithContent(n.value,new uh.CompositeDecorator(r.mention.decorators)),selection:uh.SelectionState.createEmpty()},"string"==typeof n.defaultValue&&console.warn("The property `defaultValue` now allow `EditorState` only, see http://react-component.github.io/editor-mention/examples/defaultValue.html "),void 0!==n.value&&(r.controlledMode=!0),r}return Go()(t,e),t.prototype.componentWillReceiveProps=function(e){var t=e.suggestions,n=this.state.selection,r=e.value;r&&n&&(r=uh.EditorState.acceptSelection(uh.EditorState.createWithContent(r,this._decorator),n)),this.setState({suggestions:t,value:r})},t.prototype.getPrefix=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.props;return Array.isArray(e.prefix)?e.prefix:[e.prefix]},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.style,i=n.tag,a=n.multiLines,s=n.suggestionStyle,l=n.placeholder,u=n.defaultValue,c=n.className,p=n.notFoundContent,f=n.getSuggestionContainer,d=n.readOnly,h=n.disabled,v=n.placement,m=this.state.suggestions,y=this.Suggestions,g=ii()(c,(e={},e[r+"-wrapper"]=!0,e.readonly=d,e.disabled=h,e.multilines=a,e)),b=this.controlledMode?{value:this.state.value}:{},C=u&&uh.EditorState.createWithContent("string"==typeof u?uh.ContentState.createFromText(u):u,this._decorator);return Zo.a.createElement("div",{className:g,style:o,ref:function(e){return t._wrapper=e}},Zo.a.createElement(ch.a,Vo()({ref:function(e){return t._editor=e},prefixCls:r,style:o,multiLines:a,plugins:this.plugins,defaultValue:C,placeholder:l,onFocus:this.onFocus,onBlur:this.onBlur,onChange:this.onEditorChange},b,{readOnly:d||h}),Zo.a.createElement(y,{mode:i?"immutable":"mutable",prefix:this.getPrefix(),prefixCls:r,style:s,placement:v,notFoundContent:p,suggestions:m,getSuggestionContainer:f?function(){return f(t._wrapper)}:null,onSearchChange:this.props.onSearchChange,onSelect:this.props.onSelect,noRedup:this.props.noRedup})))},t}(Zo.a.Component);Ih.propTypes={value:ni.a.object,suggestions:ni.a.array,prefix:ni.a.oneOfType([ni.a.string,ni.a.arrayOf(ni.a.string)]),prefixCls:ni.a.string,tag:ni.a.element,style:ni.a.object,className:ni.a.string,onSearchChange:ni.a.func,onChange:ni.a.func,mode:ni.a.string,multiLines:ni.a.bool,suggestionStyle:ni.a.object,placeholder:ni.a.string,defaultValue:ni.a.object,notFoundContent:ni.a.any,position:ni.a.string,onFocus:ni.a.func,onBlur:ni.a.func,onSelect:ni.a.func,getSuggestionContainer:ni.a.func,noRedup:ni.a.bool,mentionStyle:ni.a.object,placement:ni.a.string},Ih.controlledMode=!1,Ih.defaultProps={prefixCls:"rc-editor-mention",prefix:"@",mode:"immutable",suggestions:[],multiLines:!1,className:"",suggestionStyle:{},notFoundContent:"\u65e0\u6cd5\u627e\u5230",position:"absolute",placement:"bottom",mentionStyle:{}};var Ah=Ih;Ah.Nav=mh,Ah.toString=Co,Ah.toEditorState=ko,Ah.getMentions=go;var jh=Ah,Rh=function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onSearchChange=function(e,t){return n.props.onSearchChange?n.props.onSearchChange(e,t):n.defaultSearchChange(e)},n.onChange=function(e){n.props.onChange&&n.props.onChange(e)},n.onFocus=function(e){n.setState({focus:!0}),n.props.onFocus&&n.props.onFocus(e)},n.onBlur=function(e){n.setState({focus:!1}),n.props.onBlur&&n.props.onBlur(e)},n.focus=function(){n.mentionEle._editor.focusEditor()},n.mentionRef=function(e){n.mentionEle=e},n.state={suggestions:e.suggestions,focus:!1},n}return Go()(t,e),Ho()(t,[{key:"componentWillReceiveProps",value:function(e){var t=e.suggestions;si()(t,this.props.suggestions)||this.setState({suggestions:t})}},{key:"defaultSearchChange",value:function(e){var t=e.toLowerCase(),n=(this.props.suggestions||[]).filter(function(e){return e.type&&e.type===mh?!e.props.value||-1!==e.props.value.toLowerCase().indexOf(t):-1!==e.toLowerCase().indexOf(t)});this.setState({suggestions:n})}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=void 0===n?"":n,o=t.prefixCls,i=t.loading,a=t.placement,s=this.state,l=s.suggestions,u=s.focus,c=ii()(r,(e={},Ko()(e,o+"-active",u),Ko()(e,o+"-placement-top","top"===a),e)),p=i?Jo.createElement(Ni.a,{type:"loading"}):this.props.notFoundContent;return Jo.createElement(jh,Vo()({},this.props,{className:c,ref:this.mentionRef,onSearchChange:this.onSearchChange,onChange:this.onChange,onFocus:this.onFocus,onBlur:this.onBlur,suggestions:l,notFoundContent:p}))}}]),t}(Jo.Component),Lh=Rh;Rh.getMentions=go,Rh.defaultProps={prefixCls:"ant-mention",notFoundContent:"\u65e0\u5339\u914d\u7ed3\u679c\uff0c\u8f7b\u6572\u7a7a\u683c\u5b8c\u6210\u8f93\u5165",loading:!1,multiLines:!1,placement:"bottom"},Rh.Nav=mh,Rh.toString=Co,Rh.toContentState=ko;var Kh=+new Date,Fh=0,Vh=function(e,t){if(e&&t){var n=Array.isArray(t)?t:t.split(","),r=e.name||"",o=e.type||"",i=o.replace(/\/.*$/,"");return n.some(function(e){var t=e.trim();return"."===t.charAt(0)?Po(r.toLowerCase(),t.toLowerCase()):/\/\*$/.test(t)?i===t.replace(/\/.*$/,""):o===t})}return!0},zh=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.state={uid:No()},r.reqs={},r.onChange=function(e){var t=e.target.files;r.uploadFiles(t),r.reset()},r.onClick=function(){var e=r.fileInput;e&&e.click()},r.onKeyDown=function(e){"Enter"===e.key&&r.onClick()},r.onFileDrop=function(e){if("dragover"===e.type)return void e.preventDefault();var t=Array.prototype.slice.call(e.dataTransfer.files).filter(function(e){return Vh(e,r.props.accept)});r.uploadFiles(t),e.preventDefault()},r.saveFileInput=function(e){r.fileInput=e},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this._isMounted=!0}},{key:"componentWillUnmount",value:function(){this._isMounted=!1,this.abort()}},{key:"uploadFiles",value:function(e){var t=this,n=Array.prototype.slice.call(e);n.forEach(function(e){e.uid=No(),t.upload(e,n)})}},{key:"upload",value:function(e,t){var n=this,r=this.props;if(!r.beforeUpload)return setTimeout(function(){return n.post(e)},0);var o=r.beforeUpload(e,t);o&&o.then?o.then(function(t){var r=Object.prototype.toString.call(t);"[object File]"===r||"[object Blob]"===r?n.post(t):n.post(e)}).catch(function(e){console&&console.log(e)}):!1!==o&&setTimeout(function(){return n.post(e)},0)}},{key:"post",value:function(e){var t=this;if(this._isMounted){var n=this.props,r=n.data,o=n.onStart,i=n.onProgress;"function"==typeof r&&(r=r(e));var a=e.uid,s=n.customRequest||To;this.reqs[a]=s({action:n.action,filename:n.name,file:e,data:r,headers:n.headers,withCredentials:n.withCredentials,onProgress:i?function(t){i(t,e)}:null,onSuccess:function(r,o){delete t.reqs[a],n.onSuccess(r,e,o)},onError:function(r,o){delete t.reqs[a],n.onError(r,o,e)}}),o(e)}}},{key:"reset",value:function(){this.setState({uid:No()})}},{key:"abort",value:function(e){var t=this.reqs;if(e){var n=e;e&&e.uid&&(n=e.uid),t[n]&&(t[n].abort(),delete t[n])}else Object.keys(t).forEach(function(e){t[e]&&t[e].abort(),delete t[e]})}},{key:"render",value:function(){var e,t=this.props,n=t.component,r=t.prefixCls,o=t.className,i=t.disabled,a=t.style,s=t.multiple,l=t.accept,u=t.children,c=ii()((e={},Ko()(e,r,!0),Ko()(e,r+"-disabled",i),Ko()(e,o,o),e)),p=i?{}:{onClick:this.onClick,onKeyDown:this.onKeyDown,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,tabIndex:"0"};return Zo.a.createElement(n,Vo()({},p,{className:c,role:"button",style:a}),Zo.a.createElement("input",{type:"file",ref:this.saveFileInput,key:this.state.uid,style:{display:"none"},accept:l,multiple:s,onChange:this.onChange}),u)}}]),t}(Jo.Component);zh.propTypes={component:ni.a.string,style:ni.a.object,prefixCls:ni.a.string,className:ni.a.string,multiple:ni.a.bool,disabled:ni.a.bool,accept:ni.a.string,children:ni.a.any,onStart:ni.a.func,data:ni.a.oneOfType([ni.a.object,ni.a.func]),headers:ni.a.object,beforeUpload:ni.a.func,customRequest:ni.a.func,onProgress:ni.a.func,withCredentials:ni.a.bool};var Bh=zh,Wh=n(530),Hh=n.n(Wh),Uh={position:"absolute",top:0,opacity:0,filter:"alpha(opacity=0)",left:0,zIndex:9999},qh=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.state={uploading:!1},r.file={},r.onLoad=function(){if(r.state.uploading){var e=r,t=e.props,n=e.file,o=void 0;try{var i=r.getIframeDocument(),a=i.getElementsByTagName("script")[0];a&&a.parentNode===i.body&&i.body.removeChild(a),o=i.body.innerHTML,t.onSuccess(o,n)}catch(e){Hh()(!1,"cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload"),o="cross-domain",t.onError(e,null,n)}r.endUpload()}},r.onChange=function(){var e=r.getFormInputNode(),t=r.file={uid:No(),name:e.value};r.startUpload();var n=r,o=n.props;if(!o.beforeUpload)return r.post(t);var i=o.beforeUpload(t);i&&i.then?i.then(function(){r.post(t)},function(){r.endUpload()}):!1!==i?r.post(t):r.endUpload()},r.saveIframe=function(e){r.iframe=e},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.updateIframeWH(),this.initIframe()}},{key:"componentDidUpdate",value:function(){this.updateIframeWH()}},{key:"getIframeNode",value:function(){return this.iframe}},{key:"getIframeDocument",value:function(){return this.getIframeNode().contentDocument}},{key:"getFormNode",value:function(){return this.getIframeDocument().getElementById("form")}},{key:"getFormInputNode",value:function(){return this.getIframeDocument().getElementById("input")}},{key:"getFormDataNode",value:function(){return this.getIframeDocument().getElementById("data")}},{key:"getFileForMultiple",value:function(e){return this.props.multiple?[e]:e}},{key:"getIframeHTML",value:function(e){var t="",n="";if(e){t='<script>document.domain="'+e+'";<\/script>',n='<input name="_documentDomain" value="'+e+'" />'}return'\n <!DOCTYPE html>\n <html>\n <head>\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <style>\n body,html {padding:0;margin:0;border:0;overflow:hidden;}\n </style>\n '+t+'\n </head>\n <body>\n <form method="post"\n encType="multipart/form-data"\n action="'+this.props.action+'" id="form"\n style="display:block;height:9999px;position:relative;overflow:hidden;">\n <input id="input" type="file"\n name="'+this.props.name+'"\n style="position:absolute;top:0;right:0;height:9999px;font-size:9999px;cursor:pointer;"/>\n '+n+'\n <span id="data"></span>\n </form>\n </body>\n </html>\n '}},{key:"initIframeSrc",value:function(){this.domain&&(this.getIframeNode().src="javascript:void((function(){\n var d = document;\n d.open();\n d.domain='"+this.domain+"';\n d.write('');\n d.close();\n })())")}},{key:"initIframe",value:function(){var e=this.getIframeNode(),t=e.contentWindow,n=void 0;this.domain=this.domain||"",this.initIframeSrc();try{n=t.document}catch(r){this.domain=document.domain,this.initIframeSrc(),t=e.contentWindow,n=t.document}n.open("text/html","replace"),n.write(this.getIframeHTML(this.domain)),n.close(),this.getFormInputNode().onchange=this.onChange}},{key:"endUpload",value:function(){this.state.uploading&&(this.file={},this.state.uploading=!1,this.setState({uploading:!1}),this.initIframe())}},{key:"startUpload",value:function(){this.state.uploading||(this.state.uploading=!0,this.setState({uploading:!0}))}},{key:"updateIframeWH",value:function(){var e=ei.a.findDOMNode(this),t=this.getIframeNode();t.style.height=e.offsetHeight+"px",t.style.width=e.offsetWidth+"px"}},{key:"abort",value:function(e){if(e){var t=e;e&&e.uid&&(t=e.uid),t===this.file.uid&&this.endUpload()}else this.endUpload()}},{key:"post",value:function(e){var t=this.getFormNode(),n=this.getFormDataNode(),r=this.props.data,o=this.props.onStart;"function"==typeof r&&(r=r(e));var i=document.createDocumentFragment();for(var a in r)if(r.hasOwnProperty(a)){var s=document.createElement("input");s.setAttribute("name",a),s.value=r[a],i.appendChild(s)}n.appendChild(i),t.submit(),n.innerHTML="",o(e)}},{key:"render",value:function(){var e,t=this.props,n=t.component,r=t.disabled,o=t.className,i=t.prefixCls,a=t.children,s=t.style,l=Vo()({},Uh,{display:this.state.uploading||r?"none":""}),u=ii()((e={},Ko()(e,i,!0),Ko()(e,i+"-disabled",r),Ko()(e,o,o),e));return Zo.a.createElement(n,{className:u,style:Vo()({position:"relative",zIndex:0},s)},Zo.a.createElement("iframe",{ref:this.saveIframe,onLoad:this.onLoad,style:l}),a)}}]),t}(Jo.Component);qh.propTypes={component:ni.a.string,style:ni.a.object,disabled:ni.a.bool,prefixCls:ni.a.string,className:ni.a.string,accept:ni.a.string,onStart:ni.a.func,multiple:ni.a.bool,children:ni.a.any,data:ni.a.oneOfType([ni.a.object,ni.a.func]),action:ni.a.string,name:ni.a.string};var Yh=qh,Gh=function(e){function t(){var e,n,r,o;Bo()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=qo()(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),r.state={Component:null},r.saveUploader=function(e){r.uploader=e},o=n,qo()(r,o)}return Go()(t,e),Ho()(t,[{key:"componentDidMount",value:function(){this.props.supportServerRender&&this.setState({Component:this.getComponent()},this.props.onReady)}},{key:"getComponent",value:function(){return"undefined"!=typeof File?Bh:Yh}},{key:"abort",value:function(e){this.uploader.abort(e)}},{key:"render",value:function(){if(this.props.supportServerRender){var e=this.state.Component;return e?Zo.a.createElement(e,Vo()({},this.props,{ref:this.saveUploader})):null}var t=this.getComponent();return Zo.a.createElement(t,Vo()({},this.props,{ref:this.saveUploader}))}}]),t}(Jo.Component);Gh.propTypes={component:ni.a.string,style:ni.a.object,prefixCls:ni.a.string,action:ni.a.string,name:ni.a.string,multipart:ni.a.bool,onError:ni.a.func,onSuccess:ni.a.func,onProgress:ni.a.func,onStart:ni.a.func,data:ni.a.oneOfType([ni.a.object,ni.a.func]),headers:ni.a.object,accept:ni.a.string,multiple:ni.a.bool,disabled:ni.a.bool,beforeUpload:ni.a.func,customRequest:ni.a.func,onReady:ni.a.func,withCredentials:ni.a.bool,supportServerRender:ni.a.bool},Gh.defaultProps={component:"span",prefixCls:"rc-upload",data:{},headers:{},name:"file",multipart:!1,onReady:Mo,onStart:Mo,onError:Mo,onSuccess:Mo,supportServerRender:!1,multiple:!1,beforeUpload:null,customRequest:null,withCredentials:!1};var Xh=Gh,$h=Xh,Jh=n(531),Zh=n.n(Jh),Qh=function(e,t){var n=new FileReader;n.onloadend=function(){return t(n.result)},n.readAsDataURL(e)},ev=function(e){return/^data:image\//.test(e)||/\.(webp|svg|png|gif|jpg|jpeg)$/.test(e)},tv=function(e){function t(){Bo()(this,t);var e=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleClose=function(t){var n=e.props.onRemove;n&&n(t)},e.handlePreview=function(t,n){var r=e.props.onPreview;if(r)return n.preventDefault(),r(t)},e}return Go()(t,e),Ho()(t,[{key:"componentDidUpdate",value:function(){var e=this;"picture"!==this.props.listType&&"picture-card"!==this.props.listType||(this.props.items||[]).forEach(function(t){"undefined"!=typeof document&&"undefined"!=typeof window&&window.FileReader&&window.File&&t.originFileObj instanceof File&&void 0===t.thumbUrl&&(t.thumbUrl="",Qh(t.originFileObj,function(n){t.thumbUrl=n,e.forceUpdate()}))})}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.items,i=void 0===o?[]:o,a=n.listType,s=n.showPreviewIcon,l=n.showRemoveIcon,u=n.locale,c=i.map(function(e){var n,o=void 0,i=Jo.createElement(Ni.a,{type:"uploading"===e.status?"loading":"paper-clip"});if("picture"===a||"picture-card"===a)if("picture-card"===a&&"uploading"===e.status)i=Jo.createElement("div",{className:r+"-list-item-uploading-text"},u.uploading);else if(e.thumbUrl||e.url){var c=ev(e.thumbUrl||e.url)?Jo.createElement("img",{src:e.thumbUrl||e.url,alt:e.name}):Jo.createElement(Ni.a,{type:"file",style:{fontSize:48,color:"rgba(0,0,0,0.5)"}});i=Jo.createElement("a",{className:r+"-list-item-thumbnail",onClick:function(n){return t.handlePreview(e,n)},href:e.url||e.thumbUrl,target:"_blank",rel:"noopener noreferrer"},c)}else i=Jo.createElement(Ni.a,{className:r+"-list-item-thumbnail",type:"picture"});if("uploading"===e.status){var p="percent"in e?Jo.createElement(Of,Vo()({type:"line"},t.props.progressAttr,{percent:e.percent})):null;o=Jo.createElement("div",{className:r+"-list-item-progress",key:"progress"},p)}var f=ii()((n={},Ko()(n,r+"-list-item",!0),Ko()(n,r+"-list-item-"+e.status,!0),n)),d=e.url?Jo.createElement("a",Vo()({},e.linkProps,{href:e.url,target:"_blank",rel:"noopener noreferrer",className:r+"-list-item-name",onClick:function(n){return t.handlePreview(e,n)},title:e.name}),e.name):Jo.createElement("span",{className:r+"-list-item-name",onClick:function(n){return t.handlePreview(e,n)},title:e.name},e.name),h=e.url||e.thumbUrl?void 0:{pointerEvents:"none",opacity:.5},v=s?Jo.createElement("a",{href:e.url||e.thumbUrl,target:"_blank",rel:"noopener noreferrer",style:h,onClick:function(n){return t.handlePreview(e,n)},title:u.previewFile},Jo.createElement(Ni.a,{type:"eye-o"})):null,m=l?Jo.createElement(Ni.a,{type:"delete",title:u.removeFile,onClick:function(){return t.handleClose(e)}}):null,y=l?Jo.createElement(Ni.a,{type:"cross",title:u.removeFile,onClick:function(){return t.handleClose(e)}}):null,g="picture-card"===a&&"uploading"!==e.status?Jo.createElement("span",{className:r+"-list-item-actions"},v,m):y,b=void 0;b=e.response&&"string"==typeof e.response?e.response:e.error&&e.error.statusText||u.uploadError;var C="error"===e.status?Jo.createElement(cf.a,{title:b},i,d):Jo.createElement("span",null,i,d);return Jo.createElement("div",{className:f,key:e.uid},Jo.createElement("div",{className:r+"-list-item-info"},C),g,Jo.createElement(Ui.a,{transitionName:"fade",component:""},o))}),p=ii()((e={},Ko()(e,r+"-list",!0),Ko()(e,r+"-list-"+a,!0),e)),f="picture-card"===a?"animate-inline":"animate";return Jo.createElement(Ui.a,{transitionName:r+"-"+f,component:"div",className:p},c)}}]),t}(Jo.Component),nv=tv;tv.defaultProps={listType:"text",progressAttr:{strokeWidth:2,showInfo:!1},prefixCls:"ant-upload",showRemoveIcon:!0,showPreviewIcon:!0};var rv=(n(244),function(e){function t(e){Bo()(this,t);var n=qo()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onStart=function(e){var t=void 0,r=n.state.fileList.concat();t=Io(e),t.status="uploading",r.push(t),n.onChange({file:t,fileList:r}),window.FormData||n.autoUpdateProgress(0,t)},n.onSuccess=function(e,t){n.clearProgressTimer();try{"string"==typeof e&&(e=JSON.parse(e))}catch(e){}var r=n.state.fileList,o=jo(t,r);o&&(o.status="done",o.response=e,n.onChange({file:Vo()({},o),fileList:r}))},n.onProgress=function(e,t){var r=n.state.fileList,o=jo(t,r);o&&(o.percent=e.percent,n.onChange({event:e,file:Vo()({},o),fileList:n.state.fileList}))},n.onError=function(e,t,r){n.clearProgressTimer();var o=n.state.fileList,i=jo(r,o);i&&(i.error=e,i.response=t,i.status="error",n.onChange({file:Vo()({},i),fileList:o}))},n.handleManualRemove=function(e){n.upload.abort(e),e.status="removed",n.handleRemove(e)},n.onChange=function(e){"fileList"in n.props||n.setState({fileList:e.fileList});var t=n.props.onChange;t&&t(e)},n.onFileDrop=function(e){n.setState({dragState:e.type})},n.beforeUpload=function(e,t){if(!n.props.beforeUpload)return!0;var r=n.props.beforeUpload(e,t);return!1===r?(n.onChange({file:e,fileList:Zh()(t.concat(n.state.fileList),function(e){return e.uid})}),!1):!r||!r.then||r},n.saveUpload=function(e){n.upload=e},n.renderUploadList=function(e){var t=n.props,r=t.showUploadList,o=t.listType,i=t.onPreview,a=r.showRemoveIcon,s=r.showPreviewIcon;return Jo.createElement(nv,{listType:o,items:n.state.fileList,onPreview:i,onRemove:n.handleManualRemove,showRemoveIcon:a,showPreviewIcon:s,locale:Vo()({},e,n.props.locale)})},n.state={fileList:e.fileList||e.defaultFileList||[],dragState:"drop"},n}return Go()(t,e),Ho()(t,[{key:"componentWillUnmount",value:function(){this.clearProgressTimer()}},{key:"autoUpdateProgress",value:function(e,t){var n=this,r=Ao(),o=0;this.clearProgressTimer(),this.progressTimer=setInterval(function(){o=r(o),n.onProgress({percent:o},t)},200)}},{key:"handleRemove",value:function(e){var t=this,n=this.props.onRemove;Promise.resolve("function"==typeof n?n(e):n).then(function(n){if(!1!==n){var r=Ro(e,t.state.fileList);r&&t.onChange({file:e,fileList:r})}})}},{key:"componentWillReceiveProps",value:function(e){"fileList"in e&&this.setState({fileList:e.fileList||[]})}},{key:"clearProgressTimer",value:function(){clearInterval(this.progressTimer)}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=void 0===n?"":n,o=t.className,i=t.showUploadList,a=t.listType,s=t.type,l=t.disabled,u=t.children,c=Vo()({onStart:this.onStart,onError:this.onError,onProgress:this.onProgress,onSuccess:this.onSuccess},this.props,{beforeUpload:this.beforeUpload});delete c.className;var p=i?Jo.createElement(La.a,{componentName:"Upload",defaultLocale:np.a.Upload},this.renderUploadList):null;if("drag"===s){var f,d=ii()(r,(f={},Ko()(f,r+"-drag",!0),Ko()(f,r+"-drag-uploading",this.state.fileList.some(function(e){return"uploading"===e.status})),Ko()(f,r+"-drag-hover","dragover"===this.state.dragState),Ko()(f,r+"-disabled",l),f));return Jo.createElement("span",{className:o},Jo.createElement("div",{className:d,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,onDragLeave:this.onFileDrop},Jo.createElement($h,Vo()({},c,{ref:this.saveUpload,className:r+"-btn"}),Jo.createElement("div",{className:r+"-drag-container"},u))),p)}var h=ii()(r,(e={},Ko()(e,r+"-select",!0),Ko()(e,r+"-select-"+a,!0),Ko()(e,r+"-disabled",l),e)),v=Jo.createElement("div",{className:h,style:{display:u?"":"none"}},Jo.createElement($h,Vo()({},c,{ref:this.saveUpload})));return"picture-card"===a?Jo.createElement("span",{className:o},p,v):Jo.createElement("span",{className:o},v,p)}}]),t}(Jo.Component)),ov=rv;rv.defaultProps={prefixCls:"ant-upload",type:"select",multiple:!1,action:"",data:{},accept:"",beforeUpload:Do,showUploadList:!0,listType:"text",className:"",disabled:!1,supportServerRender:!0};var iv=function(e){function t(){return Bo()(this,t),qo()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return Go()(t,e),Ho()(t,[{key:"render",value:function(){var e=this.props;return Jo.createElement(ov,Vo()({},e,{type:"drag",style:Vo()({},e.style,{height:e.height})}))}}]),t}(Jo.Component),av=iv;ov.Dragger=av;var sv=ov,lv=n(563),uv=lv.version;n.d(t,"Affix",function(){return vi}),n.d(t,"Anchor",function(){return Si}),n.d(t,"AutoComplete",function(){return Hi}),n.d(t,"Alert",function(){return Yi}),n.d(t,"Avatar",function(){return $i}),n.d(t,"BackTop",function(){return ea}),n.d(t,"Badge",function(){return ia}),n.d(t,"Breadcrumb",function(){return fa}),n.d(t,"Button",function(){return Pi.a}),n.d(t,"Calendar",function(){return Ha}),n.d(t,"Card",function(){return ws}),n.d(t,"Collapse",function(){return Fs}),n.d(t,"Carousel",function(){return Ws}),n.d(t,"Cascader",function(){return ul}),n.d(t,"Checkbox",function(){return cl.a}),n.d(t,"Col",function(){return xl}),n.d(t,"DatePicker",function(){return Eu}),n.d(t,"Divider",function(){return Nt}),n.d(t,"Dropdown",function(){return Tu.a}),n.d(t,"Form",function(){return Nc}),n.d(t,"Icon",function(){return Ni.a}),n.d(t,"Input",function(){return Vi}),n.d(t,"InputNumber",function(){return Vc}),n.d(t,"Layout",function(){return tp}),n.d(t,"List",function(){return fp}),n.d(t,"LocaleProvider",function(){return vp}),n.d(t,"message",function(){return Pp}),n.d(t,"Menu",function(){return Mp.a}),n.d(t,"Modal",function(){return Qp}),n.d(t,"notification",function(){return uf}),n.d(t,"Pagination",function(){return op.a}),n.d(t,"Popconfirm",function(){return df}),n.d(t,"Popover",function(){return vf}),n.d(t,"Progress",function(){return Of}),n.d(t,"Radio",function(){return Ka.default}),n.d(t,"Rate",function(){return jf}),n.d(t,"Row",function(){return Rf}),n.d(t,"Select",function(){return _i.a}),n.d(t,"Slider",function(){return Zf}),n.d(t,"Spin",function(){return rp.a}),n.d(t,"Steps",function(){return id}),n.d(t,"Switch",function(){return ud}),n.d(t,"Table",function(){return cd.default}),n.d(t,"Transfer",function(){return Sd}),n.d(t,"Tree",function(){return Dd}),n.d(t,"TreeSelect",function(){return Xd}),n.d(t,"Tabs",function(){return ys}),n.d(t,"Tag",function(){return th}),n.d(t,"TimePicker",function(){return hu}),n.d(t,"Timeline",function(){return lh}),n.d(t,"Tooltip",function(){return cf.a}),n.d(t,"Mention",function(){return Lh}),n.d(t,"Upload",function(){return sv}),n.d(t,"version",function(){return uv})},function(e,t,n){n(254);var r=n(29).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){var r=n(47);r(r.S+r.F*!n(49),"Object",{defineProperty:n(41).f})},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){e.exports={default:n(257),__esModule:!0}},function(e,t,n){n(258),e.exports=n(29).Object.assign},function(e,t,n){var r=n(47);r(r.S+r.F,"Object",{assign:n(259)})},function(e,t,n){"use strict";var r=n(82),o=n(110),i=n(84),a=n(111),s=n(169),l=Object.assign;e.exports=!l||n(68)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=l({},e)[n]||Object.keys(l({},t)).join("")!=r})?function(e,t){for(var n=a(e),l=arguments.length,u=1,c=o.f,p=i.f;l>u;)for(var f,d=s(arguments[u++]),h=c?r(d).concat(c(d)):r(d),v=h.length,m=0;v>m;)p.call(d,f=h[m++])&&(n[f]=d[f]);return n}:l},function(e,t,n){var r=n(58),o=n(170),i=n(261);e.exports=function(e){return function(t,n,a){var s,l=r(t),u=o(l.length),c=i(a,u);if(e&&n!=n){for(;u>c;)if((s=l[c++])!=s)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){var r=n(106),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t,n){e.exports={default:n(263),__esModule:!0}},function(e,t,n){n(85),n(115),e.exports=n(116).f("iterator")},function(e,t,n){var r=n(106),o=n(105);e.exports=function(e){return function(t,n){var i,a,s=String(o(t)),l=r(n),u=s.length;return l<0||l>=u?e?"":void 0:(i=s.charCodeAt(l),i<55296||i>56319||l+1===u||(a=s.charCodeAt(l+1))<56320||a>57343?e?s.charAt(l):i:e?s.slice(l,l+2):a-56320+(i-55296<<10)+65536)}}},function(e,t,n){"use strict";var r=n(113),o=n(69),i=n(114),a={};n(56)(a,n(30)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(41),o=n(48),i=n(82);e.exports=n(49)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),s=a.length,l=0;s>l;)r.f(e,n=a[l++],t[n]);return e}},function(e,t,n){var r=n(40).document;e.exports=r&&r.documentElement},function(e,t,n){var r=n(50),o=n(111),i=n(107)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){"use strict";var r=n(270),o=n(271),i=n(59),a=n(58);e.exports=n(171)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){e.exports={default:n(273),__esModule:!0}},function(e,t,n){n(274),n(279),n(280),n(281),e.exports=n(29).Symbol},function(e,t,n){"use strict";var r=n(40),o=n(50),i=n(49),a=n(47),s=n(172),l=n(275).KEY,u=n(68),c=n(108),p=n(114),f=n(83),d=n(30),h=n(116),v=n(117),m=n(276),y=n(277),g=n(48),b=n(57),C=n(58),w=n(103),S=n(69),x=n(113),_=n(278),k=n(174),E=n(41),O=n(82),T=k.f,N=E.f,P=_.f,M=r.Symbol,D=r.JSON,I=D&&D.stringify,A=d("_hidden"),j=d("toPrimitive"),R={}.propertyIsEnumerable,L=c("symbol-registry"),K=c("symbols"),F=c("op-symbols"),V=Object.prototype,z="function"==typeof M,B=r.QObject,W=!B||!B.prototype||!B.prototype.findChild,H=i&&u(function(){return 7!=x(N({},"a",{get:function(){return N(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=T(V,t);r&&delete V[t],N(e,t,n),r&&e!==V&&N(V,t,r)}:N,U=function(e){var t=K[e]=x(M.prototype);return t._k=e,t},q=z&&"symbol"==typeof M.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof M},Y=function(e,t,n){return e===V&&Y(F,t,n),g(e),t=w(t,!0),g(n),o(K,t)?(n.enumerable?(o(e,A)&&e[A][t]&&(e[A][t]=!1),n=x(n,{enumerable:S(0,!1)})):(o(e,A)||N(e,A,S(1,{})),e[A][t]=!0),H(e,t,n)):N(e,t,n)},G=function(e,t){g(e);for(var n,r=m(t=C(t)),o=0,i=r.length;i>o;)Y(e,n=r[o++],t[n]);return e},X=function(e,t){return void 0===t?x(e):G(x(e),t)},$=function(e){var t=R.call(this,e=w(e,!0));return!(this===V&&o(K,e)&&!o(F,e))&&(!(t||!o(this,e)||!o(K,e)||o(this,A)&&this[A][e])||t)},J=function(e,t){if(e=C(e),t=w(t,!0),e!==V||!o(K,t)||o(F,t)){var n=T(e,t);return!n||!o(K,t)||o(e,A)&&e[A][t]||(n.enumerable=!0),n}},Z=function(e){for(var t,n=P(C(e)),r=[],i=0;n.length>i;)o(K,t=n[i++])||t==A||t==l||r.push(t);return r},Q=function(e){for(var t,n=e===V,r=P(n?F:C(e)),i=[],a=0;r.length>a;)!o(K,t=r[a++])||n&&!o(V,t)||i.push(K[t]);return i};z||(M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var e=f(arguments.length>0?arguments[0]:void 0),t=function(n){this===V&&t.call(F,n),o(this,A)&&o(this[A],e)&&(this[A][e]=!1),H(this,e,S(1,n))};return i&&W&&H(V,e,{configurable:!0,set:t}),U(e)},s(M.prototype,"toString",function(){return this._k}),k.f=J,E.f=Y,n(173).f=_.f=Z,n(84).f=$,n(110).f=Q,i&&!n(112)&&s(V,"propertyIsEnumerable",$,!0),h.f=function(e){return U(d(e))}),a(a.G+a.W+a.F*!z,{Symbol:M});for(var ee="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),te=0;ee.length>te;)d(ee[te++]);for(var ne=O(d.store),re=0;ne.length>re;)v(ne[re++]);a(a.S+a.F*!z,"Symbol",{for:function(e){return o(L,e+="")?L[e]:L[e]=M(e)},keyFor:function(e){if(!q(e))throw TypeError(e+" is not a symbol!");for(var t in L)if(L[t]===e)return t},useSetter:function(){W=!0},useSimple:function(){W=!1}}),a(a.S+a.F*!z,"Object",{create:X,defineProperty:Y,defineProperties:G,getOwnPropertyDescriptor:J,getOwnPropertyNames:Z,getOwnPropertySymbols:Q}),D&&a(a.S+a.F*(!z||u(function(){var e=M();return"[null]"!=I([e])||"{}"!=I({a:e})||"{}"!=I(Object(e))})),"JSON",{stringify:function(e){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);if(n=t=r[1],(b(t)||void 0!==e)&&!q(e))return y(t)||(t=function(e,t){if("function"==typeof n&&(t=n.call(this,e,t)),!q(t))return t}),r[1]=t,I.apply(D,r)}}),M.prototype[j]||n(56)(M.prototype,j,M.prototype.valueOf),p(M,"Symbol"),p(Math,"Math",!0),p(r.JSON,"JSON",!0)},function(e,t,n){var r=n(83)("meta"),o=n(57),i=n(50),a=n(41).f,s=0,l=Object.isExtensible||function(){return!0},u=!n(68)(function(){return l(Object.preventExtensions({}))}),c=function(e){a(e,r,{value:{i:"O"+ ++s,w:{}}})},p=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!l(e))return"F";if(!t)return"E";c(e)}return e[r].i},f=function(e,t){if(!i(e,r)){if(!l(e))return!0;if(!t)return!1;c(e)}return e[r].w},d=function(e){return u&&h.NEED&&l(e)&&!i(e,r)&&c(e),e},h=e.exports={KEY:r,NEED:!1,fastKey:p,getWeak:f,onFreeze:d}},function(e,t,n){var r=n(82),o=n(110),i=n(84);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var a,s=n(e),l=i.f,u=0;s.length>u;)l.call(e,a=s[u++])&&t.push(a);return t}},function(e,t,n){var r=n(104);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){var r=n(58),o=n(173).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(e){try{return o(e)}catch(e){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?s(e):o(r(e))}},function(e,t){},function(e,t,n){n(117)("asyncIterator")},function(e,t,n){n(117)("observable")},function(e,t,n){e.exports={default:n(283),__esModule:!0}},function(e,t,n){n(284),e.exports=n(29).Object.setPrototypeOf},function(e,t,n){var r=n(47);r(r.S,"Object",{setPrototypeOf:n(285).set})},function(e,t,n){var r=n(57),o=n(48),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(102)(Function.call,n(174).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){e.exports={default:n(287),__esModule:!0}},function(e,t,n){n(288);var r=n(29).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){var r=n(47);r(r.S,"Object",{create:n(113)})},function(e,t,n){"use strict";var r=n(86),o=n(10),i=n(290);e.exports=function(){function e(e,t,n,r,a,s){s!==i&&o(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=r,n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function r(e,t,n){function r(t){var r=new i.default(t);n.call(e,r)}return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var o=n(292),i=function(e){return e&&e.__esModule?e:{default:e}}(o);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return null===e||void 0===e}function i(){return f}function a(){return d}function s(e){var t=e.type,n="function"==typeof e.stopPropagation||"boolean"==typeof e.cancelBubble;u.default.call(this),this.nativeEvent=e;var r=a;"defaultPrevented"in e?r=e.defaultPrevented?i:a:"getPreventDefault"in e?r=e.getPreventDefault()?i:a:"returnValue"in e&&(r=e.returnValue===d?i:a),this.isDefaultPrevented=r;var o=[],s=void 0,l=void 0,c=h.concat();for(v.forEach(function(e){t.match(e.reg)&&(c=c.concat(e.props),e.fix&&o.push(e.fix))}),s=c.length;s;)l=c[--s],this[l]=e[l];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),s=o.length;s;)(0,o[--s])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var l=n(293),u=r(l),c=n(16),p=r(c),f=!0,d=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],v=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){o(e.which)&&(e.which=o(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,r=void 0,o=void 0,i=t.wheelDelta,a=t.axis,s=t.wheelDeltaY,l=t.wheelDeltaX,u=t.detail;i&&(o=i/120),u&&(o=0-(u%3==0?u/3:u)),void 0!==a&&(a===e.HORIZONTAL_AXIS?(r=0,n=0-o):a===e.VERTICAL_AXIS&&(n=0,r=o)),void 0!==s&&(r=s/120),void 0!==l&&(n=-1*l/120),n||r||(r=o),void 0!==n&&(e.deltaX=n),void 0!==r&&(e.deltaY=r),void 0!==o&&(e.delta=o)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,r=void 0,i=void 0,a=e.target,s=t.button;return a&&o(e.pageX)&&!o(t.clientX)&&(n=a.ownerDocument||document,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||void 0===s||(e.which=1&s?1:2&s?3:4&s?2:0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===a?e.toElement:e.fromElement),e}}],m=u.default.prototype;(0,p.default)(s.prototype,m,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=d,m.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=f,m.stopPropagation.call(this)}}),t.default=s,e.exports=t.default},function(e,t,n){"use strict";function r(){return!1}function o(){return!0}function i(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),i.prototype={isEventObject:1,constructor:i,isDefaultPrevented:r,isPropagationStopped:r,isImmediatePropagationStopped:r,preventDefault:function(){this.isDefaultPrevented=o},stopPropagation:function(){this.isPropagationStopped=o},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=o,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t.default=i,e.exports=t.default},function(e,t,n){e.exports={default:n(295),__esModule:!0}},function(e,t,n){n(85),n(296),e.exports=n(29).Array.from},function(e,t,n){"use strict";var r=n(102),o=n(47),i=n(111),a=n(297),s=n(298),l=n(170),u=n(299),c=n(175);o(o.S+o.F*!n(300)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,p,f=i(e),d="function"==typeof this?this:Array,h=arguments.length,v=h>1?arguments[1]:void 0,m=void 0!==v,y=0,g=c(f);if(m&&(v=r(v,h>2?arguments[2]:void 0,2)),void 0==g||d==Array&&s(g))for(t=l(f.length),n=new d(t);t>y;y++)u(n,y,m?v(f[y],y):f[y]);else for(p=g.call(f),n=new d;!(o=p.next()).done;y++)u(n,y,m?a(p,v,[o.value,y],!0):o.value);return n.length=y,n}})},function(e,t,n){var r=n(48);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t}}},function(e,t,n){var r=n(59),o=n(30)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){"use strict";var r=n(41),o=n(69);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(30)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){"use strict";function r(e){return e}function o(e,t,n){function o(e,t){var n=g.hasOwnProperty(t)?g[t]:null;x.hasOwnProperty(t)&&s("OVERRIDE_BASE"===n,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",t),e&&s("DEFINE_MANY"===n||"DEFINE_MANY_MERGED"===n,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",t)}function u(e,n){if(n){s("function"!=typeof n,"ReactClass: You're attempting to use a component class or function as a mixin. Instead, just use a regular object."),s(!t(n),"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object.");var r=e.prototype,i=r.__reactAutoBindPairs;n.hasOwnProperty(l)&&C.mixins(e,n.mixins);for(var a in n)if(n.hasOwnProperty(a)&&a!==l){var u=n[a],c=r.hasOwnProperty(a);if(o(c,a),C.hasOwnProperty(a))C[a](e,u);else{var p=g.hasOwnProperty(a),h="function"==typeof u,v=h&&!p&&!c&&!1!==n.autobind;if(v)i.push(a,u),r[a]=u;else if(c){var m=g[a];s(p&&("DEFINE_MANY_MERGED"===m||"DEFINE_MANY"===m),"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",m,a),"DEFINE_MANY_MERGED"===m?r[a]=f(r[a],u):"DEFINE_MANY"===m&&(r[a]=d(r[a],u))}else r[a]=u}}}else;}function c(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in C;s(!o,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',n);var i=n in e;if(i){var a=b.hasOwnProperty(n)?b[n]:null;return s("DEFINE_MANY_MERGED"===a,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n),void(e[n]=f(e[n],r))}e[n]=r}}}function p(e,t){s(e&&t&&"object"==typeof e&&"object"==typeof t,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.");for(var n in t)t.hasOwnProperty(n)&&(s(void 0===e[n],"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",n),e[n]=t[n]);return e}function f(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return p(o,n),p(o,r),o}}function d(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function h(e,t){var n=t.bind(e);return n}function v(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=h(e,o)}}function m(e){var t=r(function(e,r,o){this.__reactAutoBindPairs.length&&v(this),this.props=e,this.context=r,this.refs=a,this.updater=o||n,this.state=null;var i=this.getInitialState?this.getInitialState():null;s("object"==typeof i&&!Array.isArray(i),"%s.getInitialState(): must return an object or null",t.displayName||"ReactCompositeComponent"),this.state=i});t.prototype=new _,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],y.forEach(u.bind(null,t)),u(t,w),u(t,e),u(t,S),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),s(t.prototype.render,"createClass(...): Class specification must implement a `render` method.");for(var o in g)t.prototype[o]||(t.prototype[o]=null);return t}var y=[],g={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",UNSAFE_componentWillMount:"DEFINE_MANY",UNSAFE_componentWillReceiveProps:"DEFINE_MANY",UNSAFE_componentWillUpdate:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},b={getDerivedStateFromProps:"DEFINE_MANY_MERGED"},C={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)u(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=i({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=i({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=f(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=i({},e.propTypes,t)},statics:function(e,t){c(e,t)},autobind:function(){}},w={componentDidMount:function(){this.__isMounted=!0}},S={componentWillUnmount:function(){this.__isMounted=!1}},x={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e,t)},isMounted:function(){return!!this.__isMounted}},_=function(){};return i(_.prototype,e.prototype,x),m}var i=n(16),a=n(302),s=n(10),l="mixins";e.exports=o},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";function r(e,t,n){n=n||{},9===t.nodeType&&(t=o.getWindow(t));var r=n.allowHorizontalScroll,i=n.onlyScrollIfNeeded,a=n.alignWithTop,s=n.alignWithLeft,l=n.offsetTop||0,u=n.offsetLeft||0,c=n.offsetBottom||0,p=n.offsetRight||0;r=void 0===r||r;var f=o.isWindow(t),d=o.offset(e),h=o.outerHeight(e),v=o.outerWidth(e),m=void 0,y=void 0,g=void 0,b=void 0,C=void 0,w=void 0,S=void 0,x=void 0,_=void 0,k=void 0;f?(S=t,k=o.height(S),_=o.width(S),x={left:o.scrollLeft(S),top:o.scrollTop(S)},C={left:d.left-x.left-u,top:d.top-x.top-l},w={left:d.left+v-(x.left+_)+p,top:d.top+h-(x.top+k)+c},b=x):(m=o.offset(t),y=t.clientHeight,g=t.clientWidth,b={left:t.scrollLeft,top:t.scrollTop},C={left:d.left-(m.left+(parseFloat(o.css(t,"borderLeftWidth"))||0))-u,top:d.top-(m.top+(parseFloat(o.css(t,"borderTopWidth"))||0))-l},w={left:d.left+v-(m.left+g+(parseFloat(o.css(t,"borderRightWidth"))||0))+p,top:d.top+h-(m.top+y+(parseFloat(o.css(t,"borderBottomWidth"))||0))+c}),C.top<0||w.top>0?!0===a?o.scrollTop(t,b.top+C.top):!1===a?o.scrollTop(t,b.top+w.top):C.top<0?o.scrollTop(t,b.top+C.top):o.scrollTop(t,b.top+w.top):i||(a=void 0===a||!!a,a?o.scrollTop(t,b.top+C.top):o.scrollTop(t,b.top+w.top)),r&&(C.left<0||w.left>0?!0===s?o.scrollLeft(t,b.left+C.left):!1===s?o.scrollLeft(t,b.left+w.left):C.left<0?o.scrollLeft(t,b.left+C.left):o.scrollLeft(t,b.left+w.left):i||(s=void 0===s||!!s,s?o.scrollLeft(t,b.left+C.left):o.scrollLeft(t,b.left+w.left)))}var o=n(304);e.exports=r},function(e,t,n){"use strict";function r(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function o(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function i(e){return o(e)}function a(e){return o(e,!0)}function s(e){var t=r(e),n=e.ownerDocument,o=n.defaultView||n.parentWindow;return t.left+=i(o),t.top+=a(o),t}function l(e,t,n){var r="",o=e.ownerDocument,i=n||o.defaultView.getComputedStyle(e,null);return i&&(r=i.getPropertyValue(t)||i[t]),r}function u(e,t){var n=e[_]&&e[_][t];if(S.test(n)&&!x.test(t)){var r=e.style,o=r[E],i=e[k][E];e[k][E]=e[_][E],r[E]="fontSize"===t?"1em":n||0,n=r.pixelLeft+O,r[E]=o,e[k][E]=i}return""===n?"auto":n}function c(e,t){for(var n=0;n<e.length;n++)t(e[n])}function p(e){return"border-box"===T(e,"boxSizing")}function f(e,t,n){var r={},o=e.style,i=void 0;for(i in t)t.hasOwnProperty(i)&&(r[i]=o[i],o[i]=t[i]);n.call(e);for(i in t)t.hasOwnProperty(i)&&(o[i]=r[i])}function d(e,t,n){var r=0,o=void 0,i=void 0,a=void 0;for(i=0;i<t.length;i++)if(o=t[i])for(a=0;a<n.length;a++){var s=void 0;s="border"===o?o+n[a]+"Width":o+n[a],r+=parseFloat(T(e,s))||0}return r}function h(e){return null!=e&&e==e.window}function v(e,t,n){if(h(e))return"width"===t?I.viewportWidth(e):I.viewportHeight(e);if(9===e.nodeType)return"width"===t?I.docWidth(e):I.docHeight(e);var r="width"===t?["Left","Right"]:["Top","Bottom"],o="width"===t?e.offsetWidth:e.offsetHeight,i=T(e),a=p(e,i),s=0;(null==o||o<=0)&&(o=void 0,s=T(e,t),(null==s||Number(s)<0)&&(s=e.style[t]||0),s=parseFloat(s)||0),void 0===n&&(n=a?D:P);var l=void 0!==o||a,u=o||s;if(n===P)return l?u-d(e,["border","padding"],r,i):s;if(l){var c=n===M?-d(e,["border"],r,i):d(e,["margin"],r,i);return u+(n===D?0:c)}return s+d(e,N.slice(n),r,i)}function m(e){var t=void 0,n=arguments;return 0!==e.offsetWidth?t=v.apply(void 0,n):f(e,A,function(){t=v.apply(void 0,n)}),t}function y(e,t,n){var r=n;{if("object"!==(void 0===t?"undefined":C(t)))return void 0!==r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):T(e,t);for(var o in t)t.hasOwnProperty(o)&&y(e,o,t[o])}}function g(e,t){"static"===y(e,"position")&&(e.style.position="relative");var n=s(e),r={},o=void 0,i=void 0;for(i in t)t.hasOwnProperty(i)&&(o=parseFloat(y(e,i))||0,r[i]=o+t[i]-n[i]);y(e,r)}var b=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},w=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,S=new RegExp("^("+w+")(?!px)[a-z%]+$","i"),x=/^(top|right|bottom|left)$/,_="currentStyle",k="runtimeStyle",E="left",O="px",T=void 0;"undefined"!=typeof window&&(T=window.getComputedStyle?l:u);var N=["margin","border","padding"],P=-1,M=2,D=1,I={};c(["Width","Height"],function(e){I["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],I["viewport"+e](n))},I["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,i=r.documentElement,a=i[n];return"CSS1Compat"===r.compatMode&&a||o&&o[n]||a}});var A={position:"absolute",visibility:"hidden",display:"block"};c(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);I["outer"+t]=function(t,n){return t&&m(t,e,n?0:D)};var n="width"===e?["Left","Right"]:["Top","Bottom"];I[e]=function(t,r){if(void 0===r)return t&&m(t,e,P);if(t){var o=T(t);return p(t)&&(r+=d(t,["padding","border"],n,o)),y(t,e,r)}}}),e.exports=b({getWindow:function(e){var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t){if(void 0===t)return s(e);g(e,t)},isWindow:h,each:c,css:y,clone:function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);if(e.overflow)for(var n in e)e.hasOwnProperty(n)&&(t.overflow[n]=e.overflow[n]);return t},scrollLeft:function(e,t){if(h(e)){if(void 0===t)return i(e);window.scrollTo(t,a(e))}else{if(void 0===t)return e.scrollLeft;e.scrollLeft=t}},scrollTop:function(e,t){if(h(e)){if(void 0===t)return a(e);window.scrollTo(i(e),t)}else{if(void 0===t)return e.scrollTop;e.scrollTop=t}},viewportWidth:0,viewportHeight:0},I)},function(e,t,n){e.exports={default:n(306),__esModule:!0}},function(e,t,n){n(115),n(85),e.exports=n(307)},function(e,t,n){var r=n(176),o=n(30)("iterator"),i=n(59);e.exports=n(29).isIterable=function(e){var t=Object(e);return void 0!==t[o]||"@@iterator"in t||i.hasOwnProperty(r(t))}},function(e,t,n){e.exports={default:n(309),__esModule:!0}},function(e,t,n){n(115),n(85),e.exports=n(310)},function(e,t,n){var r=n(48),o=n(175);e.exports=n(29).getIterator=function(e){var t=o(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return r(t.call(e))}},function(e,t,n){"use strict";var r=n(312);e.exports=function(e,t,n,o){var i=n?n.call(o,e,t):void 0;if(void 0!==i)return!!i;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var a=r(e),s=r(t),l=a.length;if(l!==s.length)return!1;o=o||null;for(var u=Object.prototype.hasOwnProperty.bind(t),c=0;c<l;c++){var p=a[c];if(!u(p))return!1;var f=e[p],d=t[p],h=n?n.call(o,f,d,p):void 0;if(!1===h||void 0===h&&f!==d)return!1}return!0}},function(e,t,n){function r(e){return null!=e&&i(y(e))}function o(e,t){return e="number"==typeof e||f.test(e)?+e:-1,t=null==t?m:t,e>-1&&e%1==0&&e<t}function i(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=m}function a(e){for(var t=l(e),n=t.length,r=n&&e.length,a=!!r&&i(r)&&(p(e)||c(e)),s=-1,u=[];++s<n;){var f=t[s];(a&&o(f,r)||h.call(e,f))&&u.push(f)}return u}function s(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function l(e){if(null==e)return[];s(e)||(e=Object(e));var t=e.length;t=t&&i(t)&&(p(e)||c(e))&&t||0;for(var n=e.constructor,r=-1,a="function"==typeof n&&n.prototype===e,l=Array(t),u=t>0;++r<t;)l[r]=r+"";for(var f in e)u&&o(f,t)||"constructor"==f&&(a||!h.call(e,f))||l.push(f);return l}var u=n(313),c=n(314),p=n(315),f=/^\d+$/,d=Object.prototype,h=d.hasOwnProperty,v=u(Object,"keys"),m=9007199254740991,y=function(e){return function(t){return null==t?void 0:t[e]}}("length"),g=v?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&r(e)?a(e):s(e)?v(e):[]}:a;e.exports=g},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return a(n)?n:void 0}function o(e){return i(e)&&f.call(e)==s}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function a(e){return null!=e&&(o(e)?d.test(c.call(e)):n(e)&&l.test(e))}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,p=u.hasOwnProperty,f=u.toString,d=RegExp("^"+c.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t){function n(e){return o(e)&&h.call(e,"callee")&&(!m.call(e,"callee")||v.call(e)==c)}function r(e){return null!=e&&a(e.length)&&!i(e)}function o(e){return l(e)&&r(e)}function i(e){var t=s(e)?v.call(e):"";return t==p||t==f}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=u}function s(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function l(e){return!!e&&"object"==typeof e}var u=9007199254740991,c="[object Arguments]",p="[object Function]",f="[object GeneratorFunction]",d=Object.prototype,h=d.hasOwnProperty,v=d.toString,m=d.propertyIsEnumerable;e.exports=n},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=v}function o(e){return i(e)&&f.call(e)==s}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function a(e){return null!=e&&(o(e)?d.test(c.call(e)):n(e)&&l.test(e))}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,p=u.hasOwnProperty,f=u.toString,d=RegExp("^"+c.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),h=function(e,t){var n=null==e?void 0:e[t];return a(n)?n:void 0}(Array,"isArray"),v=9007199254740991,m=h||function(e){return n(e)&&r(e.length)&&"[object Array]"==f.call(e)};e.exports=m},function(e,t,n){"use strict";function r(e){var t=null,n=!1;return h.Children.forEach(e,function(e){e&&e.props&&e.props.checked&&(t=e.props.value,n=!0)}),n?{value:t}:void 0}var o=n(8),i=n.n(o),a=n(2),s=n.n(a),l=n(7),u=n.n(l),c=n(3),p=n.n(c),f=n(4),d=n.n(f),h=n(0),v=(n.n(h),n(5)),m=n.n(v),y=n(6),g=n.n(y),b=n(31),C=n.n(b),w=n(123),S=function(e){function t(e){s()(this,t);var n=p()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onRadioChange=function(e){var t=n.state.value,r=e.target.value;"value"in n.props||n.setState({value:r});var o=n.props.onChange;o&&r!==t&&o(e)};var o=void 0;if("value"in e)o=e.value;else if("defaultValue"in e)o=e.defaultValue;else{var i=r(e.children);o=i&&i.value}return n.state={value:o},n}return d()(t,e),u()(t,[{key:"getChildContext",value:function(){return{radioGroup:{onChange:this.onRadioChange,value:this.state.value,disabled:this.props.disabled,name:this.props.name}}}},{key:"componentWillReceiveProps",value:function(e){if("value"in e)this.setState({value:e.value});else{var t=r(e.children);t&&this.setState({value:t.value})}}},{key:"shouldComponentUpdate",value:function(e,t){return!C()(this.props,e)||!C()(this.state,t)}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=void 0===n?"ant-radio-group":n,o=t.className,a=void 0===o?"":o,s=t.options,l=g()(r,i()({},r+"-"+t.size,t.size),a),u=t.children;return s&&s.length>0&&(u=s.map(function(t,n){return"string"==typeof t?h.createElement(w.a,{key:n,disabled:e.props.disabled,value:t,onChange:e.onRadioChange,checked:e.state.value===t},t):h.createElement(w.a,{key:n,disabled:t.disabled||e.props.disabled,value:t.value,onChange:e.onRadioChange,checked:e.state.value===t.value},t.label)})),h.createElement("div",{className:l,style:t.style,onMouseEnter:t.onMouseEnter,onMouseLeave:t.onMouseLeave,id:t.id},u)}}]),t}(h.Component);t.a=S,S.defaultProps={disabled:!1},S.childContextTypes={radioGroup:m.a.any}},function(e,t,n){"use strict";var r=n(1),o=n.n(r),i=n(2),a=n.n(i),s=n(7),l=n.n(s),u=n(3),c=n.n(u),p=n(4),f=n.n(p),d=n(0),h=(n.n(d),n(5)),v=n.n(h),m=n(123),y=function(e){function t(){return a()(this,t),c()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return f()(t,e),l()(t,[{key:"render",value:function(){var e=o()({},this.props);return this.context.radioGroup&&(e.onChange=this.context.radioGroup.onChange,e.checked=this.props.value===this.context.radioGroup.value,e.disabled=this.props.disabled||this.context.radioGroup.disabled),d.createElement(m.a,e)}}]),t}(d.Component);t.a=y,y.defaultProps={prefixCls:"ant-radio-button"},y.contextTypes={radioGroup:v.a.any}},function(e,t){},function(e,t,n){var r=n(33),o=function(){return r.Date.now()};e.exports=o},function(e,t,n){function r(e){if("number"==typeof e)return e;if(i(e))return a;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(s,"");var n=u.test(e);return n||c.test(e)?p(e.slice(2),n?2:8):l.test(e)?a:+e}var o=n(32),i=n(91),a=NaN,s=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,p=parseInt;e.exports=r},function(e,t,n){function r(e){var t=a.call(e,l),n=e[l];try{e[l]=void 0;var r=!0}catch(e){}var o=s.call(e);return r&&(t?e[l]=n:delete e[l]),o}var o=n(72),i=Object.prototype,a=i.hasOwnProperty,s=i.toString,l=o?o.toStringTag:void 0;e.exports=r},function(e,t){function n(e){return o.call(e)}var r=Object.prototype,o=r.toString;e.exports=n},function(e,t,n){"use strict";t.__esModule=!0;var r=n(324),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=o.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(0),u=r(l),c=n(325),p=n(16),f=r(p),d=n(331),h=r(d),v=n(185),m=r(v),y=n(333),g=r(y),b=g.default&&n(186),C=function(e){function t(n){o(this,t);var r=i(this,e.call(this,n));return r.innerSliderRefHandler=function(e){return r.innerSlider=e},r.slickPrev=function(){return r.innerSlider.slickPrev()},r.slickNext=function(){return r.innerSlider.slickNext()},r.slickGoTo=function(e){return r.innerSlider.slickGoTo(e)},r.slickPause=function(){return r.innerSlider.pause()},r.slickPlay=function(){return r.innerSlider.autoPlay()},r.state={breakpoint:null},r._responsiveMediaHandlers=[],r}return a(t,e),t.prototype.media=function(e,t){b.register(e,t),this._responsiveMediaHandlers.push({query:e,handler:t})},t.prototype.componentWillMount=function(){var e=this;if(this.props.responsive){var t=this.props.responsive.map(function(e){return e.breakpoint});t.sort(function(e,t){return e-t}),t.forEach(function(n,r){var o=void 0;o=0===r?(0,h.default)({minWidth:0,maxWidth:n}):(0,h.default)({minWidth:t[r-1]+1,maxWidth:n}),g.default&&e.media(o,function(){e.setState({breakpoint:n})})});var n=(0,h.default)({minWidth:t.slice(-1)[0]});g.default&&this.media(n,function(){e.setState({breakpoint:null})})}},t.prototype.componentWillUnmount=function(){this._responsiveMediaHandlers.forEach(function(e){b.unregister(e.query,e.handler)})},t.prototype.render=function(){var e,t,n=this;this.state.breakpoint?(t=this.props.responsive.filter(function(e){return e.breakpoint===n.state.breakpoint}),e="unslick"===t[0].settings?"unslick":(0,f.default)({},m.default,this.props,t[0].settings)):e=(0,f.default)({},m.default,this.props),e.centerMode&&(e.slidesToScroll,e.slidesToScroll=1),e.fade&&(e.slidesToShow,e.slidesToScroll,e.slidesToShow=1,e.slidesToScroll=1);var r=u.default.Children.toArray(this.props.children);return r=r.filter(function(e){return"string"==typeof e?!!e.trim():!!e}),"unslick"===e?(e=(0,f.default)({unslick:!0},m.default,this.props),e.slidesToShow=r.length,e.className+=" unslicked"):r.length<=e.slidesToShow&&(e.unslick=!0,e.slidesToShow=r.length,e.className+=" unslicked"),u.default.createElement(c.InnerSlider,s({ref:this.innerSliderRefHandler},e),r)},t}(u.default.Component);t.default=C},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.InnerSlider=void 0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(0),a=r(i),s=n(326),l=r(s),u=n(128),c=r(u),p=n(327),f=r(p),d=n(185),h=(r(d),n(15)),v=r(h),m=n(6),y=r(m),g=n(16),b=r(g),C=n(73),w=n(126),S=n(328),x=n(329),_=n(330);t.InnerSlider=(0,v.default)({displayName:"InnerSlider",mixins:[c.default,l.default],list:null,track:null,listRefHandler:function(e){this.list=e},trackRefHandler:function(e){this.track=e},getInitialState:function(){return o({},f.default,{currentSlide:this.props.initialSlide})},componentWillMount:function(){if(this.props.init&&this.props.init(),this.props.lazyLoad){var e=(0,C.getOnDemandLazySlides)((0,b.default)({},this.props,this.state));e.length>0&&(this.setState(function(t,n){return{lazyLoadedList:t.lazyLoadedList.concat(e)}}),this.props.onLazyLoad&&this.props.onLazyLoad(e))}},componentDidMount:function(){var e=this,t=(0,b.default)({listRef:this.list,trackRef:this.track},this.props),n=(0,C.initializedState)(t);(0,b.default)(t,{slideIndex:n.currentSlide},n);var r=(0,w.getTrackLeft)(t);(0,b.default)(t,{left:r});var o=(0,w.getTrackCSS)(t);n.trackStyle=o,this.setState(n,function(){e.adaptHeight(),e.autoPlay()}),window&&(window.addEventListener?window.addEventListener("resize",this.onWindowResized):window.attachEvent("onresize",this.onWindowResized))},componentWillUnmount:function(){this.animationEndCallback&&clearTimeout(this.animationEndCallback),window.addEventListener?window.removeEventListener("resize",this.onWindowResized):window.detachEvent("onresize",this.onWindowResized),this.autoplayTimer&&clearInterval(this.autoplayTimer)},componentWillReceiveProps:function(e){var t=this,n=(0,b.default)({listRef:this.list,trackRef:this.track},e,this.state),r=(0,C.initializedState)(n);(0,b.default)(n,{slideIndex:r.currentSlide},r);var o=(0,w.getTrackLeft)(n);(0,b.default)(n,{left:o});var i=(0,w.getTrackCSS)(n);a.default.Children.count(this.props.children)!==a.default.Children.count(e.children)&&(r.trackStyle=i),this.setState(r,function(){t.state.currentSlide>=a.default.Children.count(e.children)&&t.changeSlide({message:"index",index:a.default.Children.count(e.children)-e.slidesToShow,currentSlide:t.state.currentSlide}),e.autoplay?t.autoPlay(e.autoplay):t.pause()})},componentDidUpdate:function(){var e=this;if(document.querySelectorAll(".slick-slide img").forEach(function(t){t.onload||(t.onload=function(){return setTimeout(function(){return e.update(e.props)},e.props.speed)})}),this.props.reInit&&this.props.reInit(),this.props.lazyLoad){var t=(0,C.getOnDemandLazySlides)((0,b.default)({},this.props,this.state));t.length>0&&(this.setState(function(e,n){return{lazyLoadedList:e.lazyLoadedList.concat(t)}}),this.props.onLazyLoad&&this.props.onLazyLoad(t))}this.adaptHeight()},onWindowResized:function(){this.update(this.props),this.setState({animating:!1}),clearTimeout(this.animationEndCallback),delete this.animationEndCallback},slickPrev:function(){var e=this;setTimeout(function(){return e.changeSlide({message:"previous"})},0)},slickNext:function(){var e=this;setTimeout(function(){return e.changeSlide({message:"next"})},0)},slickGoTo:function(e){var t=this;e=Number(e),!isNaN(e)&&setTimeout(function(){return t.changeSlide({message:"index",index:e,currentSlide:t.state.currentSlide})},0)},render:function(){var e=(0,y.default)("slick-initialized","slick-slider",this.props.className,{"slick-vertical":this.props.vertical}),t=(0,b.default)({},this.props,this.state),n=(0,C.extractObject)(t,["fade","cssEase","speed","infinite","centerMode","focusOnSelect","currentSlide","lazyLoad","lazyLoadedList","rtl","slideWidth","slideHeight","listHeight","vertical","slidesToShow","slidesToScroll","slideCount","trackStyle","variableWidth","unslick","centerPadding"]);n.focusOnSelect=this.props.focusOnSelect?this.selectHandler:null;var r;if(!0===this.props.dots&&this.state.slideCount>=this.props.slidesToShow){var i=(0,C.extractObject)(t,["dotsClass","slideCount","slidesToShow","currentSlide","slidesToScroll","clickHandler","children","customPaging","infinite","appendDots"]);i.clickHandler=this.changeSlide,r=a.default.createElement(x.Dots,i)}var s,l,u=(0,C.extractObject)(t,["infinite","centerMode","currentSlide","slideCount","slidesToShow","prevArrow","nextArrow"]);u.clickHandler=this.changeSlide,this.props.arrows&&(s=a.default.createElement(_.PrevArrow,u),l=a.default.createElement(_.NextArrow,u));var c=null;this.props.vertical&&(c={height:this.state.listHeight});var p=null;!1===this.props.vertical?!0===this.props.centerMode&&(p={padding:"0px "+this.props.centerPadding}):!0===this.props.centerMode&&(p={padding:this.props.centerPadding+" 0px"});var f=(0,b.default)({},c,p),d={className:"slick-list",style:f,onMouseDown:this.swipeStart,onMouseMove:this.state.dragging?this.swipeMove:null,onMouseUp:this.swipeEnd,onMouseLeave:this.state.dragging?this.swipeEnd:null,onTouchStart:this.swipeStart,onTouchMove:this.state.dragging?this.swipeMove:null,onTouchEnd:this.swipeEnd,onTouchCancel:this.state.dragging?this.swipeEnd:null,onKeyDown:this.props.accessibility?this.keyHandler:null},h={className:e,onMouseEnter:this.onInnerSliderEnter,onMouseLeave:this.onInnerSliderLeave,onMouseOver:this.onInnerSliderOver,dir:"ltr"};return this.props.unslick&&(d={className:"slick-list"},h={className:e}),a.default.createElement("div",h,this.props.unslick?"":s,a.default.createElement("div",o({ref:this.listRefHandler},d),a.default.createElement(S.Track,o({ref:this.trackRefHandler},n),this.props.children)),this.props.unslick?"":l,this.props.unslick?"":r)}})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(126),i=n(128),a=(r(i),n(16)),s=r(a),l=n(9),u=r(l),c=n(127),p=n(73),f={changeSlide:function(e){var t,n,r,o,i,a=this.props,s=a.slidesToScroll,l=a.slidesToShow,u=a.centerMode,p=a.rtl,f=this.state,d=f.slideCount,h=f.currentSlide;if(o=d%s!=0,t=o?0:(d-h)%s,"previous"===e.message)r=0===t?s:l-t,i=h-r,this.props.lazyLoad&&!this.props.infinite&&(n=h-r,i=-1===n?d-1:n);else if("next"===e.message)r=0===t?s:t,i=h+r,this.props.lazyLoad&&!this.props.infinite&&(i=(h+s)%d+t);else if("dots"===e.message){if((i=e.index*e.slidesToScroll)===e.currentSlide)return}else if("children"===e.message){if((i=e.index)===e.currentSlide)return;if(this.props.infinite){var v=(0,c.siblingDirection)({currentSlide:h,targetSlide:i,slidesToShow:l,centerMode:u,slideCount:d,rtl:p});i>e.currentSlide&&"left"===v?i-=d:i<e.currentSlide&&"right"===v&&(i+=d)}}else if("index"===e.message&&(i=Number(e.index))===e.currentSlide)return;this.slideHandler(i)},keyHandler:function(e){e.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===e.keyCode&&!0===this.props.accessibility?this.changeSlide({message:!0===this.props.rtl?"next":"previous"}):39===e.keyCode&&!0===this.props.accessibility&&this.changeSlide({message:!0===this.props.rtl?"previous":"next"}))},selectHandler:function(e){this.changeSlide(e)},swipeStart:function(e){"IMG"===e.target.tagName&&e.preventDefault();var t,n;!1!==this.props.swipe&&(!1===this.props.draggable&&-1!==e.type.indexOf("mouse")||(t=void 0!==e.touches?e.touches[0].pageX:e.clientX,n=void 0!==e.touches?e.touches[0].pageY:e.clientY,this.setState({dragging:!0,touchObject:{startX:t,startY:n,curX:t,curY:n}})))},swipeMove:function(e){if(!this.state.dragging)return void e.preventDefault();if(!this.state.scrolling){if(this.state.animating)return void e.preventDefault();this.props.vertical&&this.props.swipeToSlide&&this.props.verticalSwiping&&e.preventDefault();var t,n,r,i=this.state.touchObject;n=(0,o.getTrackLeft)((0,s.default)({slideIndex:this.state.currentSlide,trackRef:this.track},this.props,this.state)),i.curX=e.touches?e.touches[0].pageX:e.clientX,i.curY=e.touches?e.touches[0].pageY:e.clientY,i.swipeLength=Math.round(Math.sqrt(Math.pow(i.curX-i.startX,2)));var a=Math.round(Math.sqrt(Math.pow(i.curY-i.startY,2)));if(!this.props.verticalSwiping&&!this.state.swiping&&a>10)return void this.setState({scrolling:!0});this.props.verticalSwiping&&(i.swipeLength=a),r=(!1===this.props.rtl?1:-1)*(i.curX>i.startX?1:-1),this.props.verticalSwiping&&(r=i.curY>i.startY?1:-1);var l=this.state.currentSlide,u=Math.ceil(this.state.slideCount/this.props.slidesToScroll),c=(0,p.getSwipeDirection)(this.state.touchObject,this.props.verticalSwiping),f=i.swipeLength;!1===this.props.infinite&&(0===l&&"right"===c||l+1>=u&&"left"===c)&&(f=i.swipeLength*this.props.edgeFriction,!1===this.state.edgeDragged&&this.props.edgeEvent&&(this.props.edgeEvent(c),this.setState({edgeDragged:!0}))),!1===this.state.swiped&&this.props.swipeEvent&&(this.props.swipeEvent(c),this.setState({swiped:!0})),t=this.props.vertical?n+f*(this.state.listHeight/this.state.listWidth)*r:this.props.rtl?n-f*r:n+f*r,this.props.verticalSwiping&&(t=n+f*r),this.setState({touchObject:i,swipeLeft:t,trackStyle:(0,o.getTrackCSS)((0,s.default)({left:t},this.props,this.state))}),Math.abs(i.curX-i.startX)<.8*Math.abs(i.curY-i.startY)||i.swipeLength>10&&(this.setState({swiping:!0}),e.preventDefault())}},getNavigableIndexes:function(){var e=void 0,t=0,n=0,r=[];for(this.props.infinite?(t=-1*this.props.slidesToShow,n=-1*this.props.slidesToShow,e=2*this.state.slideCount):e=this.state.slideCount;t<e;)r.push(t),t=n+this.props.slidesToScroll,n+=this.props.slidesToScroll<=this.props.slidesToShow?this.props.slidesToScroll:this.props.slidesToShow;return r},checkNavigable:function(e){var t=this.getNavigableIndexes(),n=0;if(e>t[t.length-1])e=t[t.length-1];else for(var r in t){if(e<t[r]){e=n;break}n=t[r]}return e},getSlideCount:function(){var e=this,t=this.props.centerMode?this.state.slideWidth*Math.floor(this.props.slidesToShow/2):0;if(this.props.swipeToSlide){var n=void 0,r=u.default.findDOMNode(this.list),o=r.querySelectorAll(".slick-slide");if(Array.from(o).every(function(r){if(e.props.vertical){if(r.offsetTop+(0,p.getHeight)(r)/2>-1*e.state.swipeLeft)return n=r,!1}else if(r.offsetLeft-t+(0,p.getWidth)(r)/2>-1*e.state.swipeLeft)return n=r,!1;return!0}),!n)return 0;var i=!0===this.props.rtl?this.state.slideCount-this.state.currentSlide:this.state.currentSlide;return Math.abs(n.dataset.index-i)||1}return this.props.slidesToScroll},swipeEnd:function(e){if(!this.state.dragging)return void(this.props.swipe&&e.preventDefault());var t=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,r=(0,p.getSwipeDirection)(t,this.props.verticalSwiping);this.props.verticalSwiping&&(n=this.state.listHeight/this.props.touchThreshold);var i=this.state.scrolling;if(this.setState({dragging:!1,edgeDragged:!1,scrolling:!1,swiping:!1,swiped:!1,swipeLeft:null,touchObject:{}}),!i&&t.swipeLength)if(t.swipeLength>n){e.preventDefault(),this.props.onSwipe&&this.props.onSwipe(r);var a=void 0,l=void 0;switch(r){case"left":case"up":l=this.state.currentSlide+this.getSlideCount(),a=this.props.swipeToSlide?this.checkNavigable(l):l,this.setState({currentDirection:0});break;case"right":case"down":l=this.state.currentSlide-this.getSlideCount(),a=this.props.swipeToSlide?this.checkNavigable(l):l,this.setState({currentDirection:1});break;default:a=this.state.currentSlide}this.slideHandler(a)}else{var u=(0,o.getTrackLeft)((0,s.default)({slideIndex:this.state.currentSlide,trackRef:this.track},this.props,this.state));this.setState({trackStyle:(0,o.getTrackAnimateCSS)((0,s.default)({left:u},this.props,this.state))})}},onInnerSliderEnter:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderOver:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderLeave:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.autoPlay()}};t.default=f},function(e,t,n){"use strict";var r={animating:!1,dragging:!1,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,listWidth:null,listHeight:null,scrolling:!1,slideCount:null,slideWidth:null,slideHeight:null,swiping:!1,swipeLeft:null,touchObject:{startX:0,startY:0,curX:0,curY:0},lazyLoadedList:[],initialized:!1,edgeDragged:!1,swiped:!1,trackStyle:{},trackWidth:0};e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0,t.Track=void 0;var s=n(0),l=r(s),u=n(16),c=r(u),p=n(6),f=r(p),d=n(127),h=n(73),v=function(e){var t,n,r,o,i;i=e.rtl?e.slideCount-1-e.index:e.index,r=i<0||i>=e.slideCount,e.centerMode?(o=Math.floor(e.slidesToShow/2),n=(i-e.currentSlide)%e.slideCount==0,i>e.currentSlide-o-1&&i<=e.currentSlide+o&&(t=!0)):t=e.currentSlide<=i&&i<e.currentSlide+e.slidesToShow;var a=i===e.currentSlide;return(0,f.default)({"slick-slide":!0,"slick-active":t,"slick-center":n,"slick-cloned":r,"slick-current":a})},m=function(e){var t={};return void 0!==e.variableWidth&&!1!==e.variableWidth||(t.width=e.slideWidth),e.fade&&(t.position="relative",e.vertical?t.top=-e.index*e.slideHeight:t.left=-e.index*e.slideWidth,t.opacity=e.currentSlide===e.index?1:0,t.transition="opacity "+e.speed+"ms "+e.cssEase+", visibility "+e.speed+"ms "+e.cssEase,t.WebkitTransition="opacity "+e.speed+"ms "+e.cssEase+", visibility "+e.speed+"ms "+e.cssEase),t},y=function(e,t){return e.key||t},g=function(e){var t,n=[],r=[],o=[],i=l.default.Children.count(e.children),a=(0,h.lazyStartIndex)(e),s=(0,h.lazyEndIndex)(e);return l.default.Children.forEach(e.children,function(u,p){var h=void 0,g={message:"children",index:p,slidesToScroll:e.slidesToScroll,currentSlide:e.currentSlide};h=!e.lazyLoad||e.lazyLoad&&e.lazyLoadedList.indexOf(p)>=0?u:l.default.createElement("div",null);var b=m((0,c.default)({},e,{index:p})),C=h.props.className||"";if(n.push(l.default.cloneElement(h,{key:"original"+y(h,p),"data-index":p,className:(0,f.default)(v((0,c.default)({index:p},e)),C),tabIndex:"-1",style:(0,c.default)({outline:"none"},h.props.style||{},b),onClick:function(t){h.props&&h.props.onClick&&h.props.onClick(t),e.focusOnSelect&&e.focusOnSelect(g)}})),e.infinite&&!1===e.fade){var w=i-p;w<=(0,d.getPreClones)(e)&&i!==e.slidesToShow&&(t=-w,t>=a&&(h=u),r.push(l.default.cloneElement(h,{key:"precloned"+y(h,t),"data-index":t,tabIndex:"-1",className:(0,f.default)(v((0,c.default)({index:t},e)),C),style:(0,c.default)({},h.props.style||{},b),onClick:function(t){h.props&&h.props.onClick&&h.props.onClick(t),e.focusOnSelect&&e.focusOnSelect(g)}}))),i!==e.slidesToShow&&(t=i+p,t<s&&(h=u),o.push(l.default.cloneElement(h,{key:"postcloned"+y(h,t),"data-index":t,tabIndex:"-1",className:(0,f.default)(v((0,c.default)({index:t},e)),C),style:(0,c.default)({},h.props.style||{},b),onClick:function(t){h.props&&h.props.onClick&&h.props.onClick(t),e.focusOnSelect&&e.focusOnSelect(g)}})))}}),e.rtl?r.concat(n,o).reverse():r.concat(n,o)};t.Track=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return a(t,e),t.prototype.render=function(){var e=g(this.props);return l.default.createElement("div",{className:"slick-track",style:this.props.trackStyle},e)},t}(l.default.Component)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0,t.Dots=void 0;var s=n(0),l=r(s),u=n(6),c=r(u),p=function(e){return e.infinite?Math.ceil(e.slideCount/e.slidesToScroll):Math.ceil((e.slideCount-e.slidesToShow)/e.slidesToScroll)+1};t.Dots=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return a(t,e),t.prototype.clickHandler=function(e,t){t.preventDefault(),this.props.clickHandler(e)},t.prototype.render=function(){var e=this,t=p({slideCount:this.props.slideCount,slidesToScroll:this.props.slidesToScroll,slidesToShow:this.props.slidesToShow,infinite:this.props.infinite}),n=Array.apply(null,Array(t+1).join("0").split("")).map(function(t,n){var r=n*e.props.slidesToScroll,o=n*e.props.slidesToScroll+(e.props.slidesToScroll-1),i=(0,c.default)({"slick-active":e.props.currentSlide>=r&&e.props.currentSlide<=o}),a={message:"dots",index:n,slidesToScroll:e.props.slidesToScroll,currentSlide:e.props.currentSlide},s=e.clickHandler.bind(e,a);return l.default.createElement("li",{key:n,className:i},l.default.cloneElement(e.props.customPaging(n),{onClick:s}))});return l.default.cloneElement(this.props.appendDots(n),{className:this.props.dotsClass})},t}(l.default.Component)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0,t.NextArrow=t.PrevArrow=void 0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(0),u=r(l),c=n(6),p=r(c),f=n(128),d=(r(f),n(73));t.PrevArrow=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return a(t,e),t.prototype.clickHandler=function(e,t){t&&t.preventDefault(),this.props.clickHandler(e,t)},t.prototype.render=function(){var e={"slick-arrow":!0,"slick-prev":!0},t=this.clickHandler.bind(this,{message:"previous"});!this.props.infinite&&(0===this.props.currentSlide||this.props.slideCount<=this.props.slidesToShow)&&(e["slick-disabled"]=!0,t=null);var n={key:"0","data-role":"none",className:(0,p.default)(e),style:{display:"block"},onClick:t},r={currentSlide:this.props.currentSlide,slideCount:this.props.slideCount};return this.props.prevArrow?u.default.cloneElement(this.props.prevArrow,s({},n,r)):u.default.createElement("button",s({key:"0",type:"button"},n)," Previous")},t}(u.default.Component),t.NextArrow=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return a(t,e),t.prototype.clickHandler=function(e,t){t&&t.preventDefault(),this.props.clickHandler(e,t)},t.prototype.render=function(){var e={"slick-arrow":!0,"slick-next":!0},t=this.clickHandler.bind(this,{message:"next"});(0,d.canGoNext)(this.props)||(e["slick-disabled"]=!0,t=null);var n={key:"1","data-role":"none",className:(0,p.default)(e),style:{display:"block"},onClick:t},r={currentSlide:this.props.currentSlide,slideCount:this.props.slideCount};return this.props.nextArrow?u.default.cloneElement(this.props.nextArrow,s({},n,r)):u.default.createElement("button",s({key:"1",type:"button"},n)," Next")},t}(u.default.Component)},function(e,t,n){var r=n(332),o=function(e){return/[height|width]$/.test(e)},i=function(e){var t="",n=Object.keys(e);return n.forEach(function(i,a){var s=e[i];i=r(i),o(i)&&"number"==typeof s&&(s+="px"),t+=!0===s?i:!1===s?"not "+i:"("+i+": "+s+")",a<n.length-1&&(t+=" and ")}),t},a=function(e){var t="";return"string"==typeof e?e:e instanceof Array?(e.forEach(function(n,r){t+=i(n),r<e.length-1&&(t+=", ")}),t):i(e)};e.exports=a},function(e,t){var n=function(e){return e.replace(/[A-Z]/g,function(e){return"-"+e.toLowerCase()}).toLowerCase()};e.exports=n},function(e,t){var n=!("undefined"==typeof window||!window.document||!window.document.createElement);e.exports=n},function(e,t,n){function r(){if(!window.matchMedia)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!window.matchMedia("only all").matches}var o=n(335),i=n(187),a=i.each,s=i.isFunction,l=i.isArray;r.prototype={constructor:r,register:function(e,t,n){var r=this.queries,i=n&&this.browserIsIncapable;return r[e]||(r[e]=new o(e,i)),s(t)&&(t={match:t}),l(t)||(t=[t]),a(t,function(t){s(t)&&(t={match:t}),r[e].addHandler(t)}),this},unregister:function(e,t){var n=this.queries[e];return n&&(t?n.removeHandler(t):(n.clear(),delete this.queries[e])),this}},e.exports=r},function(e,t,n){function r(e,t){this.query=e,this.isUnconditional=t,this.handlers=[],this.mql=window.matchMedia(e);var n=this;this.listener=function(e){n.mql=e.currentTarget||e,n.assess()},this.mql.addListener(this.listener)}var o=n(336),i=n(187).each;r.prototype={constuctor:r,addHandler:function(e){var t=new o(e);this.handlers.push(t),this.matches()&&t.on()},removeHandler:function(e){var t=this.handlers;i(t,function(n,r){if(n.equals(e))return n.destroy(),!t.splice(r,1)})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){i(this.handlers,function(e){e.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var e=this.matches()?"on":"off";i(this.handlers,function(t){t[e]()})}},e.exports=r},function(e,t){function n(e){this.options=e,!e.deferSetup&&this.setup()}n.prototype={constructor:n,setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(e){return this.options===e||this.options.match===e}},e.exports=n},function(e,t){e.exports=function(e,t){if(e===t)return!0;var n=e.length;if(t.length!==n)return!1;for(var r=0;r<n;r++)if(e[r]!==t[r])return!1;return!0}},function(e,t,n){!function(t,n){e.exports=n()}(0,function(){"use strict";function e(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r=e||[],o=[],i=0;do{var a=r.filter(function(e){return t(e,i)})[0];if(!a)break;o.push(a),r=a[n.childrenKeyName]||[],i+=1}while(r.length>0);return o}return e})},function(e,t){function n(e,t){return null!=e&&o.call(e,t)}var r=Object.prototype,o=r.hasOwnProperty;e.exports=n},function(e,t,n){var r=n(341),o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,a=r(function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(o,function(e,n,r,o){t.push(r?o.replace(i,"$1"):n||e)}),t});e.exports=a},function(e,t,n){function r(e){var t=o(e,function(e){return n.size===i&&n.clear(),e}),n=t.cache;return t}var o=n(342),i=500;e.exports=r},function(e,t,n){function r(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(i);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a)||i,a};return n.cache=new(r.Cache||o),n}var o=n(132),i="Expected a function";r.Cache=o,e.exports=r},function(e,t,n){function r(){this.size=0,this.__data__={hash:new o,map:new(a||i),string:new o}}var o=n(344),i=n(93),a=n(134);e.exports=r},function(e,t,n){function r(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(345),i=n(350),a=n(351),s=n(352),l=n(353);r.prototype.clear=o,r.prototype.delete=i,r.prototype.get=a,r.prototype.has=s,r.prototype.set=l,e.exports=r},function(e,t,n){function r(){this.__data__=o?o(null):{},this.size=0}var o=n(92);e.exports=r},function(e,t,n){function r(e){return!(!a(e)||i(e))&&(o(e)?h:u).test(s(e))}var o=n(133),i=n(347),a=n(32),s=n(191),l=/[\\^$.*+?()[\]{}|]/g,u=/^\[object .+?Constructor\]$/,c=Function.prototype,p=Object.prototype,f=c.toString,d=p.hasOwnProperty,h=RegExp("^"+f.call(d).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){function r(e){return!!i&&i in e}var o=n(348),i=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=r},function(e,t,n){var r=n(33),o=r["__core-js_shared__"];e.exports=o},function(e,t){function n(e,t){return null==e?void 0:e[t]}e.exports=n},function(e,t){function n(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}e.exports=n},function(e,t,n){function r(e){var t=this.__data__;if(o){var n=t[e];return n===i?void 0:n}return s.call(t,e)?t[e]:void 0}var o=n(92),i="__lodash_hash_undefined__",a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){var t=this.__data__;return o?void 0!==t[e]:a.call(t,e)}var o=n(92),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=o&&void 0===t?i:t,this}var o=n(92),i="__lodash_hash_undefined__";e.exports=r},function(e,t){function n(){this.__data__=[],this.size=0}e.exports=n},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);return!(n<0)&&(n==t.length-1?t.pop():a.call(t,n,1),--this.size,!0)}var o=n(94),i=Array.prototype,a=i.splice;e.exports=r},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);return n<0?void 0:t[n][1]}var o=n(94);e.exports=r},function(e,t,n){function r(e){return o(this.__data__,e)>-1}var o=n(94);e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__,r=o(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var o=n(94);e.exports=r},function(e,t,n){function r(e){var t=o(this,e).delete(e);return this.size-=t?1:0,t}var o=n(95);e.exports=r},function(e,t){function n(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=n},function(e,t,n){function r(e){return o(this,e).get(e)}var o=n(95);e.exports=r},function(e,t,n){function r(e){return o(this,e).has(e)}var o=n(95);e.exports=r},function(e,t,n){function r(e,t){var n=o(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var o=n(95);e.exports=r},function(e,t,n){function r(e){return null==e?"":o(e)}var o=n(365);e.exports=r},function(e,t,n){function r(e){if("string"==typeof e)return e;if(a(e))return i(e,r)+"";if(s(e))return c?c.call(e):"";var t=e+"";return"0"==t&&1/e==-l?"-0":t}var o=n(72),i=n(192),a=n(37),s=n(91),l=1/0,u=o?o.prototype:void 0,c=u?u.toString:void 0;e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e)==a}var o=n(52),i=n(43),a="[object Arguments]";e.exports=r},function(e,t,n){function r(e,t,n,r){if(!s(e))return e;t=i(t,e);for(var u=-1,c=t.length,p=c-1,f=e;null!=f&&++u<c;){var d=l(t[u]),h=n;if(u!=p){var v=f[d];h=r?r(v,d,f):void 0,void 0===h&&(h=s(v)?v:a(t[u+1])?[]:{})}o(f,d,h),f=f[d]}return e}var o=n(195),i=n(130),a=n(96),s=n(32),l=n(75);e.exports=r},function(e,t,n){e.exports=n(369)},function(e,t,n){"use strict";function r(){}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n.n(o),a=n(8),s=n.n(a),l=n(17),u=n.n(l),c=n(2),p=n.n(c),f=n(7),d=n.n(f),h=n(3),v=n.n(h),m=n(4),y=n.n(m),g=n(0),b=n.n(g),C=n(5),w=n.n(C),S=n(6),x=function(e){function t(e){p()(this,t);var n=v()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));_.call(n);var r=!1;return r="checked"in e?!!e.checked:!!e.defaultChecked,n.state={checked:r},n}return y()(t,e),d()(t,[{key:"componentDidMount",value:function(){var e=this.props,t=e.autoFocus,n=e.disabled;t&&!n&&this.focus()}},{key:"componentWillReceiveProps",value:function(e){"checked"in e&&this.setState({checked:!!e.checked})}},{key:"setChecked",value:function(e){this.props.disabled||("checked"in this.props||this.setState({checked:e}),this.props.onChange(e))}},{key:"focus",value:function(){this.node.focus()}},{key:"blur",value:function(){this.node.blur()}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=t.prefixCls,o=t.disabled,a=t.checkedChildren,l=t.tabIndex,c=t.unCheckedChildren,p=u()(t,["className","prefixCls","disabled","checkedChildren","tabIndex","unCheckedChildren"]),f=this.state.checked,d=o?-1:l||0,h=S((e={},s()(e,n,!!n),s()(e,r,!0),s()(e,r+"-checked",f),s()(e,r+"-disabled",o),e));return b.a.createElement("span",i()({},p,{className:h,tabIndex:d,ref:this.saveNode,onKeyDown:this.handleKeyDown,onClick:this.toggle,onMouseUp:this.handleMouseUp}),b.a.createElement("span",{className:r+"-inner"},f?a:c))}}]),t}(g.Component),_=function(){var e=this;this.toggle=function(){var t=e.props.onClick,n=!e.state.checked;e.setChecked(n),t(n)},this.handleKeyDown=function(t){37===t.keyCode?e.setChecked(!1):39===t.keyCode?e.setChecked(!0):32!==t.keyCode&&13!==t.keyCode||e.toggle()},this.handleMouseUp=function(t){e.node&&e.node.blur(),e.props.onMouseUp&&e.props.onMouseUp(t)},this.saveNode=function(t){e.node=t}};x.propTypes={className:w.a.string,prefixCls:w.a.string,disabled:w.a.bool,checkedChildren:w.a.any,unCheckedChildren:w.a.any,onChange:w.a.func,onMouseUp:w.a.func,onClick:w.a.func,tabIndex:w.a.number,checked:w.a.bool,defaultChecked:w.a.bool,autoFocus:w.a.bool},x.defaultProps={prefixCls:"rc-switch",checkedChildren:null,unCheckedChildren:null,className:"",defaultChecked:!1,onChange:r,onClick:r},t.default=x},function(e,t,n){"use strict";var r=n(371),o=n(412);n.n(o);t.default=r.a},function(e,t,n){"use strict";function r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"vertical";if("undefined"==typeof document||"undefined"==typeof window)return 0;if(U)return U;var t=document.createElement("div");for(var n in q)q.hasOwnProperty(n)&&(t.style[n]=q[n]);document.body.appendChild(t);var r=0;return"vertical"===e?r=t.offsetWidth-t.clientWidth:"horizontal"===e&&(r=t.offsetHeight-t.clientHeight),document.body.removeChild(t),U=r}function o(e,t,n){function r(){var r=this,i=arguments;i[0]&&i[0].persist&&i[0].persist();var a=function(){o=null,n||e.apply(r,i)},s=n&&!o;clearTimeout(o),o=setTimeout(a,t),s&&e.apply(r,i)}var o=void 0;return r.cancel=function(){o&&(clearTimeout(o),o=null)},r}function i(e,t,n){Y[t]||(H()(e,t,n),Y[t]=!e)}function a(e,t){var n=e.indexOf(t),r=e.slice(0,n),o=e.slice(n+1,e.length);return r.concat(o)}function s(e,t){var n=t.table,r=n.props,o=r.prefixCls,i=r.expandIconAsCell,a=e.fixed,s=[];i&&"right"!==a&&s.push(K.a.createElement("col",{className:o+"-expand-icon-col",key:"rc-table-expand-icon-col"}));var l=void 0;return l="left"===a?n.columnManager.leftLeafColumns():"right"===a?n.columnManager.rightLeafColumns():n.columnManager.leafColumns(),s=s.concat(l.map(function(e){return K.a.createElement("col",{key:e.key||e.dataIndex,style:{width:e.width,minWidth:e.width}})})),K.a.createElement("colgroup",null,s)}function l(e){var t=e.row,n=e.index,r=e.height,o=e.components,i=e.onHeaderRow,a=o.header.row,s=o.header.cell,l=i(t.map(function(e){return e.column}),n),u=l?l.style:{},c=T()({height:r},u);return K.a.createElement(a,T()({},l,{style:c}),t.map(function(e,t){var n=e.column,r=ie()(e,["column"]),o=n.onHeaderCell?n.onHeaderCell(n):{};return n.align&&(r.style={textAlign:n.align}),K.a.createElement(s,T()({},r,o,{key:n.key||n.dataIndex||t}))}))}function u(e,t){var n=e.fixedColumnsHeadRowsHeight,r=t.columns,o=t.rows,i=t.fixed,a=n[0];return i&&a&&r?"auto"===a?"auto":a/o.length:null}function c(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments[2];return n=n||[],n[t]=n[t]||[],e.forEach(function(e){if(e.rowSpan&&n.length<e.rowSpan)for(;n.length<e.rowSpan;)n.push([]);var r={key:e.key,className:e.className||"",children:e.title,column:e};e.children&&c(e.children,t+1,n),"colSpan"in e&&(r.colSpan=e.colSpan),"rowSpan"in e&&(r.rowSpan=e.rowSpan),0!==r.colSpan&&n[t].push(r)}),n.filter(function(e){return e.length>0})}function p(e,t){var n=t.table,r=n.components,o=n.props,i=o.prefixCls,a=o.showHeader,s=o.onHeaderRow,l=e.expander,u=e.columns,p=e.fixed;if(!a)return null;var f=c(u);l.renderExpandIndentCell(f,p);var d=r.header.wrapper;return K.a.createElement(d,{className:i+"-thead"},f.map(function(e,t){return K.a.createElement(ae,{key:t,index:t,fixed:p,columns:u,rows:f,row:e,components:r,onHeaderRow:s})}))}function f(e,t){var n=e.expandedRowsHeight,r=e.fixedColumnsBodyRowsHeight,o=t.fixed,i=t.index,a=t.rowKey;return o?n[a]?n[a]:r[i]?r[i]:null:null}function d(e,t){var n=t.table,o=n.props,i=o.prefixCls,a=o.scroll,s=o.showHeader,l=e.columns,u=e.fixed,c=e.tableClassName,p=e.handleBodyScrollLeft,f=e.expander,d=n.saveRef,h=n.props.useFixedHeader,v={};if(a.y){h=!0;var m=r("horizontal");m>0&&!u&&(v.marginBottom="-"+m+"px",v.paddingBottom="0px")}return h&&s?K.a.createElement("div",{key:"headTable",ref:u?null:d("headTable"),className:i+"-header",style:v,onScroll:p},K.a.createElement(ge,{tableClassName:c,hasHead:!0,hasBody:!1,fixed:u,columns:l,expander:f})):null}function h(e,t){var n=t.table,o=n.props,i=o.prefixCls,a=o.scroll,s=e.columns,l=e.fixed,u=e.tableClassName,c=e.getRowKey,p=e.handleBodyScroll,f=e.expander,d=e.isAnyColumnsFixed,h=n.saveRef,v=n.props.useFixedHeader,m=T()({},n.props.bodyStyle),y={};if((a.x||l)&&(m.overflowX=m.overflowX||"auto",m.WebkitTransform="translate3d (0, 0, 0)"),a.y){l?(y.maxHeight=m.maxHeight||a.y,y.overflowY=m.overflowY||"scroll"):m.maxHeight=m.maxHeight||a.y,m.overflowY=m.overflowY||"scroll",v=!0;var g=r();g>0&&l&&(m.marginBottom="-"+g+"px",m.paddingBottom="0px")}var b=K.a.createElement(ge,{tableClassName:u,hasHead:!v,hasBody:!0,fixed:l,columns:s,expander:f,getRowKey:c,isAnyColumnsFixed:d});if(l&&s.length){var C=void 0;return"left"===s[0].fixed||!0===s[0].fixed?C="fixedColumnsBodyLeft":"right"===s[0].fixed&&(C="fixedColumnsBodyRight"),delete m.overflowX,delete m.overflowY,K.a.createElement("div",{key:"bodyTable",className:i+"-body-outer",style:T()({},m)},K.a.createElement("div",{className:i+"-body-inner",style:y,ref:h(C),onScroll:p},b))}return K.a.createElement("div",{key:"bodyTable",className:i+"-body",style:m,ref:h("bodyTable"),onScroll:p},b)}function v(e){function t(e){o=T()({},o,e);for(var t=0;t<i.length;t++)i[t]()}function n(){return o}function r(e){return i.push(e),function(){var t=i.indexOf(e);i.splice(t,1)}}var o=e,i=[];return{setState:t,getState:n,subscribe:r}}function m(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"tr";return function(t){function n(e){P()(this,n);var t=A()(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));t.store=e.store;var r=t.store.getState(),o=r.selectedRowKeys;return t.state={selected:o.indexOf(e.rowKey)>=0},t}return R()(n,t),D()(n,[{key:"componentDidMount",value:function(){this.subscribe()}},{key:"componentWillUnmount",value:function(){this.unsubscribe&&this.unsubscribe()}},{key:"subscribe",value:function(){var e=this,t=this.props,n=t.store,r=t.rowKey;this.unsubscribe=n.subscribe(function(){var t=e.store.getState(),n=t.selectedRowKeys,o=n.indexOf(r)>=0;o!==e.state.selected&&e.setState({selected:o})})}},{key:"render",value:function(){var t=Object(nt.a)(this.props,["prefixCls","rowKey","store"]),n=Pe()(this.props.className,E()({},this.props.prefixCls+"-row-selected",this.state.selected));return L.createElement(e,T()({},t,{className:n}),this.props.children)}}]),n}(L.Component)}function y(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"children",n=[];return function e(r){r.forEach(function(r){if(r[t]){var o=T()({},r);delete o[t],n.push(o),r[t].length>0&&e(r[t])}else n.push(r)})}(e),n}function g(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"children";return e.map(function(e,r){var o={};return e[n]&&(o[n]=g(e[n],t,n)),T()({},t(e,r),o)})}function b(e,t){return e.reduce(function(e,n){if(t(n)&&e.push(n),n.children){var r=b(n.children,t);e.push.apply(e,ot()(r))}return e},[])}function C(e){var t=[];return L.Children.forEach(e,function(e){if(L.isValidElement(e)){var n=T()({},e.props);e.key&&(n.key=e.key),e.type&&e.type.__ANT_TABLE_COLUMN_GROUP&&(n.children=C(n.children)),t.push(n)}}),t}function w(){}function S(e){e.stopPropagation(),e.nativeEvent.stopImmediatePropagation&&e.nativeEvent.stopImmediatePropagation()}var x=n(19),_=n.n(x),k=n(8),E=n.n(k),O=n(1),T=n.n(O),N=n(2),P=n.n(N),M=n(7),D=n.n(M),I=n(3),A=n.n(I),j=n(4),R=n.n(j),L=n(0),K=n.n(L),F=n(9),V=n.n(F),z=n(5),B=n.n(z),W=n(36),H=n.n(W),U=void 0,q={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"},Y={},G=n(31),X=n.n(G),$=n(35),J=n(64),Z=n(375),Q=n.n(Z),ee=function(){function e(t,n){P()(this,e),this._cached={},this.columns=t||this.normalize(n)}return e.prototype.isAnyColumnsFixed=function(){var e=this;return this._cache("isAnyColumnsFixed",function(){return e.columns.some(function(e){return!!e.fixed})})},e.prototype.isAnyColumnsLeftFixed=function(){var e=this;return this._cache("isAnyColumnsLeftFixed",function(){return e.columns.some(function(e){return"left"===e.fixed||!0===e.fixed})})},e.prototype.isAnyColumnsRightFixed=function(){var e=this;return this._cache("isAnyColumnsRightFixed",function(){return e.columns.some(function(e){return"right"===e.fixed})})},e.prototype.leftColumns=function(){var e=this;return this._cache("leftColumns",function(){return e.groupedColumns().filter(function(e){return"left"===e.fixed||!0===e.fixed})})},e.prototype.rightColumns=function(){var e=this;return this._cache("rightColumns",function(){return e.groupedColumns().filter(function(e){return"right"===e.fixed})})},e.prototype.leafColumns=function(){var e=this;return this._cache("leafColumns",function(){return e._leafColumns(e.columns)})},e.prototype.leftLeafColumns=function(){var e=this;return this._cache("leftLeafColumns",function(){return e._leafColumns(e.leftColumns())})},e.prototype.rightLeafColumns=function(){var e=this;return this._cache("rightLeafColumns",function(){return e._leafColumns(e.rightColumns())})},e.prototype.groupedColumns=function(){var e=this;return this._cache("groupedColumns",function(){return function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];o[n]=o[n]||[];var i=[],a=function(e){var t=o.length-n;e&&!e.children&&t>1&&(!e.rowSpan||e.rowSpan<t)&&(e.rowSpan=t)};return t.forEach(function(s,l){var u=T()({},s);o[n].push(u),r.colSpan=r.colSpan||0,u.children&&u.children.length>0?(u.children=e(u.children,n+1,u,o),r.colSpan=r.colSpan+u.colSpan):r.colSpan++;for(var c=0;c<o[n].length-1;++c)a(o[n][c]);l+1===t.length&&a(u),i.push(u)}),i}(e.columns)})},e.prototype.normalize=function(e){var t=this,n=[];return K.a.Children.forEach(e,function(e){if(K.a.isValidElement(e)){var r=T()({},e.props);e.key&&(r.key=e.key),e.type.isTableColumnGroup&&(r.children=t.normalize(r.children)),n.push(r)}}),n},e.prototype.reset=function(e,t){this.columns=e||this.normalize(t),this._cached={}},e.prototype._cache=function(e,t){return e in this._cached?this._cached[e]:(this._cached[e]=t(),this._cached[e])},e.prototype._leafColumns=function(e){var t=this,n=[];return e.forEach(function(e){e.children?n.push.apply(n,t._leafColumns(e.children)):n.push(e)}),n},e}(),te=ee,ne=n(119),re=n.n(ne);s.propTypes={fixed:B.a.string},s.contextTypes={table:B.a.any};var oe=n(17),ie=n.n(oe),ae=Object(J.connect)(function(e,t){return{height:u(e,t)}})(l);p.propTypes={fixed:B.a.string,columns:B.a.array.isRequired,expander:B.a.object.isRequired,onHeaderRow:B.a.func},p.contextTypes={table:B.a.any};var se=n(137),le=n.n(se),ue=function(e){function t(){var n,r,o;P()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=A()(this,e.call.apply(e,[this].concat(a))),r.handleClick=function(e){var t=r.props,n=t.record,o=t.column.onCellClick;o&&o(n,e)},o=n,A()(r,o)}return R()(t,e),t.prototype.isInvalidRenderCellText=function(e){return e&&!K.a.isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)},t.prototype.render=function(){var e=this.props,t=e.record,n=e.indentSize,r=e.prefixCls,o=e.indent,i=e.index,a=e.expandIcon,s=e.column,l=e.component,u=s.dataIndex,c=s.render,p=s.className,f=void 0===p?"":p,d=void 0;d="number"==typeof u?le()(t,u):u&&0!==u.length?le()(t,u):t;var h={},v=void 0,m=void 0;c&&(d=c(d,t,i),this.isInvalidRenderCellText(d)&&(h=d.props||h,v=h.colSpan,m=h.rowSpan,d=d.children)),s.onCell&&(h=T()({},h,s.onCell(t))),this.isInvalidRenderCellText(d)&&(d=null);var y=a?K.a.createElement("span",{style:{paddingLeft:n*o+"px"},className:r+"-indent indent-level-"+o}):null;return 0===m||0===v?null:(s.align&&(h.style={textAlign:s.align}),K.a.createElement(l,T()({className:f,onClick:this.handleClick},h),y,a,d))},t}(K.a.Component);ue.propTypes={record:B.a.object,prefixCls:B.a.string,index:B.a.number,indent:B.a.number,indentSize:B.a.number,column:B.a.object,expandIcon:B.a.node,component:B.a.any};var ce=ue,pe=function(e){function t(n){P()(this,t);var r=A()(this,e.call(this,n));return r.onRowClick=function(e){var t=r.props,n=t.record,o=t.index,i=t.onRowClick;i&&i(n,o,e)},r.onRowDoubleClick=function(e){var t=r.props,n=t.record,o=t.index,i=t.onRowDoubleClick;i&&i(n,o,e)},r.onContextMenu=function(e){var t=r.props,n=t.record,o=t.index,i=t.onRowContextMenu;i&&i(n,o,e)},r.onMouseEnter=function(e){var t=r.props,n=t.record,o=t.index,i=t.onRowMouseEnter;(0,t.onHover)(!0,t.rowKey),i&&i(n,o,e)},r.onMouseLeave=function(e){var t=r.props,n=t.record,o=t.index,i=t.onRowMouseLeave;(0,t.onHover)(!1,t.rowKey),i&&i(n,o,e)},r.shouldRender=n.visible,r}return R()(t,e),t.prototype.componentDidMount=function(){this.shouldRender&&this.saveRowRef()},t.prototype.componentWillReceiveProps=function(e){(this.props.visible||!this.props.visible&&e.visible)&&(this.shouldRender=!0)},t.prototype.shouldComponentUpdate=function(e){return!(!this.props.visible&&!e.visible)},t.prototype.componentDidUpdate=function(){this.shouldRender&&!this.rowRef&&this.saveRowRef()},t.prototype.setExpanedRowHeight=function(){var e,t=this.props,n=t.store,r=t.rowKey,o=n.getState(),i=o.expandedRowsHeight,a=this.rowRef.getBoundingClientRect().height;i=T()({},i,(e={},e[r]=a,e)),n.setState({expandedRowsHeight:i})},t.prototype.setRowHeight=function(){var e=this.props,t=e.store,n=e.index,r=t.getState().fixedColumnsBodyRowsHeight.slice(),o=this.rowRef.getBoundingClientRect().height;r[n]=o,t.setState({fixedColumnsBodyRowsHeight:r})},t.prototype.getStyle=function(){var e=this.props,t=e.height,n=e.visible;return t&&t!==this.style.height&&(this.style=T()({},this.style,{height:t})),n||this.style.display||(this.style=T()({},this.style,{display:"none"})),this.style},t.prototype.saveRowRef=function(){this.rowRef=V.a.findDOMNode(this);var e=this.props,t=e.isAnyColumnsFixed,n=e.fixed,r=e.expandedRow,o=e.ancestorKeys;t&&(!n&&r&&this.setExpanedRowHeight(),!n&&o.length>=0&&this.setRowHeight())},t.prototype.render=function(){if(!this.shouldRender)return null;var e=this.props,t=e.prefixCls,n=e.columns,r=e.record,o=e.index,a=e.onRow,s=e.indent,l=e.indentSize,u=e.hovered,c=e.height,p=e.visible,f=e.components,d=e.hasExpandIcon,h=e.renderExpandIcon,v=e.renderExpandIconCell,m=f.body.row,y=f.body.cell,g=this.props.className;u&&(g+=" "+t+"-hover");var b=[];v(b);for(var C=0;C<n.length;C++){var w=n[C];i(void 0===w.onCellClick,"column[onCellClick] is deprecated, please use column[onCell] instead."),b.push(K.a.createElement(ce,{prefixCls:t,record:r,indentSize:l,indent:s,index:o,column:w,key:w.key||w.dataIndex,expandIcon:d(C)&&h(),component:y}))}var S=(t+" "+g+" "+t+"-level-"+s).trim(),x=a(r,o),_=x?x.style:{},k={height:c};return p||(k.display="none"),k=T()({},k,_),K.a.createElement(m,T()({onClick:this.onRowClick,onDoubleClick:this.onRowDoubleClick,onMouseEnter:this.onMouseEnter,onMouseLeave:this.onMouseLeave,onContextMenu:this.onContextMenu,className:S},x,{style:k}),b)},t}(K.a.Component);pe.propTypes={onRow:B.a.func,onRowClick:B.a.func,onRowDoubleClick:B.a.func,onRowContextMenu:B.a.func,onRowMouseEnter:B.a.func,onRowMouseLeave:B.a.func,record:B.a.object,prefixCls:B.a.string,onHover:B.a.func,columns:B.a.array,height:B.a.oneOfType([B.a.string,B.a.number]),index:B.a.number,rowKey:B.a.oneOfType([B.a.string,B.a.number]).isRequired,className:B.a.string,indent:B.a.number,indentSize:B.a.number,hasExpandIcon:B.a.func.isRequired,hovered:B.a.bool.isRequired,visible:B.a.bool.isRequired,store:B.a.object.isRequired,fixed:B.a.oneOfType([B.a.string,B.a.bool]),renderExpandIcon:B.a.func,renderExpandIconCell:B.a.func,components:B.a.any,expandedRow:B.a.bool,isAnyColumnsFixed:B.a.bool,ancestorKeys:B.a.array.isRequired},pe.defaultProps={onRow:function(){},expandIconColumnIndex:0,expandRowByClick:!1,onHover:function(){},hasExpandIcon:function(){},renderExpandIcon:function(){},renderExpandIconCell:function(){}};var fe=Object(J.connect)(function(e,t){var n=e.currentHoverKey,r=e.expandedRowKeys,o=t.rowKey,i=t.ancestorKeys;return{visible:0===i.length||i.every(function(e){return~r.indexOf(e)}),hovered:n===o,height:f(e,t)}})(pe),de=function(e){function t(){return P()(this,t),A()(this,e.apply(this,arguments))}return R()(t,e),t.prototype.shouldComponentUpdate=function(e){return!X()(e,this.props)},t.prototype.render=function(){var e=this.props,t=e.expandable,n=e.prefixCls,r=e.onExpand,o=e.needIndentSpaced,i=e.expanded,a=e.record;if(t){var s=i?"expanded":"collapsed";return K.a.createElement("span",{className:n+"-expand-icon "+n+"-"+s,onClick:function(e){return r(a,e)}})}return o?K.a.createElement("span",{className:n+"-expand-icon "+n+"-spaced"}):null},t}(K.a.Component);de.propTypes={record:B.a.object,prefixCls:B.a.string,expandable:B.a.any,expanded:B.a.bool,needIndentSpaced:B.a.bool,onExpand:B.a.func};var he=de,ve=function(e){function t(){var n,r,o;P()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=A()(this,e.call.apply(e,[this].concat(a))),r.hasExpandIcon=function(e){var t=r.props.expandRowByClick;return!r.expandIconAsCell&&!t&&e===r.expandIconColumnIndex},r.handleExpandChange=function(e,t){var n=r.props,o=n.onExpandedChange,i=n.expanded,a=n.rowKey;r.expandable&&o(!i,e,t,a)},r.handleRowClick=function(e,t,n){var o=r.props,i=o.expandRowByClick,a=o.onRowClick;i&&r.handleExpandChange(e,n),a&&a(e,t,n)},r.renderExpandIcon=function(){var e=r.props,t=e.prefixCls,n=e.expanded,o=e.record,i=e.needIndentSpaced;return K.a.createElement(he,{expandable:r.expandable,prefixCls:t,onExpand:r.handleExpandChange,needIndentSpaced:i,expanded:n,record:o})},r.renderExpandIconCell=function(e){if(r.expandIconAsCell){var t=r.props.prefixCls;e.push(K.a.createElement("td",{className:t+"-expand-icon-cell",key:"rc-table-expand-icon-cell"},r.renderExpandIcon()))}},o=n,A()(r,o)}return R()(t,e),t.prototype.componentWillUnmount=function(){this.handleDestroy()},t.prototype.handleDestroy=function(){var e=this.props,t=e.onExpandedChange,n=e.rowKey,r=e.record;this.expandable&&t(!1,r,null,n,!0)},t.prototype.render=function(){var e=this.props,t=e.childrenColumnName,n=e.expandedRowRender,r=e.indentSize,o=e.record,i=e.fixed;this.expandIconAsCell="right"!==i&&this.props.expandIconAsCell,this.expandIconColumnIndex="right"!==i?this.props.expandIconColumnIndex:-1;var a=o[t];this.expandable=!(!a&&!n);var s={indentSize:r,onRowClick:this.handleRowClick,hasExpandIcon:this.hasExpandIcon,renderExpandIcon:this.renderExpandIcon,renderExpandIconCell:this.renderExpandIconCell};return this.props.children(s)},t}(K.a.Component);ve.propTypes={prefixCls:B.a.string.isRequired,rowKey:B.a.oneOfType([B.a.string,B.a.number]).isRequired,fixed:B.a.oneOfType([B.a.string,B.a.bool]),record:B.a.object.isRequired,indentSize:B.a.number,needIndentSpaced:B.a.bool.isRequired,expandRowByClick:B.a.bool,expanded:B.a.bool.isRequired,expandIconAsCell:B.a.bool,expandIconColumnIndex:B.a.number,childrenColumnName:B.a.string,expandedRowRender:B.a.func,onExpandedChange:B.a.func.isRequired,onRowClick:B.a.func,children:B.a.func.isRequired};var me=Object(J.connect)(function(e,t){var n=e.expandedRowKeys,r=t.rowKey;return{expanded:!!~n.indexOf(r)}})(ve),ye=function(e){function t(){var n,r,o;P()(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=A()(this,e.call.apply(e,[this].concat(a))),r.handleRowHover=function(e,t){r.props.store.setState({currentHoverKey:e?t:null})},r.renderRows=function(e,t){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],o=r.context.table,i=o.columnManager,a=o.components,s=o.props,l=s.prefixCls,u=s.childrenColumnName,c=s.rowClassName,p=s.rowRef,f=s.onRowClick,d=s.onRowDoubleClick,h=s.onRowContextMenu,v=s.onRowMouseEnter,m=s.onRowMouseLeave,y=s.onRow,g=r.props,b=g.getRowKey,C=g.fixed,w=g.expander,S=g.isAnyColumnsFixed,x=[],_=0;_<e.length;_++)!function(o){var s=e[o],g=b(s,o),_="string"==typeof c?c:c(s,o,t),k={};i.isAnyColumnsFixed()&&(k.onHover=r.handleRowHover);var E=void 0;E="left"===C?i.leftLeafColumns():"right"===C?i.rightLeafColumns():i.leafColumns();var O=l+"-row",N=K.a.createElement(me,T()({},w.props,{fixed:C,index:o,prefixCls:O,record:s,key:g,rowKey:g,onRowClick:f,needIndentSpaced:w.needIndentSpaced,onExpandedChange:w.handleExpandChange}),function(e){return K.a.createElement(fe,T()({fixed:C,indent:t,className:_,record:s,index:o,prefixCls:O,childrenColumnName:u,columns:E,onRow:y,onRowDoubleClick:d,onRowContextMenu:h,onRowMouseEnter:v,onRowMouseLeave:m},k,{rowKey:g,ancestorKeys:n,ref:p(s,o,t),components:a,isAnyColumnsFixed:S},e))});x.push(N),w.renderRows(r.renderRows,x,s,o,t,C,g,n)}(_);return x},o=n,A()(r,o)}return R()(t,e),t.prototype.render=function(){var e=this.context.table,t=e.components,n=e.props,r=n.prefixCls,o=n.scroll,i=n.data,a=n.getBodyWrapper,l=this.props,u=l.expander,c=l.tableClassName,f=l.hasHead,d=l.hasBody,h=l.fixed,v=l.columns,m={};!h&&o.x&&(!0===o.x?m.tableLayout="fixed":m.width=o.x);var y=d?t.table:"table",g=t.body.wrapper,b=void 0;return d&&(b=K.a.createElement(g,{className:r+"-tbody"},this.renderRows(i,0)),a&&(b=a(b))),K.a.createElement(y,{className:c,style:m,key:"table"},K.a.createElement(s,{columns:v,fixed:h}),f&&K.a.createElement(p,{expander:u,columns:v,fixed:h}),b)},t}(K.a.Component);ye.propTypes={fixed:B.a.oneOfType([B.a.string,B.a.bool]),columns:B.a.array.isRequired,tableClassName:B.a.string.isRequired,hasHead:B.a.bool.isRequired,hasBody:B.a.bool.isRequired,store:B.a.object.isRequired,expander:B.a.object.isRequired,getRowKey:B.a.func,isAnyColumnsFixed:B.a.bool},ye.contextTypes={table:B.a.any};var ge=Object(J.connect)()(ye);d.propTypes={fixed:B.a.oneOfType([B.a.string,B.a.bool]),columns:B.a.array.isRequired,tableClassName:B.a.string.isRequired,handleBodyScrollLeft:B.a.func.isRequired,expander:B.a.object.isRequired},d.contextTypes={table:B.a.any},h.propTypes={fixed:B.a.oneOfType([B.a.string,B.a.bool]),columns:B.a.array.isRequired,tableClassName:B.a.string.isRequired,handleBodyScroll:B.a.func.isRequired,getRowKey:B.a.func.isRequired,expander:B.a.object.isRequired,isAnyColumnsFixed:B.a.bool},h.contextTypes={table:B.a.any};var be=function(e){function t(n){P()(this,t);var r=A()(this,e.call(this,n));Ce.call(r);var o=n.data,i=n.childrenColumnName,a=n.defaultExpandAllRows,s=n.expandedRowKeys,l=n.defaultExpandedRowKeys,u=n.getRowKey,c=[],p=[].concat(o);if(a)for(var f=0;f<p.length;f++){var d=p[f];c.push(u(d,f)),p=p.concat(d[i]||[])}else c=s||l;return r.columnManager=n.columnManager,r.store=n.store,r.store.setState({expandedRowsHeight:{},expandedRowKeys:c}),r}return R()(t,e),t.prototype.componentWillReceiveProps=function(e){"expandedRowKeys"in e&&this.store.setState({expandedRowKeys:e.expandedRowKeys})},t.prototype.renderExpandedRow=function(e,t,n,r,o,i,a){var s=this.props,l=s.prefixCls,u=s.expandIconAsCell,c=s.indentSize,p=void 0;p="left"===a?this.columnManager.leftLeafColumns().length:"right"===a?this.columnManager.rightLeafColumns().length:this.columnManager.leafColumns().length;var f=[{key:"extra-row",render:function(){return{props:{colSpan:p},children:"right"!==a?n(e,t,i):"&nbsp;"}}}];u&&"right"!==a&&f.unshift({key:"expand-icon-placeholder",render:function(){return null}});var d=o[o.length-1],h=d+"-extra-row",v={body:{row:"tr",cell:"td"}};return K.a.createElement(fe,{key:h,columns:f,className:r,rowKey:h,ancestorKeys:o,prefixCls:l+"-expanded-row",indentSize:c,indent:i,fixed:a,components:v,expandedRow:!0})},t.prototype.render=function(){var e=this.props,t=e.data,n=e.childrenColumnName,r=e.children,o=t.some(function(e){return e[n]});return r({props:this.props,needIndentSpaced:o,renderRows:this.renderRows,handleExpandChange:this.handleExpandChange,renderExpandIndentCell:this.renderExpandIndentCell})},t}(K.a.Component);be.propTypes={expandIconAsCell:B.a.bool,expandedRowKeys:B.a.array,expandedRowClassName:B.a.func,defaultExpandAllRows:B.a.bool,defaultExpandedRowKeys:B.a.array,expandIconColumnIndex:B.a.number,expandedRowRender:B.a.func,childrenColumnName:B.a.string,indentSize:B.a.number,onExpand:B.a.func,onExpandedRowsChange:B.a.func,columnManager:B.a.object.isRequired,store:B.a.object.isRequired,prefixCls:B.a.string.isRequired,data:B.a.array,children:B.a.func.isRequired},be.defaultProps={expandIconAsCell:!1,expandedRowClassName:function(){return""},expandIconColumnIndex:0,defaultExpandAllRows:!1,defaultExpandedRowKeys:[],childrenColumnName:"children",indentSize:15,onExpand:function(){},onExpandedRowsChange:function(){}};var Ce=function(){var e=this;this.handleExpandChange=function(t,n,r,o){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];r&&(r.preventDefault(),r.stopPropagation());var s=e.props,l=s.onExpandedRowsChange,u=s.onExpand,c=e.store.getState(),p=c.expandedRowKeys;if(t)p=[].concat(p,[o]);else{-1!==p.indexOf(o)&&(p=a(p,o))}e.props.expandedRowKeys||e.store.setState({expandedRowKeys:p}),l(p),i||u(t,n)},this.renderExpandIndentCell=function(t,n){var r=e.props,o=r.prefixCls;if(r.expandIconAsCell&&"right"!==n&&t.length){var i={key:"rc-table-expand-icon-cell",className:o+"-expand-icon-th",title:"",rowSpan:t.length};t[0].unshift(T()({},i,{column:i}))}},this.renderRows=function(t,n,r,o,i,a,s,l){var u=e.props,c=u.expandedRowClassName,p=u.expandedRowRender,f=u.childrenColumnName,d=r[f],h=[].concat(l,[s]),v=i+1;p&&n.push(e.renderExpandedRow(r,o,p,c(r,o,i),h,v,a)),d&&n.push.apply(n,t(d,v,h))}},we=Object(J.connect)()(be),Se=function(e){function t(n){P()(this,t);var r=A()(this,e.call(this,n));return r.getRowKey=function(e,t){var n=r.props.rowKey,o="function"==typeof n?n(e,t):e[n];return i(void 0!==o,"Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key."),void 0===o?t:o},r.handleWindowResize=function(){r.syncFixedTableRowHeight(),r.setScrollPositionClassName()},r.syncFixedTableRowHeight=function(){var e=r.tableNode.getBoundingClientRect();if(!(void 0!==e.height&&e.height<=0)){var t=r.props.prefixCls,n=r.headTable?r.headTable.querySelectorAll("thead"):r.bodyTable.querySelectorAll("thead"),o=r.bodyTable.querySelectorAll("."+t+"-row")||[],i=[].map.call(n,function(e){return e.getBoundingClientRect().height||"auto"}),a=[].map.call(o,function(e){return e.getBoundingClientRect().height||"auto"}),s=r.store.getState();X()(s.fixedColumnsHeadRowsHeight,i)&&X()(s.fixedColumnsBodyRowsHeight,a)||r.store.setState({fixedColumnsHeadRowsHeight:i,fixedColumnsBodyRowsHeight:a})}},r.handleBodyScrollLeft=function(e){if(e.currentTarget===e.target){var t=e.target,n=r.props.scroll,o=void 0===n?{}:n,i=r.headTable,a=r.bodyTable;t.scrollLeft!==r.lastScrollLeft&&o.x&&(t===a&&i?i.scrollLeft=t.scrollLeft:t===i&&a&&(a.scrollLeft=t.scrollLeft),r.setScrollPositionClassName()),r.lastScrollLeft=t.scrollLeft}},r.handleBodyScrollTop=function(e){var t=e.target,n=r.props.scroll,o=void 0===n?{}:n,i=r.headTable,a=r.bodyTable,s=r.fixedColumnsBodyLeft,l=r.fixedColumnsBodyRight;if(t.scrollTop!==r.lastScrollTop&&o.y&&t!==i){var u=t.scrollTop;s&&t!==s&&(s.scrollTop=u),l&&t!==l&&(l.scrollTop=u),a&&t!==a&&(a.scrollTop=u)}r.lastScrollTop=t.scrollTop},r.handleBodyScroll=function(e){r.handleBodyScrollLeft(e),r.handleBodyScrollTop(e)},r.saveRef=function(e){return function(t){r[e]=t}},["onRowClick","onRowDoubleClick","onRowContextMenu","onRowMouseEnter","onRowMouseLeave"].forEach(function(e){i(void 0===n[e],e+" is deprecated, please use onRow instead.")}),i(void 0===n.getBodyWrapper,"getBodyWrapper is deprecated, please use custom components instead."),r.columnManager=new te(n.columns,n.children),r.store=Object(J.create)({currentHoverKey:null,fixedColumnsHeadRowsHeight:[],fixedColumnsBodyRowsHeight:[]}),r.setScrollPosition("left"),r.debouncedWindowResize=o(r.handleWindowResize,150),r}return R()(t,e),t.prototype.getChildContext=function(){return{table:{props:this.props,columnManager:this.columnManager,saveRef:this.saveRef,components:Q()({table:"table",header:{wrapper:"thead",row:"tr",cell:"th"},body:{wrapper:"tbody",row:"tr",cell:"td"}},this.props.components)}}},t.prototype.componentDidMount=function(){this.columnManager.isAnyColumnsFixed()&&(this.handleWindowResize(),this.resizeEvent=Object($.a)(window,"resize",this.debouncedWindowResize))},t.prototype.componentWillReceiveProps=function(e){e.columns&&e.columns!==this.props.columns?this.columnManager.reset(e.columns):e.children!==this.props.children&&this.columnManager.reset(null,e.children)},t.prototype.componentDidUpdate=function(e){this.columnManager.isAnyColumnsFixed()&&(this.handleWindowResize(),this.resizeEvent||(this.resizeEvent=Object($.a)(window,"resize",this.debouncedWindowResize))),e.data.length>0&&0===this.props.data.length&&this.hasScrollX()&&this.resetScrollX()},t.prototype.componentWillUnmount=function(){this.resizeEvent&&this.resizeEvent.remove(),this.debouncedWindowResize&&this.debouncedWindowResize.cancel()},t.prototype.setScrollPosition=function(e){if(this.scrollPosition=e,this.tableNode){var t=this.props.prefixCls;"both"===e?re()(this.tableNode).remove(new RegExp("^"+t+"-scroll-position-.+$")).add(t+"-scroll-position-left").add(t+"-scroll-position-right"):re()(this.tableNode).remove(new RegExp("^"+t+"-scroll-position-.+$")).add(t+"-scroll-position-"+e)}},t.prototype.setScrollPositionClassName=function(){var e=this.bodyTable,t=0===e.scrollLeft,n=e.scrollLeft+1>=e.children[0].getBoundingClientRect().width-e.getBoundingClientRect().width;t&&n?this.setScrollPosition("both"):t?this.setScrollPosition("left"):n?this.setScrollPosition("right"):"middle"!==this.scrollPosition&&this.setScrollPosition("middle")},t.prototype.resetScrollX=function(){this.headTable&&(this.headTable.scrollLeft=0),this.bodyTable&&(this.bodyTable.scrollLeft=0)},t.prototype.hasScrollX=function(){var e=this.props.scroll;return"x"in(void 0===e?{}:e)},t.prototype.renderMainTable=function(){var e=this.props,t=e.scroll,n=e.prefixCls,r=this.columnManager.isAnyColumnsFixed(),o=r||t.x||t.y,i=[this.renderTable({columns:this.columnManager.groupedColumns(),isAnyColumnsFixed:r}),this.renderEmptyText(),this.renderFooter()];return o?K.a.createElement("div",{className:n+"-scroll"},i):i},t.prototype.renderLeftFixedTable=function(){var e=this.props.prefixCls;return K.a.createElement("div",{className:e+"-fixed-left"},this.renderTable({columns:this.columnManager.leftColumns(),fixed:"left"}))},t.prototype.renderRightFixedTable=function(){var e=this.props.prefixCls;return K.a.createElement("div",{className:e+"-fixed-right"},this.renderTable({columns:this.columnManager.rightColumns(),fixed:"right"}))},t.prototype.renderTable=function(e){var t=e.columns,n=e.fixed,r=e.isAnyColumnsFixed,o=this.props,i=o.prefixCls,a=o.scroll,s=void 0===a?{}:a,l=s.x||n?i+"-fixed":"";return[K.a.createElement(d,{key:"head",columns:t,fixed:n,tableClassName:l,handleBodyScrollLeft:this.handleBodyScrollLeft,expander:this.expander}),K.a.createElement(h,{key:"body",columns:t,fixed:n,tableClassName:l,getRowKey:this.getRowKey,handleBodyScroll:this.handleBodyScroll,expander:this.expander,isAnyColumnsFixed:r})]},t.prototype.renderTitle=function(){var e=this.props,t=e.title,n=e.prefixCls;return t?K.a.createElement("div",{className:n+"-title",key:"title"},t(this.props.data)):null},t.prototype.renderFooter=function(){var e=this.props,t=e.footer,n=e.prefixCls;return t?K.a.createElement("div",{className:n+"-footer",key:"footer"},t(this.props.data)):null},t.prototype.renderEmptyText=function(){var e=this.props,t=e.emptyText,n=e.prefixCls;if(e.data.length)return null;var r=n+"-placeholder";return K.a.createElement("div",{className:r,key:"emptyText"},"function"==typeof t?t():t)},t.prototype.render=function(){var e=this,t=this.props,n=t.prefixCls,r=t.prefixCls;t.className&&(r+=" "+t.className),(t.useFixedHeader||t.scroll&&t.scroll.y)&&(r+=" "+n+"-fixed-header"),"both"===this.scrollPosition?r+=" "+n+"-scroll-position-left "+n+"-scroll-position-right":r+=" "+n+"-scroll-position-"+this.scrollPosition;var o=this.columnManager.isAnyColumnsLeftFixed(),i=this.columnManager.isAnyColumnsRightFixed();return K.a.createElement(J.Provider,{store:this.store},K.a.createElement(we,T()({},t,{columnManager:this.columnManager,getRowKey:this.getRowKey}),function(a){return e.expander=a,K.a.createElement("div",{ref:e.saveRef("tableNode"),className:r,style:t.style,id:t.id},e.renderTitle(),K.a.createElement("div",{className:n+"-content"},e.renderMainTable(),o&&e.renderLeftFixedTable(),i&&e.renderRightFixedTable()))}))},t}(K.a.Component);Se.propTypes=T()({data:B.a.array,useFixedHeader:B.a.bool,columns:B.a.array,prefixCls:B.a.string,bodyStyle:B.a.object,style:B.a.object,rowKey:B.a.oneOfType([B.a.string,B.a.func]),rowClassName:B.a.oneOfType([B.a.string,B.a.func]),onRow:B.a.func,onHeaderRow:B.a.func,onRowClick:B.a.func,onRowDoubleClick:B.a.func,onRowContextMenu:B.a.func,onRowMouseEnter:B.a.func,onRowMouseLeave:B.a.func,showHeader:B.a.bool,title:B.a.func,id:B.a.string,footer:B.a.func,emptyText:B.a.oneOfType([B.a.node,B.a.func]),scroll:B.a.object,rowRef:B.a.func,getBodyWrapper:B.a.func,children:B.a.node,components:B.a.shape({table:B.a.any,header:B.a.shape({wrapper:B.a.any,row:B.a.any,cell:B.a.any}),body:B.a.shape({wrapper:B.a.any,row:B.a.any,cell:B.a.any})})},we.PropTypes),Se.childContextTypes={table:B.a.any,components:B.a.any},Se.defaultProps={data:[],useFixedHeader:!1,rowKey:"key",rowClassName:function(){return""},onRow:function(){},onHeaderRow:function(){},prefixCls:"rc-table",bodyStyle:{},style:{},showHeader:!0,scroll:{},rowRef:function(){return null},emptyText:function(){return"No Data"}};var xe=Se,_e=function(e){function t(){return P()(this,t),A()(this,e.apply(this,arguments))}return R()(t,e),t}(L.Component);_e.propTypes={className:B.a.string,colSpan:B.a.number,title:B.a.node,dataIndex:B.a.string,width:B.a.oneOfType([B.a.number,B.a.string]),fixed:B.a.oneOf([!0,"left","right"]),render:B.a.func,onCellClick:B.a.func,onCell:B.a.func,onHeaderCell:B.a.func};var ke=_e,Ee=function(e){function t(){return P()(this,t),A()(this,e.apply(this,arguments))}return R()(t,e),t}(L.Component);Ee.propTypes={title:B.a.node},Ee.isTableColumnGroup=!0;var Oe=Ee;xe.Column=ke,xe.ColumnGroup=Oe;var Te=xe,Ne=n(6),Pe=n.n(Ne),Me=n(140),De=n(14),Ie=n(139),Ae=n(26),je=n(46),Re=n(27),Le=n(61),Ke=n(410),Fe=n.n(Ke),Ve=n(129),ze=n(62),Be=n(90),We=function(e){return L.createElement("div",{className:e.className,onClick:e.onClick},e.children)},He=function(e){function t(e){P()(this,t);var n=A()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.setNeverShown=function(e){var t=F.findDOMNode(n);!!Fe()(t,".ant-table-scroll")&&(n.neverShown=!!e.fixed)},n.setSelectedKeys=function(e){var t=e.selectedKeys;n.setState({selectedKeys:t})},n.handleClearFilters=function(){n.setState({selectedKeys:[]},n.handleConfirm)},n.handleConfirm=function(){n.setVisible(!1),n.confirmFilter()},n.onVisibleChange=function(e){n.setVisible(e),e||n.confirmFilter()},n.handleMenuItemClick=function(e){if(!(e.keyPath.length<=1)){var t=n.state.keyPathOfSelectedItem;n.state.selectedKeys.indexOf(e.key)>=0?delete t[e.key]:t[e.key]=e.keyPath,n.setState({keyPathOfSelectedItem:t})}},n.renderFilterIcon=function(){var e=n.props,t=e.column,r=e.locale,o=e.prefixCls,i=t.filterIcon,a=n.props.selectedKeys.length>0?o+"-selected":"";return i?L.cloneElement(i,{title:r.filterTitle,className:Pe()(i.className,E()({},o+"-icon",!0))}):L.createElement(De.a,{title:r.filterTitle,type:"filter",className:a})};var r="filterDropdownVisible"in e.column&&e.column.filterDropdownVisible;return n.state={selectedKeys:e.selectedKeys,keyPathOfSelectedItem:{},visible:r},n}return R()(t,e),D()(t,[{key:"componentDidMount",value:function(){var e=this.props.column;this.setNeverShown(e)}},{key:"componentWillReceiveProps",value:function(e){var t=e.column;this.setNeverShown(t);var n={};"selectedKeys"in e&&(n.selectedKeys=e.selectedKeys),"filterDropdownVisible"in t&&(n.visible=t.filterDropdownVisible),Object.keys(n).length>0&&this.setState(n)}},{key:"setVisible",value:function(e){var t=this.props.column;"filterDropdownVisible"in t||this.setState({visible:e}),t.onFilterDropdownVisibleChange&&t.onFilterDropdownVisibleChange(e)}},{key:"confirmFilter",value:function(){this.state.selectedKeys!==this.props.selectedKeys&&this.props.confirmFilter(this.props.column,this.state.selectedKeys)}},{key:"renderMenuItem",value:function(e){var t=this.props.column,n=!("filterMultiple"in t)||t.filterMultiple,r=n?L.createElement(ze.a,{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}):L.createElement(Be.default,{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0});return L.createElement(Le.b,{key:e.value},r,L.createElement("span",null,e.text))}},{key:"hasSubMenu",value:function(){var e=this.props.column.filters;return(void 0===e?[]:e).some(function(e){return!!(e.children&&e.children.length>0)})}},{key:"renderMenus",value:function(e){var t=this;return e.map(function(e){if(e.children&&e.children.length>0){var n=t.state.keyPathOfSelectedItem,r=Object.keys(n).some(function(t){return n[t].indexOf(e.value)>=0}),o=r?t.props.dropdownPrefixCls+"-submenu-contain-selected":"";return L.createElement(Le.d,{title:e.text,className:o,key:e.value.toString()},t.renderMenus(e.children))}return t.renderMenuItem(e)})}},{key:"render",value:function(){var e=this.props,t=e.column,n=e.locale,r=e.prefixCls,o=e.dropdownPrefixCls,i=e.getPopupContainer,a=!("filterMultiple"in t)||t.filterMultiple,s=Pe()(E()({},o+"-menu-without-submenu",!this.hasSubMenu())),l=t.filterDropdown?L.createElement(We,null,t.filterDropdown):L.createElement(We,{className:r+"-dropdown"},L.createElement(Le.e,{multiple:a,onClick:this.handleMenuItemClick,prefixCls:o+"-menu",className:s,onSelect:this.setSelectedKeys,onDeselect:this.setSelectedKeys,selectedKeys:this.state.selectedKeys,getPopupContainer:function(e){return e.parentNode}},this.renderMenus(t.filters)),L.createElement("div",{className:r+"-dropdown-btns"},L.createElement("a",{className:r+"-dropdown-link confirm",onClick:this.handleConfirm},n.filterConfirm),L.createElement("a",{className:r+"-dropdown-link clear",onClick:this.handleClearFilters},n.filterReset)));return L.createElement(Ve.a,{trigger:["click"],overlay:l,visible:!this.neverShown&&this.state.visible,onVisibleChange:this.onVisibleChange,getPopupContainer:i,forceRender:!0},this.renderFilterIcon())}}]),t}(L.Component),Ue=He;He.defaultProps={handleFilter:function(){},column:{}};var qe=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},Ye=function(e){function t(e){P()(this,t);var n=A()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={checked:n.getCheckState(e)},n}return R()(t,e),D()(t,[{key:"componentDidMount",value:function(){this.subscribe()}},{key:"componentWillUnmount",value:function(){this.unsubscribe&&this.unsubscribe()}},{key:"subscribe",value:function(){var e=this,t=this.props.store;this.unsubscribe=t.subscribe(function(){var t=e.getCheckState(e.props);e.setState({checked:t})})}},{key:"getCheckState",value:function(e){var t=e.store,n=e.defaultSelection,r=e.rowIndex;return t.getState().selectionDirty?t.getState().selectedRowKeys.indexOf(r)>=0:t.getState().selectedRowKeys.indexOf(r)>=0||n.indexOf(r)>=0}},{key:"render",value:function(){var e=this.props,t=e.type,n=e.rowIndex,r=qe(e,["type","rowIndex"]),o=this.state.checked;return"radio"===t?L.createElement(Be.default,T()({checked:o,value:n},r)):L.createElement(ze.a,T()({checked:o},r))}}]),t}(L.Component),Ge=Ye,Xe=n(198),$e=function(e){function t(e){P()(this,t);var n=A()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleSelectAllChagne=function(e){var t=e.target.checked;n.props.onSelect(t?"all":"removeAll",0,null)},n.defaultSelections=e.hideDefaultSelections?[]:[{key:"all",text:e.locale.selectAll,onSelect:function(){}},{key:"invert",text:e.locale.selectInvert,onSelect:function(){}}],n.state={checked:n.getCheckState(e),indeterminate:n.getIndeterminateState(e)},n}return R()(t,e),D()(t,[{key:"componentDidMount",value:function(){this.subscribe()}},{key:"componentWillReceiveProps",value:function(e){this.setCheckState(e)}},{key:"componentWillUnmount",value:function(){this.unsubscribe&&this.unsubscribe()}},{key:"subscribe",value:function(){var e=this,t=this.props.store;this.unsubscribe=t.subscribe(function(){e.setCheckState(e.props)})}},{key:"checkSelection",value:function(e,t,n){var r=this.props,o=r.store,i=r.getCheckboxPropsByItem,a=r.getRecordKey;return("every"===t||"some"===t)&&(n?e[t](function(e,t){return i(e,t).defaultChecked}):e[t](function(e,t){return o.getState().selectedRowKeys.indexOf(a(e,t))>=0}))}},{key:"setCheckState",value:function(e){var t=this.getCheckState(e),n=this.getIndeterminateState(e);t!==this.state.checked&&this.setState({checked:t}),n!==this.state.indeterminate&&this.setState({indeterminate:n})}},{key:"getCheckState",value:function(e){var t=e.store,n=e.data;return!!n.length&&(t.getState().selectionDirty?this.checkSelection(n,"every",!1):this.checkSelection(n,"every",!1)||this.checkSelection(n,"every",!0))}},{key:"getIndeterminateState",value:function(e){var t=e.store,n=e.data;return!!n.length&&(t.getState().selectionDirty?this.checkSelection(n,"some",!1)&&!this.checkSelection(n,"every",!1):this.checkSelection(n,"some",!1)&&!this.checkSelection(n,"every",!1)||this.checkSelection(n,"some",!0)&&!this.checkSelection(n,"every",!0))}},{key:"renderMenus",value:function(e){var t=this;return e.map(function(e,n){return L.createElement(Xe.a.Item,{key:e.key||n},L.createElement("div",{onClick:function(){t.props.onSelect(e.key,n,e.onSelect)}},e.text))})}},{key:"render",value:function(){var e=this.props,t=e.disabled,n=e.prefixCls,r=e.selections,o=e.getPopupContainer,i=this.state,a=i.checked,s=i.indeterminate,l=n+"-selection",u=null;if(r){var c=Array.isArray(r)?this.defaultSelections.concat(r):this.defaultSelections,p=L.createElement(Xe.a,{className:l+"-menu",selectedKeys:[]},this.renderMenus(c));u=c.length>0?L.createElement(Ve.a,{overlay:p,getPopupContainer:o},L.createElement("div",{className:l+"-down"},L.createElement(De.a,{type:"down"}))):null}return L.createElement("div",{className:l},L.createElement(ze.a,{className:Pe()(E()({},l+"-select-all-custom",u)),checked:a,indeterminate:s,disabled:t,onChange:this.handleSelectAllChagne}),u)}}]),t}(L.Component),Je=$e,Ze=function(e){function t(){return P()(this,t),A()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return R()(t,e),t}(L.Component),Qe=Ze,et=function(e){function t(){return P()(this,t),A()(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return R()(t,e),t}(L.Component),tt=et;et.__ANT_TABLE_COLUMN_GROUP=!0;var nt=n(20),rt=n(60),ot=n.n(rt),it=this&&this.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},at={onChange:w,onShowSizeChange:w},st={},lt=function(e){function t(e){P()(this,t);var n=A()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.getCheckboxPropsByItem=function(e,t){var r=n.props.rowSelection,o=void 0===r?{}:r;if(!o.getCheckboxProps)return{};var i=n.getRecordKey(e,t);return n.CheckboxPropsCache[i]||(n.CheckboxPropsCache[i]=o.getCheckboxProps(e)),n.CheckboxPropsCache[i]},n.onRow=function(e,t){var r=n.props,o=r.onRow,i=r.prefixCls,a=o?o(e,t):{};return T()({},a,{prefixCls:i,store:n.store,rowKey:n.getRecordKey(e,t)})},n.handleFilter=function(e,t){var r=n.props,o=T()({},n.state.pagination),i=T()({},n.state.filters,E()({},n.getColumnKey(e),t)),a=[];g(n.columns,function(e){e.children||a.push(n.getColumnKey(e))}),Object.keys(i).forEach(function(e){a.indexOf(e)<0&&delete i[e]}),r.pagination&&(o.current=1,o.onChange(o.current));var s={pagination:o,filters:{}},l=T()({},i);n.getFilteredValueColumns().forEach(function(e){var t=n.getColumnKey(e);t&&delete l[t]}),Object.keys(l).length>0&&(s.filters=l),"object"===_()(r.pagination)&&"current"in r.pagination&&(s.pagination=T()({},o,{current:n.state.pagination.current})),n.setState(s,function(){n.store.setState({selectionDirty:!1});var e=n.props.onChange;e&&e.apply(null,n.prepareParamsArguments(T()({},n.state,{selectionDirty:!1,filters:i,pagination:o})))})},n.handleSelect=function(e,t,r){var o=r.target.checked,i=r.nativeEvent,a=n.store.getState().selectionDirty?[]:n.getDefaultSelection(),s=n.store.getState().selectedRowKeys.concat(a),l=n.getRecordKey(e,t);o?s.push(n.getRecordKey(e,t)):s=s.filter(function(e){return l!==e}),n.store.setState({selectionDirty:!0}),n.setSelectedRowKeys(s,{selectWay:"onSelect",record:e,checked:o,changeRowKeys:void 0,nativeEvent:i})},n.handleRadioSelect=function(e,t,r){var o=r.target.checked,i=r.nativeEvent,a=n.store.getState().selectionDirty?[]:n.getDefaultSelection(),s=n.store.getState().selectedRowKeys.concat(a);s=[n.getRecordKey(e,t)],n.store.setState({selectionDirty:!0}),n.setSelectedRowKeys(s,{selectWay:"onSelect",record:e,checked:o,changeRowKeys:void 0,nativeEvent:i})},n.handleSelectRow=function(e,t,r){var o=n.getFlatCurrentPageData(),i=n.store.getState().selectionDirty?[]:n.getDefaultSelection(),a=n.store.getState().selectedRowKeys.concat(i),s=o.filter(function(e,t){return!n.getCheckboxPropsByItem(e,t).disabled}).map(function(e,t){return n.getRecordKey(e,t)}),l=[],u="",c=void 0;switch(e){case"all":s.forEach(function(e){a.indexOf(e)<0&&(a.push(e),l.push(e))}),u="onSelectAll",c=!0;break;case"removeAll":s.forEach(function(e){a.indexOf(e)>=0&&(a.splice(a.indexOf(e),1),l.push(e))}),u="onSelectAll",c=!1;break;case"invert":s.forEach(function(e){a.indexOf(e)<0?a.push(e):a.splice(a.indexOf(e),1),l.push(e),u="onSelectInvert"})}n.store.setState({selectionDirty:!0});var p=n.props.rowSelection,f=2;if(p&&p.hideDefaultSelections&&(f=0),t>=f&&"function"==typeof r)return r(s);n.setSelectedRowKeys(a,{selectWay:u,checked:c,changeRowKeys:l})},n.handlePageChange=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];var i=n.props,a=T()({},n.state.pagination);a.current=e||(a.current||1),a.onChange.apply(a,[a.current].concat(r));var s={pagination:a};i.pagination&&"object"===_()(i.pagination)&&"current"in i.pagination&&(s.pagination=T()({},a,{current:n.state.pagination.current})),n.setState(s),n.store.setState({selectionDirty:!1});var l=n.props.onChange;l&&l.apply(null,n.prepareParamsArguments(T()({},n.state,{selectionDirty:!1,pagination:a})))},n.renderSelectionBox=function(e){return function(t,r,o){var i=n.getRecordKey(r,o),a=n.getCheckboxPropsByItem(r,o),s=function(t){"radio"===e?n.handleRadioSelect(r,i,t):n.handleSelect(r,i,t)};return L.createElement("span",{onClick:S},L.createElement(Ge,T()({type:e,store:n.store,rowIndex:i,onChange:s,defaultSelection:n.getDefaultSelection()},a)))}},n.getRecordKey=function(e,t){var r=n.props.rowKey,o="function"==typeof r?r(e,t):e[r];return Object(Re.a)(void 0!==o,"Each record in dataSource of table should have a unique `key` prop, or set `rowKey` to an unique primary key,see https://u.ant.design/table-row-key"),void 0===o?t:o},n.getPopupContainer=function(){return F.findDOMNode(n)},n.handleShowSizeChange=function(e,t){var r=n.state.pagination;r.onShowSizeChange(e,t);var o=T()({},r,{pageSize:t,current:e});n.setState({pagination:o});var i=n.props.onChange;i&&i.apply(null,n.prepareParamsArguments(T()({},n.state,{pagination:o})))},n.renderTable=function(e,t){var r,o=T()({},e,n.props.locale),i=n.props,a=(i.style,i.className,i.prefixCls),s=i.showHeader,l=it(i,["style","className","prefixCls","showHeader"]),u=n.getCurrentPageData(),c=n.props.expandedRowRender&&!1!==n.props.expandIconAsCell,p=Pe()((r={},E()(r,a+"-"+n.props.size,!0),E()(r,a+"-bordered",n.props.bordered),E()(r,a+"-empty",!u.length),E()(r,a+"-without-column-header",!s),r)),f=n.renderRowSelection(o);f=n.renderColumnsDropdown(f,o),f=f.map(function(e,t){var r=T()({},e);return r.key=n.getColumnKey(r,t),r});var d=f[0]&&"selection-column"===f[0].key?1:0;return"expandIconColumnIndex"in l&&(d=l.expandIconColumnIndex),L.createElement(Te,T()({key:"table"},l,{onRow:n.onRow,components:n.components,prefixCls:a,data:u,columns:f,showHeader:s,className:p,expandIconColumnIndex:d,expandIconAsCell:c,emptyText:!t.spinning&&o.emptyText}))},Object(Re.a)(!("columnsPageRange"in e||"columnsPageSize"in e),"`columnsPageRange` and `columnsPageSize` are removed, please use fixed columns instead, see: https://u.ant.design/fixed-columns."),n.columns=e.columns||C(e.children),n.createComponents(e.components),n.state=T()({},n.getDefaultSortOrder(n.columns),{filters:n.getFiltersFromColumns(),pagination:n.getDefaultPagination(e)}),n.CheckboxPropsCache={},n.store=v({selectedRowKeys:(e.rowSelection||{}).selectedRowKeys||[],selectionDirty:!1}),n}return R()(t,e),D()(t,[{key:"getDefaultSelection",value:function(){var e=this,t=this.props.rowSelection;return(void 0===t?{}:t).getCheckboxProps?this.getFlatData().filter(function(t,n){return e.getCheckboxPropsByItem(t,n).defaultChecked}).map(function(t,n){return e.getRecordKey(t,n)}):[]}},{key:"getDefaultPagination",value:function(e){var t=e.pagination||{};return this.hasPagination(e)?T()({},at,t,{current:t.defaultCurrent||t.current||1,pageSize:t.defaultPageSize||t.pageSize||10}):{}}},{key:"componentWillReceiveProps",value:function(e){if(this.columns=e.columns||C(e.children),("pagination"in e||"pagination"in this.props)&&this.setState(function(t){var n=T()({},at,t.pagination,e.pagination);return n.current=n.current||1,n.pageSize=n.pageSize||10,{pagination:!1!==e.pagination?n:st}}),e.rowSelection&&"selectedRowKeys"in e.rowSelection){this.store.setState({selectedRowKeys:e.rowSelection.selectedRowKeys||[]});var t=this.props.rowSelection;t&&e.rowSelection.getCheckboxProps!==t.getCheckboxProps&&(this.CheckboxPropsCache={})}if("dataSource"in e&&e.dataSource!==this.props.dataSource&&(this.store.setState({selectionDirty:!1}),this.CheckboxPropsCache={}),this.getSortOrderColumns(this.columns).length>0){var n=this.getSortStateFromColumns(this.columns);n.sortColumn===this.state.sortColumn&&n.sortOrder===this.state.sortOrder||this.setState(n)}if(this.getFilteredValueColumns(this.columns).length>0){var r=this.getFiltersFromColumns(this.columns),o=T()({},this.state.filters);Object.keys(r).forEach(function(e){o[e]=r[e]}),this.isFiltersChanged(o)&&this.setState({filters:o})}this.createComponents(e.components,this.props.components)}},{key:"setSelectedRowKeys",value:function(e,t){var n=this,r=t.selectWay,o=t.record,i=t.checked,a=t.changeRowKeys,s=t.nativeEvent,l=this.props.rowSelection,u=void 0===l?{}:l;!u||"selectedRowKeys"in u||this.store.setState({selectedRowKeys:e});var c=this.getFlatData();if(u.onChange||u[r]){var p=c.filter(function(t,r){return e.indexOf(n.getRecordKey(t,r))>=0});if(u.onChange&&u.onChange(e,p),"onSelect"===r&&u.onSelect)u.onSelect(o,i,p,s);else if("onSelectAll"===r&&u.onSelectAll){var f=c.filter(function(e,t){return a.indexOf(n.getRecordKey(e,t))>=0});u.onSelectAll(i,p,f)}else"onSelectInvert"===r&&u.onSelectInvert&&u.onSelectInvert(e)}}},{key:"hasPagination",value:function(e){return!1!==(e||this.props).pagination}},{key:"isFiltersChanged",value:function(e){var t=this,n=!1;return Object.keys(e).length!==Object.keys(this.state.filters).length?n=!0:Object.keys(e).forEach(function(r){e[r]!==t.state.filters[r]&&(n=!0)}),n}},{key:"getSortOrderColumns",value:function(e){return b(e||this.columns||[],function(e){return"sortOrder"in e})}},{key:"getFilteredValueColumns",value:function(e){return b(e||this.columns||[],function(e){return void 0!==e.filteredValue})}},{key:"getFiltersFromColumns",value:function(e){var t=this,n={};return this.getFilteredValueColumns(e).forEach(function(e){var r=t.getColumnKey(e);n[r]=e.filteredValue}),n}},{key:"getDefaultSortOrder",value:function(e){var t=this.getSortStateFromColumns(e),n=b(e||[],function(e){return null!=e.defaultSortOrder})[0];return n&&!t.sortColumn?{sortColumn:n,sortOrder:n.defaultSortOrder}:t}},{key:"getSortStateFromColumns",value:function(e){var t=this.getSortOrderColumns(e).filter(function(e){return e.sortOrder})[0];return t?{sortColumn:t,sortOrder:t.sortOrder}:{sortColumn:null,sortOrder:null}}},{key:"getSorterFn",value:function(){var e=this.state,t=e.sortOrder,n=e.sortColumn;if(t&&n&&"function"==typeof n.sorter)return function(e,r){var o=n.sorter(e,r);return 0!==o?"descend"===t?-o:o:0}}},{key:"toggleSortOrder",value:function(e,t){var n=this.state,r=n.sortColumn,o=n.sortOrder;this.isSortColumn(t)?o===e?(o="",r=null):o=e:(o=e,r=t);var i={sortOrder:o,sortColumn:r};0===this.getSortOrderColumns().length&&this.setState(i);var a=this.props.onChange;a&&a.apply(null,this.prepareParamsArguments(T()({},this.state,i)))}},{key:"renderRowSelection",value:function(e){var t=this,n=this.props,r=n.prefixCls,o=n.rowSelection,i=this.columns.concat();if(o){var a=this.getFlatCurrentPageData().filter(function(e,n){return!o.getCheckboxProps||!t.getCheckboxPropsByItem(e,n).disabled}),s=Pe()(r+"-selection-column",E()({},r+"-selection-column-custom",o.selections)),l={key:"selection-column",render:this.renderSelectionBox(o.type),className:s,fixed:o.fixed,width:o.columnWidth};if("radio"!==o.type){var u=a.every(function(e,n){return t.getCheckboxPropsByItem(e,n).disabled});l.title=L.createElement(Je,{store:this.store,locale:e,data:a,getCheckboxPropsByItem:this.getCheckboxPropsByItem,getRecordKey:this.getRecordKey,disabled:u,prefixCls:r,onSelect:this.handleSelectRow,selections:o.selections,hideDefaultSelections:o.hideDefaultSelections,getPopupContainer:this.getPopupContainer})}"fixed"in o?l.fixed=o.fixed:i.some(function(e){return"left"===e.fixed||!0===e.fixed})&&(l.fixed="left"),i[0]&&"selection-column"===i[0].key?i[0]=l:i.unshift(l)}return i}},{key:"getColumnKey",value:function(e,t){return e.key||e.dataIndex||t}},{key:"getMaxCurrent",value:function(e){var t=this.state.pagination,n=t.current,r=t.pageSize;return(n-1)*r>=e?Math.floor((e-1)/r)+1:n}},{key:"isSortColumn",value:function(e){var t=this.state.sortColumn;return!(!e||!t)&&this.getColumnKey(t)===this.getColumnKey(e)}},{key:"renderColumnsDropdown",value:function(e,t){var n=this,r=this.props,o=r.prefixCls,i=r.dropdownPrefixCls,a=this.state.sortOrder;return g(e,function(e,r){var s=T()({},e),l=n.getColumnKey(s,r),u=void 0,c=void 0;if(s.filters&&s.filters.length>0||s.filterDropdown){var p=n.state.filters[l]||[];u=L.createElement(Ue,{locale:t,column:s,selectedKeys:p,confirmFilter:n.handleFilter,prefixCls:o+"-filter",dropdownPrefixCls:i||"ant-dropdown",getPopupContainer:n.getPopupContainer})}if(s.sorter){var f=n.isSortColumn(s);f&&(s.className=Pe()(s.className,E()({},o+"-column-sort",a)));var d=f&&"ascend"===a,h=f&&"descend"===a;c=L.createElement("div",{className:o+"-column-sorter"},L.createElement("span",{className:o+"-column-sorter-up "+(d?"on":"off"),title:"\u2191",onClick:function(){return n.toggleSortOrder("ascend",s)}},L.createElement(De.a,{type:"caret-up"})),L.createElement("span",{className:o+"-column-sorter-down "+(h?"on":"off"),title:"\u2193",onClick:function(){return n.toggleSortOrder("descend",s)}},L.createElement(De.a,{type:"caret-down"})))}return s.title=L.createElement("span",{key:l},s.title,c,u),(c||u)&&(s.className=Pe()(o+"-column-has-filters",s.className)),s})}},{key:"renderPagination",value:function(e){if(!this.hasPagination())return null;var t="default",n=this.state.pagination;n.size?t=n.size:"middle"!==this.props.size&&"small"!==this.props.size||(t="small");var r=n.position||"bottom",o=n.total||this.getLocalData().length;return o>0&&(r===e||"both"===r)?L.createElement(Me.a,T()({key:"pagination-"+e},n,{className:Pe()(n.className,this.props.prefixCls+"-pagination"),onChange:this.handlePageChange,total:o,size:t,current:this.getMaxCurrent(o),onShowSizeChange:this.handleShowSizeChange})):null}},{key:"prepareParamsArguments",value:function(e){var t=T()({},e.pagination);delete t.onChange,delete t.onShowSizeChange;var n=e.filters,r={};return e.sortColumn&&e.sortOrder&&(r.column=e.sortColumn,r.order=e.sortOrder,r.field=e.sortColumn.dataIndex,r.columnKey=this.getColumnKey(e.sortColumn)),[t,n,r]}},{key:"findColumn",value:function(e){var t=this,n=void 0;return g(this.columns,function(r){t.getColumnKey(r)===e&&(n=r)}),n}},{key:"getCurrentPageData",value:function(){var e=this.getLocalData(),t=void 0,n=void 0,r=this.state;return this.hasPagination()?(n=r.pagination.pageSize,t=this.getMaxCurrent(r.pagination.total||e.length)):(n=Number.MAX_VALUE,t=1),(e.length>n||n===Number.MAX_VALUE)&&(e=e.filter(function(e,r){return r>=(t-1)*n&&r<t*n})),e}},{key:"getFlatData",value:function(){return y(this.getLocalData())}},{key:"getFlatCurrentPageData",value:function(){return y(this.getCurrentPageData())}},{key:"recursiveSort",value:function(e,t){var n=this,r=this.props.childrenColumnName,o=void 0===r?"children":r;return e.sort(t).map(function(e){return e[o]?T()({},e,E()({},o,n.recursiveSort(e[o],t))):e})}},{key:"getLocalData",value:function(){var e=this,t=this.state,n=this.props.dataSource,r=n||[];r=r.slice(0);var o=this.getSorterFn();return o&&(r=this.recursiveSort(r,o)),t.filters&&Object.keys(t.filters).forEach(function(n){var o=e.findColumn(n);if(o){var i=t.filters[n]||[];if(0!==i.length){var a=o.onFilter;r=a?r.filter(function(e){return i.some(function(t){return a(t,e)})}):r}}}),r}},{key:"createComponents",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],n=e&&e.body&&e.body.row,r=t&&t.body&&t.body.row;this.components&&n===r||(this.components=T()({},e),this.components.body=T()({},e.body,{row:m(n)}))}},{key:"render",value:function(){var e=this,t=this.props,n=t.style,r=t.className,o=t.prefixCls,i=this.getCurrentPageData(),a=this.props.loading;"boolean"==typeof a&&(a={spinning:a});var s=L.createElement(Ae.a,{componentName:"Table",defaultLocale:je.a.Table},function(t){return e.renderTable(t,a)}),l=this.hasPagination()&&i&&0!==i.length?o+"-with-pagination":o+"-without-pagination";return L.createElement("div",{className:Pe()(o+"-wrapper",r),style:n},L.createElement(Ie.a,T()({},a,{className:a.spinning?l+" "+o+"-spin-holder":""}),this.renderPagination("top"),s,this.renderPagination("bottom")))}}]),t}(L.Component);t.a=lt;lt.Column=Qe,lt.ColumnGroup=tt,lt.propTypes={dataSource:B.a.array,columns:B.a.array,prefixCls:B.a.string,useFixedHeader:B.a.bool,rowSelection:B.a.object,className:B.a.string,size:B.a.string,loading:B.a.oneOfType([B.a.bool,B.a.object]),bordered:B.a.bool,onChange:B.a.func,locale:B.a.object,dropdownPrefixCls:B.a.string},lt.defaultProps={dataSource:[],prefixCls:"ant-table",useFixedHeader:!1,rowSelection:null,className:"",size:"large",loading:!1,bordered:!1,indentSize:20,locale:{},rowKey:"key",showHeader:!0}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(0),l=(function(e){e&&e.__esModule}(s),n(199)),u=function(e){function t(){return r(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),a(t,[{key:"getChildContext",value:function(){return{miniStore:this.props.store}}},{key:"render",value:function(){return s.Children.only(this.props.children)}}]),t}(s.Component);u.propTypes={store:l.storeShape.isRequired},u.childContextTypes={miniStore:l.storeShape.isRequired},t.default=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){return e.displayName||e.name||"Component"}function l(e){var t=!!e,n=e||y;return function(e){var r=function(r){function s(e,t){o(this,s);var r=i(this,(s.__proto__||Object.getPrototypeOf(s)).call(this,e,t));return r.handleChange=function(){if(r.unsubscribe){var e=n(r.store.getState(),r.props);(0,d.default)(r.nextState,e)||(r.nextState=e,r.setState({subscribed:e}))}},r.store=t.miniStore,r.state={subscribed:n(r.store.getState(),e)},r}return a(s,r),c(s,[{key:"componentDidMount",value:function(){this.trySubscribe()}},{key:"componentWillUnmount",value:function(){this.tryUnsubscribe()}},{key:"trySubscribe",value:function(){t&&(this.unsubscribe=this.store.subscribe(this.handleChange),this.handleChange())}},{key:"tryUnsubscribe",value:function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)}},{key:"render",value:function(){return(0,p.createElement)(e,u({},this.props,this.state.subscribed,{store:this.store}))}}]),s}(p.Component);return r.displayName="Connect("+s(e)+")",r.contextTypes={miniStore:m.storeShape.isRequired},(0,v.default)(r,e)}}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t.default=l;var p=n(0),f=n(31),d=r(f),h=n(197),v=r(h),m=n(199),y=function(){return{}}},function(e,t,n){"use strict";function r(e){function t(e){i=o({},i,e);for(var t=0;t<a.length;t++)a[t]()}function n(){return i}function r(e){return a.push(e),function(){var t=a.indexOf(e);a.splice(t,1)}}var i=e,a=[];return{setState:t,getState:n,subscribe:r}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.default=r},function(e,t,n){var r=n(376),o=n(401),i=o(function(e,t,n){r(e,t,n)});e.exports=i},function(e,t,n){function r(e,t,n,p,f){e!==t&&a(t,function(a,u){if(l(a))f||(f=new o),s(e,t,u,n,r,p,f);else{var d=p?p(c(e,u),a,u+"",e,t,f):void 0;void 0===d&&(d=a),i(e,u,d)}},u)}var o=n(141),i=n(200),a=n(382),s=n(384),l=n(32),u=n(206),c=n(205);e.exports=r},function(e,t,n){function r(){this.__data__=new o,this.size=0}var o=n(93);e.exports=r},function(e,t){function n(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}e.exports=n},function(e,t){function n(e){return this.__data__.get(e)}e.exports=n},function(e,t){function n(e){return this.__data__.has(e)}e.exports=n},function(e,t,n){function r(e,t){var n=this.__data__;if(n instanceof o){var r=n.__data__;if(!i||r.length<s-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new a(r)}return n.set(e,t),this.size=n.size,this}var o=n(93),i=n(134),a=n(132),s=200;e.exports=r},function(e,t,n){var r=n(383),o=r();e.exports=o},function(e,t){function n(e){return function(t,n,r){for(var o=-1,i=Object(t),a=r(t),s=a.length;s--;){var l=a[e?s:++o];if(!1===n(i[l],l,i))break}return t}}e.exports=n},function(e,t,n){function r(e,t,n,r,b,C,w){var S=y(e,n),x=y(t,n),_=w.get(x);if(_)return void o(e,n,_);var k=C?C(S,x,n+"",e,t,w):void 0,E=void 0===k;if(E){var O=c(x),T=!O&&f(x),N=!O&&!T&&m(x);k=x,O||T||N?c(S)?k=S:p(S)?k=s(S):T?(E=!1,k=i(x,!0)):N?(E=!1,k=a(x,!0)):k=[]:v(x)||u(x)?(k=S,u(S)?k=g(S):(!h(S)||r&&d(S))&&(k=l(x))):E=!1}E&&(w.set(x,k),b(k,x,r,C,w),w.delete(x)),o(e,n,k)}var o=n(200),i=n(385),a=n(386),s=n(202),l=n(388),u=n(135),c=n(37),p=n(390),f=n(144),d=n(133),h=n(32),v=n(392),m=n(145),y=n(205),g=n(396);e.exports=r},function(e,t,n){(function(e){function r(e,t){if(t)return e.slice();var n=e.length,r=u?u(n):new e.constructor(n);return e.copy(r),r}var o=n(33),i="object"==typeof t&&t&&!t.nodeType&&t,a=i&&"object"==typeof e&&e&&!e.nodeType&&e,s=a&&a.exports===i,l=s?o.Buffer:void 0,u=l?l.allocUnsafe:void 0;e.exports=r}).call(t,n(142)(e))},function(e,t,n){function r(e,t){var n=t?o(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}var o=n(387);e.exports=r},function(e,t,n){function r(e){var t=new e.constructor(e.byteLength);return new o(t).set(new o(e)),t}var o=n(201);e.exports=r},function(e,t,n){function r(e){return"function"!=typeof e.constructor||a(e)?{}:o(i(e))}var o=n(389),i=n(203),a=n(143);e.exports=r},function(e,t,n){var r=n(32),o=Object.create,i=function(){function e(){}return function(t){if(!r(t))return{};if(o)return o(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();e.exports=i},function(e,t,n){function r(e){return i(e)&&o(e)}var o=n(76),i=n(43);e.exports=r},function(e,t){function n(){return!1}e.exports=n},function(e,t,n){function r(e){if(!a(e)||o(e)!=s)return!1;var t=i(e);if(null===t)return!0;var n=p.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==f}var o=n(52),i=n(203),a=n(43),s="[object Object]",l=Function.prototype,u=Object.prototype,c=l.toString,p=u.hasOwnProperty,f=c.call(Object);e.exports=r},function(e,t,n){function r(e){return a(e)&&i(e.length)&&!!s[o(e)]}var o=n(52),i=n(136),a=n(43),s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s["[object Arguments]"]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s["[object Function]"]=s["[object Map]"]=s["[object Number]"]=s["[object Object]"]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1,e.exports=r},function(e,t){function n(e){return function(t){return e(t)}}e.exports=n},function(e,t,n){(function(e){var r=n(184),o="object"==typeof t&&t&&!t.nodeType&&t,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,a=i&&i.exports===o,s=a&&r.process,l=function(){try{return s&&s.binding&&s.binding("util")}catch(e){}}();e.exports=l}).call(t,n(142)(e))},function(e,t,n){function r(e){return o(e,i(e))}var o=n(397),i=n(206);e.exports=r},function(e,t,n){function r(e,t,n,r){var a=!n;n||(n={});for(var s=-1,l=t.length;++s<l;){var u=t[s],c=r?r(n[u],e[u],u,n,e):void 0;void 0===c&&(c=e[u]),a?i(n,u,c):o(n,u,c)}return n}var o=n(195),i=n(138);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}e.exports=n},function(e,t,n){function r(e){if(!o(e))return a(e);var t=i(e),n=[];for(var r in e)("constructor"!=r||!t&&l.call(e,r))&&n.push(r);return n}var o=n(32),i=n(143),a=n(400),s=Object.prototype,l=s.hasOwnProperty;e.exports=r},function(e,t){function n(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}e.exports=n},function(e,t,n){function r(e){return o(function(t,n){var r=-1,o=n.length,a=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,s&&i(n[0],n[1],s)&&(a=o<3?void 0:a,o=1),t=Object(t);++r<o;){var l=n[r];l&&e(t,l,r,a)}return t})}var o=n(402),i=n(409);e.exports=r},function(e,t,n){function r(e,t){return a(i(e,t,o),e+"")}var o=n(146),i=n(403),a=n(405);e.exports=r},function(e,t,n){function r(e,t,n){return t=i(void 0===t?e.length-1:t,0),function(){for(var r=arguments,a=-1,s=i(r.length-t,0),l=Array(s);++a<s;)l[a]=r[t+a];a=-1;for(var u=Array(t+1);++a<t;)u[a]=r[a];return u[t]=n(l),o(e,this,u)}}var o=n(404),i=Math.max;e.exports=r},function(e,t){function n(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}e.exports=n},function(e,t,n){var r=n(406),o=n(408),i=o(r);e.exports=i},function(e,t,n){var r=n(407),o=n(196),i=n(146),a=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:r(t),writable:!0})}:i;e.exports=a},function(e,t){function n(e){return function(){return e}}e.exports=n},function(e,t){function n(e){var t=0,n=0;return function(){var a=i(),s=o-(a-n);if(n=a,s>0){if(++t>=r)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var r=800,o=16,i=Date.now;e.exports=n},function(e,t,n){function r(e,t,n){if(!s(n))return!1;var r=typeof t;return!!("number"==r?i(n)&&a(t,n.length):"string"==r&&t in n)&&o(n[t],e)}var o=n(74),i=n(76),a=n(96),s=n(32);e.exports=r},function(e,t,n){var r=n(411);e.exports=function(e,t,n){for(n=n||document,e={parentNode:e};(e=e.parentNode)&&e!==n;)if(r(e,t))return e}},function(e,t,n){"use strict";function r(e,t){var n=window.Element.prototype,r=n.matches||n.mozMatchesSelector||n.msMatchesSelector||n.oMatchesSelector||n.webkitMatchesSelector;if(!e||1!==e.nodeType)return!1;var o=e.parentNode;if(r)return r.call(e,t);for(var i=o.querySelectorAll(t),a=i.length,s=0;s<a;s++)if(i[s]===e)return!0;return!1}e.exports=r},function(e,t){},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),u=r(l),c=n(5),p=r(c),f=n(9),d=n(414),h=n(415),v=r(h),m=n(416),y=r(m),g=n(417),b=r(g),C=n(418),w=r(C),S=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.lazyLoadHandler=n.lazyLoadHandler.bind(n),e.throttle>0&&(e.debounce?n.lazyLoadHandler=(0,v.default)(n.lazyLoadHandler,e.throttle):n.lazyLoadHandler=(0,y.default)(n.lazyLoadHandler,e.throttle)),n.state={visible:!1},n}return a(t,e),s(t,[{key:"componentDidMount",value:function(){this._mounted=!0;var e=this.getEventNode();this.lazyLoadHandler(),this.lazyLoadHandler.flush&&this.lazyLoadHandler.flush(),(0,d.add)(window,"resize",this.lazyLoadHandler),(0,d.add)(e,"scroll",this.lazyLoadHandler)}},{key:"componentWillReceiveProps",value:function(){this.state.visible||this.lazyLoadHandler()}},{key:"shouldComponentUpdate",value:function(e,t){return t.visible}},{key:"componentWillUnmount",value:function(){this._mounted=!1,this.lazyLoadHandler.cancel&&this.lazyLoadHandler.cancel(),this.detachListeners()}},{key:"getEventNode",value:function(){return(0,b.default)((0,f.findDOMNode)(this))}},{key:"getOffset",value:function(){var e=this.props,t=e.offset,n=e.offsetVertical,r=e.offsetHorizontal,o=e.offsetTop,i=e.offsetBottom,a=e.offsetLeft,s=e.offsetRight,l=e.threshold,u=l||t,c=n||u,p=r||u;return{top:o||c,bottom:i||c,left:a||p,right:s||p}}},{key:"lazyLoadHandler",value:function(){if(this._mounted){var e=this.getOffset(),t=(0,f.findDOMNode)(this),n=this.getEventNode();if((0,w.default)(t,n,e)){var r=this.props.onContentVisible;this.setState({visible:!0},function(){r&&r()}),this.detachListeners()}}}},{key:"detachListeners",value:function(){var e=this.getEventNode();(0,d.remove)(window,"resize",this.lazyLoadHandler),(0,d.remove)(e,"scroll",this.lazyLoadHandler)}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.className,r=e.height,o=e.width,i=this.state.visible,a={height:r,width:o},s="LazyLoad"+(i?" is-visible":"")+(n?" "+n:"");return u.default.createElement(this.props.elementType,{className:s,style:a},i&&l.Children.only(t))}}]),t}(l.Component);t.default=S,S.propTypes={children:p.default.node.isRequired,className:p.default.string,debounce:p.default.bool,elementType:p.default.string,height:p.default.oneOfType([p.default.string,p.default.number]),offset:p.default.number,offsetBottom:p.default.number,offsetHorizontal:p.default.number,offsetLeft:p.default.number,offsetRight:p.default.number,offsetTop:p.default.number,offsetVertical:p.default.number,threshold:p.default.number,throttle:p.default.number,width:p.default.oneOfType([p.default.string,p.default.number]),onContentVisible:p.default.func},S.defaultProps={elementType:"div",debounce:!0,offset:0,offsetBottom:0,offsetHorizontal:0,offsetLeft:0,offsetRight:0,offsetTop:0,offsetVertical:0,throttle:250}},function(e,t,n){var r,o;!function(i,a){r=a,void 0!==(o="function"==typeof r?r.call(t,n,t,e):r)&&(e.exports=o)}(0,function(){function e(e,t){return function(n,r,o,i){n[e]?n[e](r,o,i):n[t]&&n[t]("on"+r,o)}}return{add:e("addEventListener","attachEvent"),remove:e("removeEventListener","detachEvent")}})},function(e,t,n){(function(t){function n(e,t,n){function o(t){var n=v,r=m;return v=m=void 0,_=t,g=e.apply(r,n)}function i(e){return _=e,b=setTimeout(c,t),k?o(e):g}function l(e){var n=e-x,r=e-_,o=t-n;return E?w(o,y-r):o}function u(e){var n=e-x,r=e-_;return void 0===x||n>=t||n<0||E&&r>=y}function c(){var e=S();if(u(e))return p(e);b=setTimeout(c,l(e))}function p(e){return b=void 0,O&&v?o(e):(v=m=void 0,g)}function f(){void 0!==b&&clearTimeout(b),_=0,v=x=m=b=void 0}function d(){return void 0===b?g:p(S())}function h(){var e=S(),n=u(e);if(v=arguments,m=this,x=e,n){if(void 0===b)return i(x);if(E)return b=setTimeout(c,t),o(x)}return void 0===b&&(b=setTimeout(c,t)),g}var v,m,y,g,b,x,_=0,k=!1,E=!1,O=!0;if("function"!=typeof e)throw new TypeError(s);return t=a(t)||0,r(n)&&(k=!!n.leading,E="maxWait"in n,y=E?C(a(n.maxWait)||0,t):y,O="trailing"in n?!!n.trailing:O),h.cancel=f,h.flush=d,h}function r(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function o(e){return!!e&&"object"==typeof e}function i(e){return"symbol"==typeof e||o(e)&&b.call(e)==u}function a(e){if("number"==typeof e)return e;if(i(e))return l;if(r(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=r(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(c,"");var n=f.test(e);return n||d.test(e)?h(e.slice(2),n?2:8):p.test(e)?l:+e}var s="Expected a function",l=NaN,u="[object Symbol]",c=/^\s+|\s+$/g,p=/^[-+]0x[0-9a-f]+$/i,f=/^0b[01]+$/i,d=/^0o[0-7]+$/i,h=parseInt,v="object"==typeof t&&t&&t.Object===Object&&t,m="object"==typeof self&&self&&self.Object===Object&&self,y=v||m||Function("return this")(),g=Object.prototype,b=g.toString,C=Math.max,w=Math.min,S=function(){return y.Date.now()};e.exports=n}).call(t,n(24))},function(e,t,n){(function(t){function n(e,t,n){function r(t){var n=v,r=m;return v=m=void 0,_=t,g=e.apply(r,n)}function i(e){return _=e,b=setTimeout(c,t),k?r(e):g}function a(e){var n=e-C,r=e-_,o=t-n;return E?S(o,y-r):o}function u(e){var n=e-C,r=e-_;return void 0===C||n>=t||n<0||E&&r>=y}function c(){var e=x();if(u(e))return p(e);b=setTimeout(c,a(e))}function p(e){return b=void 0,O&&v?r(e):(v=m=void 0,g)}function f(){void 0!==b&&clearTimeout(b),_=0,v=C=m=b=void 0}function d(){return void 0===b?g:p(x())}function h(){var e=x(),n=u(e);if(v=arguments,m=this,C=e,n){if(void 0===b)return i(C);if(E)return b=setTimeout(c,t),r(C)}return void 0===b&&(b=setTimeout(c,t)),g}var v,m,y,g,b,C,_=0,k=!1,E=!1,O=!0;if("function"!=typeof e)throw new TypeError(l);return t=s(t)||0,o(n)&&(k=!!n.leading,E="maxWait"in n,y=E?w(s(n.maxWait)||0,t):y,O="trailing"in n?!!n.trailing:O),h.cancel=f,h.flush=d,h}function r(e,t,r){var i=!0,a=!0;if("function"!=typeof e)throw new TypeError(l);return o(r)&&(i="leading"in r?!!r.leading:i,a="trailing"in r?!!r.trailing:a),n(e,t,{leading:i,maxWait:t,trailing:a})}function o(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function i(e){return!!e&&"object"==typeof e}function a(e){return"symbol"==typeof e||i(e)&&C.call(e)==c}function s(e){if("number"==typeof e)return e;if(a(e))return u;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(p,"");var n=d.test(e);return n||h.test(e)?v(e.slice(2),n?2:8):f.test(e)?u:+e}var l="Expected a function",u=NaN,c="[object Symbol]",p=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,d=/^0b[01]+$/i,h=/^0o[0-7]+$/i,v=parseInt,m="object"==typeof t&&t&&t.Object===Object&&t,y="object"==typeof self&&self&&self.Object===Object&&self,g=m||y||Function("return this")(),b=Object.prototype,C=b.toString,w=Math.max,S=Math.min,x=function(){return g.Date.now()};e.exports=r}).call(t,n(24))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(e,t){return"undefined"!=typeof getComputedStyle?getComputedStyle(e,null).getPropertyValue(t):e.style[t]},o=function(e){return r(e,"overflow")+r(e,"overflow-y")+r(e,"overflow-x")},i=function(e){if(!(e instanceof HTMLElement))return window;for(var t=e;t&&t!==document.body&&t!==document.documentElement&&t.parentNode;){if(/(scroll|auto)/.test(o(t)))return t;t=t.parentNode}return window};t.default=i},function(e,t,n){"use strict";function r(e,t,n){if(a(e))return!1;var r=void 0,o=void 0,s=void 0,l=void 0;if(void 0===t||t===window)r=window.pageYOffset,s=window.pageXOffset,o=r+window.innerHeight,l=s+window.innerWidth;else{var u=(0,i.default)(t);r=u.top,s=u.left,o=r+t.offsetHeight,l=s+t.offsetWidth}var c=(0,i.default)(e);return r<=c.top+e.offsetHeight+n.top&&o>=c.top-n.bottom&&s<=c.left+e.offsetWidth+n.left&&l>=c.left-n.right}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r;var o=n(419),i=function(e){return e&&e.__esModule?e:{default:e}}(o),a=function(e){return null===e.offsetParent}},function(e,t,n){"use strict";function r(e){var t=e.getBoundingClientRect();return{top:t.top+window.pageYOffset,left:t.left+window.pageXOffset}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r},function(e,t){},function(e,t,n){"use strict";var r=n(16),o=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(77),a=n(25),s=n(54),l=n(28),u=n(45),c=n(22),p=n(12),f=n(11),d=(n(65),n(39)),h=n(436),v=u.draft_tree_data_support,m=v?l:s,y=f.List,g=f.Repeat,b={insertAtomicBlock:function(e,t,n){var r=e.getCurrentContent(),s=e.getSelection(),l=c.removeRange(r,s,"backward"),u=l.getSelectionAfter(),f=c.splitBlock(l,u),h=f.getSelectionAfter(),b=c.setBlockType(f,h,"atomic"),C=a.create({entity:t}),w={key:d(),type:"atomic",text:n,characterList:y(g(C,n.length))},S={key:d(),type:"unstyled"};v&&(w=o({},w,{nextSibling:S.key}),S=o({},S,{prevSibling:w.key}));var x=[new m(w),new m(S)],_=i.createFromArray(x),k=c.replaceWithFragment(b,h,_),E=k.merge({selectionBefore:s,selectionAfter:k.getSelectionAfter().set("hasFocus",!0)});return p.push(e,E,"insert-fragment")},moveAtomicBlock:function(e,t,n,r){var o=e.getCurrentContent(),i=e.getSelection(),a=void 0;if("before"===r||"after"===r){var s=o.getBlockForKey("before"===r?n.getStartKey():n.getEndKey());a=h(o,t,s,r)}else{var l=c.removeRange(o,n,"backward"),u=l.getSelectionAfter(),f=l.getBlockForKey(u.getFocusKey());if(0===u.getStartOffset())a=h(l,t,f,"before");else if(u.getEndOffset()===f.getLength())a=h(l,t,f,"after");else{var d=c.splitBlock(l,u),v=d.getSelectionAfter(),m=d.getBlockForKey(v.getFocusKey());a=h(d,t,m,"before")}}var y=a.merge({selectionBefore:i,selectionAfter:a.getSelectionAfter().set("hasFocus",!0)});return p.push(e,y,"move-block")}};e.exports=b},function(e,t,n){"use strict";var r={draft_killswitch_allow_nontextnodes:!1,draft_segmented_entities_behavior:!1,draft_handlebeforeinput_composed_text:!1,draft_tree_data_support:!1};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){var i=e.getBlockMap(),s=t.getStartKey(),l=t.getStartOffset(),u=t.getEndKey(),c=t.getEndOffset(),p=i.skipUntil(function(e,t){return t===s}).takeUntil(function(e,t){return t===u}).concat(a([[u,i.get(u)]])).map(function(e,t){var i,a;s===u?(i=l,a=c):(i=t===s?l:0,a=t===u?c:e.getLength());for(var p,f=e.getCharacterList();i<a;)p=f.get(i),f=f.set(i,r?o.applyStyle(p,n):o.removeStyle(p,n)),i++;return e.set("characterList",f)});return e.merge({blockMap:i.merge(p),selectionBefore:t,selectionAfter:t})}var o=n(25),i=n(11),a=i.Map,s={add:function(e,t,n){return r(e,t,n,!0)},remove:function(e,t,n){return r(e,t,n,!1)}};e.exports=s},function(e,t,n){"use strict";function r(e,t,n){var r=e.getBlockMap(),a=t.getStartKey(),s=t.getStartOffset(),l=t.getEndKey(),u=t.getEndOffset(),c=r.skipUntil(function(e,t){return t===a}).takeUntil(function(e,t){return t===l}).toOrderedMap().merge(o.OrderedMap([[l,r.get(l)]])).map(function(e,t){var r=t===a?s:0,o=t===l?u:e.getLength();return i(e,r,o,n)});return e.merge({blockMap:r.merge(c),selectionBefore:t,selectionAfter:t})}var o=n(11),i=n(425);e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){for(var i=e.getCharacterList();t<n;)i=i.set(t,o.applyEntity(i.get(t),r)),t++;return e.set("characterList",i)}var o=n(25);e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r,i){var a=r.getStartOffset(),s=r.getEndOffset(),l=t.getEntityAt(a),u=n.getEntityAt(s-1);if(!l&&!u)return r;var c=r;if(l&&l===u)c=o(e,t,c,i,l,!0,!0);else if(l&&u){var p=o(e,t,c,i,l,!1,!0),f=o(e,n,c,i,u,!1,!1);c=c.merge({anchorOffset:p.getAnchorOffset(),focusOffset:f.getFocusOffset(),isBackward:!1})}else if(l){var d=o(e,t,c,i,l,!1,!0);c=c.merge({anchorOffset:d.getStartOffset(),isBackward:!1})}else if(u){var h=o(e,n,c,i,u,!1,!1);c=c.merge({focusOffset:h.getEndOffset(),isBackward:!1})}return c}function o(e,t,n,r,o,l,u){var c=n.getStartOffset(),p=n.getEndOffset(),f=e.__get(o),d=f.getMutability(),h=u?c:p;if("MUTABLE"===d)return n;var v=a(t,o).filter(function(e){return h<=e.end&&h>=e.start});1!=v.length&&s(!1);var m=v[0];if("IMMUTABLE"===d)return n.merge({anchorOffset:m.start,focusOffset:m.end,isBackward:!1});l||(u?p=m.end:c=m.start);var y=i.getRemovalRange(c,p,t.getText().slice(m.start,m.end),m.start,r);return n.merge({anchorOffset:y.start,focusOffset:y.end,isBackward:!1})}var i=n(427),a=n(428),s=n(10);e.exports=r},function(e,t,n){"use strict";var r={getRemovalRange:function(e,t,n,r,o){var i=n.split(" ");i=i.map(function(e,t){if("forward"===o){if(t>0)return" "+e}else if(t<i.length-1)return e+" ";return e});for(var a,s,l=r,u=null,c=null,p=0;p<i.length;p++){if(s=i[p],a=l+s.length,e<a&&l<t)null!==u?c=a:(u=l,c=a);else if(null!==u)break;l=a}var f=r+n.length,d=u===r,h=c===f;return(!d&&h||d&&!h)&&("forward"===o?c!==f&&c++:u!==r&&u--),{start:u,end:c}}};e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=[];return e.findEntityRanges(function(e){return e.getEntity()===t},function(e,t){n.push({start:e,end:t})}),n.length||o(!1),n}var o=n(10);e.exports=r},function(e,t,n){"use strict";var r=n(77),o=n(28),i=n(11),a=n(210),s=n(10),l=n(208),u=i.List,c=function(e,t,n,r,o,i){var s=n.get(o),l=s.getText(),u=s.getCharacterList(),c=o,p=i+r.getText().length,f=s.merge({text:l.slice(0,i)+r.getText()+l.slice(i),characterList:a(u,r.getCharacterList(),i),data:r.getData()});return e.merge({blockMap:n.set(o,f),selectionBefore:t,selectionAfter:t.merge({anchorKey:c,anchorOffset:p,focusKey:c,focusOffset:p,isBackward:!1})})},p=function(e,t,n){var r=e.getText(),o=e.getCharacterList(),i=r.slice(0,t),a=o.slice(0,t),s=n.first();return e.merge({text:i+s.getText(),characterList:a.concat(s.getCharacterList()),type:i?e.getType():s.getType(),data:s.getData()})},f=function(e,t,n){var r=e.getText(),o=e.getCharacterList(),i=r.length,a=r.slice(t,i),s=o.slice(t,i),l=n.last();return l.merge({text:l.getText()+a,characterList:l.getCharacterList().concat(s),data:l.getData()})},d=function(e,t){var n=e.getKey(),r=e,o=[];for(t.get(n)&&o.push(n);r&&r.getNextSiblingKey();){var i=r.getNextSiblingKey();if(!i)break;o.push(i),r=t.get(i)}return o},h=function(e,t,n,r){return e.withMutations(function(t){var o=n.getKey(),i=r.getKey(),a=n.getNextSiblingKey(),s=n.getParentKey(),l=d(r,e),c=l[l.length-1];if(t.get(i)?(t.setIn([o,"nextSibling"],i),t.setIn([i,"prevSibling"],o)):(t.setIn([o,"nextSibling"],r.getNextSiblingKey()),t.setIn([r.getNextSiblingKey(),"prevSibling"],o)),t.setIn([c,"nextSibling"],a),a&&t.setIn([a,"prevSibling"],c),l.forEach(function(e){return t.setIn([e,"parent"],s)}),s){var p=e.get(s),f=p.getChildKeys(),h=f.indexOf(o),v=h+1,m=f.toArray();m.splice.apply(m,[v,0].concat(l)),t.setIn([s,"children"],u(m))}})},v=function(e,t,n,i,a,s){var l=n.first()instanceof o,u=[],c=i.size,d=n.get(a),v=i.first(),m=i.last(),y=m.getLength(),g=m.getKey(),b=l&&(!d.getChildKeys().isEmpty()||!v.getChildKeys().isEmpty());n.forEach(function(e,t){if(t!==a)return void u.push(e);b?u.push(e):u.push(p(e,s,i)),i.slice(b?0:1,c-1).forEach(function(e){return u.push(e)}),u.push(f(e,s,i))});var C=r.createFromArray(u);return l&&(C=h(C,0,d,v)),e.merge({blockMap:C,selectionBefore:t,selectionAfter:t.merge({anchorKey:g,anchorOffset:y,focusKey:g,focusOffset:y,isBackward:!1})})},m=function(e,t,n){t.isCollapsed()||s(!1);var r=e.getBlockMap(),i=l(n),a=t.getStartKey(),u=t.getStartOffset(),p=r.get(a);return p instanceof o&&(p.getChildKeys().isEmpty()||s(!1)),1===i.size?c(e,t,r,i.first(),a,u):v(e,t,r,i,a,u)};e.exports=m},function(e,t,n){"use strict";function r(e,t,n,r){t.isCollapsed()||a(!1);var o=n.length;if(!o)return e;var l=e.getBlockMap(),u=t.getStartKey(),c=t.getStartOffset(),p=l.get(u),f=p.getText(),d=p.merge({text:f.slice(0,c)+n+f.slice(c,p.getLength()),characterList:i(p.getCharacterList(),s(r,o).toList(),c)}),h=c+o;return e.merge({blockMap:l.set(u,d),selectionAfter:t.merge({anchorOffset:h,focusOffset:h})})}var o=n(11),i=n(210),a=n(10),s=o.Repeat;e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=t.getStartKey(),o=t.getEndKey(),a=e.getBlockMap(),s=a.toSeq().skipUntil(function(e,t){return t===r}).takeUntil(function(e,t){return t===o}).concat(i([[o,a.get(o)]])).map(n);return e.merge({blockMap:a.merge(s),selectionBefore:t,selectionAfter:t})}var o=n(11),i=o.Map;e.exports=r},function(e,t,n){"use strict";var r=n(28),o=n(11),i=n(211),a=(o.List,o.Map),s=function(e,t,n){if(e){var r=t.get(e);r&&t.set(e,n(r))}},l=function(e,t){var n=[];if(!e)return n;for(var r=t.get(e);r&&r.getParentKey();){var o=r.getParentKey();o&&n.push(o),r=o?t.get(o):null}return n},u=function(e,t){var n=[];if(!e)return n;for(var r=i(e,t);r&&t.get(r);){var o=t.get(r);n.push(r),r=o.getParentKey()?i(o,t):null}return n},c=function(e,t,n){if(!e)return null;for(var r=n.get(e.getKey()).getNextSiblingKey();r&&!t.get(r);)r=n.get(r).getNextSiblingKey()||null;return r},p=function(e,t,n){if(!e)return null;for(var r=n.get(e.getKey()).getPrevSiblingKey();r&&!t.get(r);)r=n.get(r).getPrevSiblingKey()||null;return r},f=function(e,t,n,r){return e.withMutations(function(e){s(t.getKey(),e,function(n){return n.merge({nextSibling:c(t,e,r),prevSibling:p(t,e,r)})}),s(n.getKey(),e,function(t){return t.merge({nextSibling:c(n,e,r),prevSibling:p(n,e,r)})}),l(t.getKey(),r).forEach(function(t){return s(t,e,function(t){return t.merge({children:t.getChildKeys().filter(function(t){return e.get(t)}),nextSibling:c(t,e,r),prevSibling:p(t,e,r)})})}),s(t.getNextSiblingKey(),e,function(e){return e.merge({prevSibling:t.getPrevSiblingKey()})}),s(t.getPrevSiblingKey(),e,function(n){return n.merge({nextSibling:c(t,e,r)})}),s(n.getNextSiblingKey(),e,function(t){return t.merge({prevSibling:p(n,e,r)})}),s(n.getPrevSiblingKey(),e,function(e){return e.merge({nextSibling:n.getNextSiblingKey()})}),l(n.getKey(),r).forEach(function(t){s(t,e,function(t){return t.merge({children:t.getChildKeys().filter(function(t){return e.get(t)}),nextSibling:c(t,e,r),prevSibling:p(t,e,r)})})}),u(n,r).forEach(function(t){return s(t,e,function(t){return t.merge({nextSibling:c(t,e,r),prevSibling:p(t,e,r)})})})})},d=function(e,t){if(t.isCollapsed())return e;var n=e.getBlockMap(),o=t.getStartKey(),s=t.getStartOffset(),u=t.getEndKey(),c=t.getEndOffset(),p=n.get(o),d=n.get(u),v=p instanceof r,m=[];if(v){var y=d.getChildKeys(),g=l(u,n);d.getNextSiblingKey()&&(m=m.concat(g)),y.isEmpty()||(m=m.concat(g.concat([u]))),m=m.concat(l(i(d,n),n))}var b=void 0;b=p===d?h(p.getCharacterList(),s,c):p.getCharacterList().slice(0,s).concat(d.getCharacterList().slice(c));var C=p.merge({text:p.getText().slice(0,s)+d.getText().slice(c),characterList:b}),w=n.toSeq().skipUntil(function(e,t){return t===o}).takeUntil(function(e,t){return t===u}).filter(function(e,t){return-1===m.indexOf(t)}).concat(a([[u,null]])).map(function(e,t){return t===o?C:null}),S=n.merge(w).filter(function(e){return!!e});return v&&(S=f(S,p,d,n)),e.merge({blockMap:S,selectionBefore:t,selectionAfter:t.merge({anchorKey:o,anchorOffset:s,focusKey:o,focusOffset:s,isBackward:!1})})},h=function(e,t,n){if(0===t)for(;t<n;)e=e.shift(),t++;else if(n===e.count())for(;n>t;)e=e.pop(),n--;else{var r=e.slice(0,t),o=e.slice(n);e=r.concat(o).toList()}return e};e.exports=d},function(e,t,n){"use strict";var r=n(28),o=n(11),i=n(39),a=n(10),s=o.List,l=o.Map,u=function(e,t,n){if(e){var r=t.get(e);r&&t.set(e,n(r))}},c=function(e,t,n){return e.withMutations(function(e){var r=t.getKey(),o=n.getKey();u(t.getParentKey(),e,function(e){var t=e.getChildKeys(),n=t.indexOf(r)+1,i=t.toArray();return i.splice(n,0,o),e.merge({children:s(i)})}),u(t.getNextSiblingKey(),e,function(e){return e.merge({prevSibling:o})}),u(r,e,function(e){return e.merge({nextSibling:o})}),u(o,e,function(e){return e.merge({prevSibling:r})})})},p=function(e,t){t.isCollapsed()||a(!1);var n=t.getAnchorKey(),o=t.getAnchorOffset(),s=e.getBlockMap(),u=s.get(n),p=u.getText(),f=u.getCharacterList(),d=i(),h=u instanceof r,v=u.merge({text:p.slice(0,o),characterList:f.slice(0,o)}),m=v.merge({key:d,text:p.slice(o),characterList:f.slice(o),data:l()}),y=s.toSeq().takeUntil(function(e){return e===u}),g=s.toSeq().skipUntil(function(e){return e===u}).rest(),b=y.concat([[n,v],[d,m]],g).toOrderedMap();return h&&(u.getChildKeys().isEmpty()||a(!1),b=c(b,v,m)),e.merge({blockMap:b,selectionBefore:t,selectionAfter:t.merge({anchorKey:d,anchorOffset:0,focusKey:d,focusOffset:0,isBackward:!1})})};e.exports=p},function(e,t,n){"use strict";var r,o=n(11),i=n(435),a=n(34),s=o.OrderedMap,l={getDirectionMap:function(e,t){r?r.reset():r=new i;var n=e.getBlockMap(),l=n.valueSeq().map(function(e){return a(r).getDirection(e.getText())}),u=s(n.keySeq().zip(l));return null!=t&&o.is(t,u)?t:u}};e.exports=l},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(214),i=n(149),a=n(10),s=function(){function e(t){r(this,e),t?i.isStrong(t)||a(!1):t=i.getGlobalDir(),this._defaultDir=t,this.reset()}return e.prototype.reset=function(){this._lastDir=this._defaultDir},e.prototype.getDirection=function(e){return this._lastDir=o.getDirection(e,this._lastDir),this._lastDir},e}();e.exports=s},function(e,t,n){"use strict";var r=n(28),o=n(11),i=n(211),a=n(10),s=o.OrderedMap,l=o.List,u=function(e,t,n){if(e){var r=t.get(e);r&&t.set(e,n(r))}},c=function(e,t,n,r,o){if(!o)return e;var i="after"===r,a=t.getKey(),s=n.getKey(),c=t.getParentKey(),p=t.getNextSiblingKey(),f=t.getPrevSiblingKey(),d=n.getParentKey(),h=i?n.getNextSiblingKey():s,v=i?s:n.getPrevSiblingKey();return e.withMutations(function(e){u(c,e,function(e){var t=e.getChildKeys();return e.merge({children:t.delete(t.indexOf(a))})}),u(f,e,function(e){return e.merge({nextSibling:p})}),u(p,e,function(e){return e.merge({prevSibling:f})}),u(h,e,function(e){return e.merge({prevSibling:a})}),u(v,e,function(e){return e.merge({nextSibling:a})}),u(d,e,function(e){var t=e.getChildKeys(),n=t.indexOf(s),r=i?n+1:0!==n?n-1:0,o=t.toArray();return o.splice(r,0,a),e.merge({children:l(o)})}),u(a,e,function(e){return e.merge({nextSibling:h,prevSibling:v,parent:d})})})},p=function(e,t,n,o){"replace"===o&&a(!1);var l=n.getKey(),u=t.getKey();u===l&&a(!1);var p=e.getBlockMap(),f=t instanceof r,d=[t],h=p.delete(u);f&&(d=[],h=p.withMutations(function(e){var n=t.getNextSiblingKey(),r=i(t,e);e.toSeq().skipUntil(function(e){return e.getKey()===u}).takeWhile(function(e){var t=e.getKey(),o=t===u,i=n&&t!==n,a=!n&&e.getParentKey()&&(!r||t!==r);return!!(o||i||a)}).forEach(function(t){d.push(t),e.delete(t.getKey())})}));var v=h.toSeq().takeUntil(function(e){return e===n}),m=h.toSeq().skipUntil(function(e){return e===n}).skip(1),y=d.map(function(e){return[e.getKey(),e]}),g=s();if("before"===o){var b=e.getBlockBefore(l);b&&b.getKey()===t.getKey()&&a(!1),g=v.concat([].concat(y,[[l,n]]),m).toOrderedMap()}else if("after"===o){var C=e.getBlockAfter(l);C&&C.getKey()===u&&a(!1),g=v.concat([[l,n]].concat(y),m).toOrderedMap()}return e.merge({blockMap:c(g,t,n,o,f),selectionBefore:e.getSelectionAfter(),selectionAfter:e.getSelectionAfter().merge({anchorKey:u,focusKey:u})})};e.exports=p},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t,n){for(var r=t;r<n;r++)if(null!=e[r])return!1;return!0}function i(e,t,n,r){for(var o=t;o<n;o++)e[o]=r}var a=n(11),s=a.List,l=function(){function e(t){r(this,e),this._decorators=t.slice()}return e.prototype.getDecorations=function(e,t){var n=Array(e.getText().length).fill(null);return this._decorators.forEach(function(r,a){var s=0;(0,r.strategy)(e,function(e,t){o(n,e,t)&&(i(n,e,t,a+"."+s),s++)},t)}),s(n)},e.prototype.getComponentForKey=function(e){var t=parseInt(e.split(".")[0],10);return this._decorators[t].component},e.prototype.getPropsForKey=function(e){var t=parseInt(e.split(".")[0],10);return this._decorators[t].props},e}();e.exports=l},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(16),s=a||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(150),u=n(215),c=n(439),p=n(440),f=n(463),d=n(466),h=n(499),v=n(12),m=n(0),y=n(9),g=n(219),b=n(154),C=n(38),w=n(66),S=n(86),x=n(39),_=n(232),k=n(155),E=n(10),O=n(34),T=C.isBrowser("IE"),N=!T,P={edit:d,composite:c,drag:f,cut:null,render:null},M=function(e){function t(n){r(this,t);var i=o(this,e.call(this,n));return i.focus=function(e){var t=i.props.editorState,n=t.getSelection().getHasFocus(),r=y.findDOMNode(i.editor);if(r){var o=b.getScrollParent(r),a=e||k(o),s=a.x,l=a.y;r instanceof HTMLElement||E(!1),r.focus(),o===window?window.scrollTo(s,l):g.setTop(o,l),n||i.update(v.forceSelection(t,t.getSelection()))}},i.blur=function(){var e=y.findDOMNode(i.editor);e instanceof HTMLElement||E(!1),e.blur()},i.setMode=function(e){i._handler=P[e]},i.exitCurrentMode=function(){i.setMode("edit")},i.restoreEditorDOM=function(e){i.setState({contentsKey:i.state.contentsKey+1},function(){i.focus(e)})},i.setClipboard=function(e){i._clipboard=e},i.getClipboard=function(){return i._clipboard},i.update=function(e){i._latestEditorState=e,i.props.onChange(e)},i.onDragEnter=function(){i._dragCount++},i.onDragLeave=function(){0===--i._dragCount&&i.exitCurrentMode()},i._blockSelectEvents=!1,i._clipboard=null,i._handler=null,i._dragCount=0,i._editorKey=n.editorKey||x(),i._placeholderAccessibilityID="placeholder-"+i._editorKey,i._latestEditorState=n.editorState,i._latestCommittedEditorState=n.editorState,i._onBeforeInput=i._buildHandler("onBeforeInput"),i._onBlur=i._buildHandler("onBlur"),i._onCharacterData=i._buildHandler("onCharacterData"),i._onCompositionEnd=i._buildHandler("onCompositionEnd"),i._onCompositionStart=i._buildHandler("onCompositionStart"),i._onCopy=i._buildHandler("onCopy"),i._onCut=i._buildHandler("onCut"),i._onDragEnd=i._buildHandler("onDragEnd"),i._onDragOver=i._buildHandler("onDragOver"),i._onDragStart=i._buildHandler("onDragStart"),i._onDrop=i._buildHandler("onDrop"),i._onInput=i._buildHandler("onInput"),i._onFocus=i._buildHandler("onFocus"),i._onKeyDown=i._buildHandler("onKeyDown"),i._onKeyPress=i._buildHandler("onKeyPress"),i._onKeyUp=i._buildHandler("onKeyUp"),i._onMouseDown=i._buildHandler("onMouseDown"),i._onMouseUp=i._buildHandler("onMouseUp"),i._onPaste=i._buildHandler("onPaste"),i._onSelect=i._buildHandler("onSelect"),i.getEditorKey=function(){return i._editorKey},i.state={contentsKey:0},i}return i(t,e),t.prototype._buildHandler=function(e){var t=this;return function(n){if(!t.props.readOnly){var r=t._handler&&t._handler[e];r&&r(t,n)}}},t.prototype._showPlaceholder=function(){return!!this.props.placeholder&&!this.props.editorState.isInCompositionMode()&&!this.props.editorState.getCurrentContent().hasText()},t.prototype._renderPlaceholder=function(){if(this._showPlaceholder()){var e={text:O(this.props.placeholder),editorState:this.props.editorState,textAlignment:this.props.textAlignment,accessibilityID:this._placeholderAccessibilityID};return m.createElement(h,e)}return null},t.prototype.render=function(){var e=this,t=this.props,n=t.blockRenderMap,r=t.blockRendererFn,o=t.blockStyleFn,i=t.customStyleFn,a=t.customStyleMap,l=t.editorState,c=t.readOnly,f=t.textAlignment,d=t.textDirectionality,h=w({"DraftEditor/root":!0,"DraftEditor/alignLeft":"left"===f,"DraftEditor/alignRight":"right"===f,"DraftEditor/alignCenter":"center"===f}),v={outline:"none",userSelect:"text",WebkitUserSelect:"text",whiteSpace:"pre-wrap",wordWrap:"break-word"},y=this.props.role||"textbox",g="combobox"===y?!!this.props.ariaExpanded:null,b={blockRenderMap:n,blockRendererFn:r,blockStyleFn:o,customStyleMap:s({},u,a),customStyleFn:i,editorKey:this._editorKey,editorState:l,key:"contents"+this.state.contentsKey,textDirectionality:d};return m.createElement("div",{className:h},this._renderPlaceholder(),m.createElement("div",{className:w("DraftEditor/editorContainer"),ref:function(t){return e.editorContainer=t}},m.createElement("div",{"aria-activedescendant":c?null:this.props.ariaActiveDescendantID,"aria-autocomplete":c?null:this.props.ariaAutoComplete,"aria-controls":c?null:this.props.ariaControls,"aria-describedby":this.props.ariaDescribedBy||this._placeholderAccessibilityID,"aria-expanded":c?null:g,"aria-label":this.props.ariaLabel,"aria-labelledby":this.props.ariaLabelledBy,"aria-multiline":this.props.ariaMultiline,autoCapitalize:this.props.autoCapitalize,autoComplete:this.props.autoComplete,autoCorrect:this.props.autoCorrect,className:w({notranslate:!c,"public/DraftEditor/content":!0}),contentEditable:!c,"data-testid":this.props.webDriverTestID,onBeforeInput:this._onBeforeInput,onBlur:this._onBlur,onCompositionEnd:this._onCompositionEnd,onCompositionStart:this._onCompositionStart,onCopy:this._onCopy,onCut:this._onCut,onDragEnd:this._onDragEnd,onDragEnter:this.onDragEnter,onDragLeave:this.onDragLeave,onDragOver:this._onDragOver,onDragStart:this._onDragStart,onDrop:this._onDrop,onFocus:this._onFocus,onInput:this._onInput,onKeyDown:this._onKeyDown,onKeyPress:this._onKeyPress,onKeyUp:this._onKeyUp,onMouseUp:this._onMouseUp,onPaste:this._onPaste,onSelect:this._onSelect,ref:function(t){return e.editor=t},role:c?null:y,spellCheck:N&&this.props.spellCheck,style:v,suppressContentEditableWarning:!0,tabIndex:this.props.tabIndex},m.createElement(p,b))))},t.prototype.componentDidMount=function(){this.setMode("edit"),T&&document.execCommand("AutoUrlDetect",!1,!1)},t.prototype.componentWillUpdate=function(e){this._blockSelectEvents=!0,this._latestEditorState=e.editorState},t.prototype.componentDidUpdate=function(){this._blockSelectEvents=!1,this._latestCommittedEditorState=this.props.editorState},t}(m.Component);M.defaultProps={blockRenderMap:l,blockRendererFn:S.thatReturnsNull,blockStyleFn:S.thatReturns(""),keyBindingFn:_,readOnly:!1,spellCheck:!1,stripPastedStyles:!1},e.exports=M},function(e,t,n){"use strict";var r=n(45),o=n(22),i=n(12),a=n(151),s=n(152),l=n(79),u=n(216),c=!1,p=!1,f="",d={onBeforeInput:function(e,t){f=(f||"")+t.data},onCompositionStart:function(e){p=!0},onCompositionEnd:function(e){c=!1,p=!1,setTimeout(function(){c||d.resolveComposition(e)},20)},onKeyDown:function(e,t){if(!p)return d.resolveComposition(e),void e._onKeyDown(t);t.which!==a.RIGHT&&t.which!==a.LEFT||t.preventDefault()},onKeyPress:function(e,t){t.which===a.RETURN&&t.preventDefault()},resolveComposition:function(e){if(!p){c=!0;var t=f;f="";var n=i.set(e._latestEditorState,{inCompositionMode:!1}),a=n.getCurrentInlineStyle(),d=s(n.getCurrentContent(),n.getSelection()),h=!t||u(n)||a.size>0||null!==d;if(h&&e.restoreEditorDOM(),e.exitCurrentMode(),t){if(r.draft_handlebeforeinput_composed_text&&e.props.handleBeforeInput&&l(e.props.handleBeforeInput(t,n)))return;var v=o.replaceText(n.getCurrentContent(),n.getSelection(),t,a,d);return void e.update(i.push(n,v,"insert-characters"))}h&&e.update(i.set(n,{nativelyRenderedContent:null,forceSelection:!0}))}}};e.exports=d},function(e,t,n){"use strict";var r=n(441);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(16),s=a||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(217),u=n(80),c=(n(12),n(0)),p=n(66),f=n(462),d=n(34),h=function(e,t,n,r){return p({"public/DraftStyleDefault/unorderedListItem":"unordered-list-item"===e,"public/DraftStyleDefault/orderedListItem":"ordered-list-item"===e,"public/DraftStyleDefault/reset":n,"public/DraftStyleDefault/depth0":0===t,"public/DraftStyleDefault/depth1":1===t,"public/DraftStyleDefault/depth2":2===t,"public/DraftStyleDefault/depth3":3===t,"public/DraftStyleDefault/depth4":4===t,"public/DraftStyleDefault/listLTR":"LTR"===r,"public/DraftStyleDefault/listRTL":"RTL"===r})},v=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.shouldComponentUpdate=function(e){var t=this.props.editorState,n=e.editorState;if(t.getDirectionMap()!==n.getDirectionMap())return!0;if(t.getSelection().getHasFocus()!==n.getSelection().getHasFocus())return!0;var r=n.getNativelyRenderedContent(),o=t.isInCompositionMode(),i=n.isInCompositionMode();if(t===n||null!==r&&n.getCurrentContent()===r||o&&i)return!1;var a=t.getCurrentContent(),s=n.getCurrentContent(),l=t.getDecorator(),u=n.getDecorator();return o!==i||a!==s||l!==u||n.mustForceSelection()},t.prototype.render=function(){for(var e=this.props,t=e.blockRenderMap,n=e.blockRendererFn,r=e.blockStyleFn,o=e.customStyleMap,i=e.customStyleFn,a=e.editorState,p=e.editorKey,v=e.textDirectionality,m=a.getCurrentContent(),y=a.getSelection(),g=a.mustForceSelection(),b=a.getDecorator(),C=d(a.getDirectionMap()),w=m.getBlocksAsArray(),S=[],x=null,_=null,k=0;k<w.length;k++){var E=w[k],O=E.getKey(),T=E.getType(),N=n(E),P=void 0,M=void 0,D=void 0;N&&(P=N.component,M=N.props,D=N.editable);var I=v||C.get(O),A=u.encode(O,0,0),j={contentState:m,block:E,blockProps:M,blockStyleFn:r,customStyleMap:o,customStyleFn:i,decorator:b,direction:I,forceSelection:g,key:O,offsetKey:A,selection:y,tree:a.getBlockTree(O)},R=t.get(T)||t.get("unstyled"),L=R.wrapper,K=R.element||t.get("unstyled").element,F=E.getDepth(),V="";if(r&&(V=r(E)),"li"===K){V=f(V,h(T,F,_!==L||null===x||F>x,I))}var z=P||l,B={className:V,"data-block":!0,"data-editor":p,"data-offset-key":A,key:O};void 0!==D&&(B=s({},B,{contentEditable:D,suppressContentEditableWarning:!0}));var W=c.createElement(K,B,c.createElement(z,j));S.push({block:W,wrapperTemplate:L,key:O,offsetKey:A}),x=L?E.getDepth():null,_=L}for(var H=[],U=0;U<S.length;){var q=S[U];if(q.wrapperTemplate){var Y=[];do{Y.push(S[U].block),U++}while(U<S.length&&S[U].wrapperTemplate===q.wrapperTemplate);var G=c.cloneElement(q.wrapperTemplate,{key:q.key+"-wrap","data-offset-key":q.offsetKey},Y);H.push(G)}else H.push(q.block),U++}return c.createElement("div",{"data-contents":"true"},H)},t}(c.Component);e.exports=v},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(16),s=n(443),l=n(0),u=n(9),c=n(10),p=n(450),f=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype._setSelection=function(){var e=this.props.selection;if(null!=e&&e.getHasFocus()){var t=this.props,n=t.block,r=t.start,o=t.text,i=n.getKey(),a=r+o.length;if(e.hasEdgeWithin(i,r,a)){var s=u.findDOMNode(this);s||c(!1);var l=s.firstChild;l||c(!1);var f=void 0;l.nodeType===Node.TEXT_NODE?f=l:"BR"===l.tagName?f=s:(f=l.firstChild)||c(!1),p(e,f,i,r,a)}}},t.prototype.shouldComponentUpdate=function(e){var t=u.findDOMNode(this.leaf);return t||c(!1),t.textContent!==e.text||e.styleSet!==this.props.styleSet||e.forceSelection},t.prototype.componentDidUpdate=function(){this._setSelection()},t.prototype.componentDidMount=function(){this._setSelection()},t.prototype.render=function(){var e=this,t=this.props.block,n=this.props.text;n.endsWith("\n")&&this.props.isLast&&(n+="\n");var r=this.props,o=r.customStyleMap,i=r.customStyleFn,u=r.offsetKey,c=r.styleSet,p=c.reduce(function(e,t){var n={},r=o[t];return void 0!==r&&e.textDecoration!==r.textDecoration&&(n.textDecoration=[e.textDecoration,r.textDecoration].join(" ").trim()),a(e,r,n)},{});if(i){var f=i(c,t);p=a(p,f)}return l.createElement("span",{"data-offset-key":u,ref:function(t){return e.leaf=t},style:p},l.createElement(s,null,n))},t}(l.Component);e.exports=f},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e){return p?"\n"===e.textContent:"BR"===e.tagName}var s=n(0),l=n(9),u=n(38),c=n(10),p=u.isBrowser("IE <= 11"),f=p?s.createElement("span",{key:"A","data-text":"true"},"\n"):s.createElement("br",{key:"A","data-text":"true"}),d=p?s.createElement("span",{key:"B","data-text":"true"},"\n"):s.createElement("br",{key:"B","data-text":"true"}),h=function(e){function t(n){r(this,t);var i=o(this,e.call(this,n));return i._forceFlag=!1,i}return i(t,e),t.prototype.shouldComponentUpdate=function(e){var t=l.findDOMNode(this),n=""===e.children;return t instanceof Element||c(!1),n?!a(t):t.textContent!==e.children},t.prototype.componentDidMount=function(){this._forceFlag=!this._forceFlag},t.prototype.componentDidUpdate=function(){this._forceFlag=!this._forceFlag},t.prototype.render=function(){return""===this.props.children?this._forceFlag?f:d:s.createElement("span",{key:this._forceFlag?"A":"B","data-text":"true"},this.props.children)},t}(s.Component);e.exports=h},function(e,t,n){"use strict";var r=n(445),o="Unknown",i={"Mac OS":"Mac OS X"},a=new r,s=a.getResult(),l=function(e){if(!e)return{major:"",minor:""};var t=e.split(".");return{major:t[0],minor:t[1]}}(s.browser.version),u={browserArchitecture:s.cpu.architecture||o,browserFullVersion:s.browser.version||o,browserMinorVersion:l.minor||o,browserName:s.browser.name||o,browserVersion:s.browser.major||o,deviceName:s.device.model||o,engineName:s.engine.name||o,engineVersion:s.engine.version||o,platformArchitecture:s.cpu.architecture||o,platformName:function(e){return i[e]||e}(s.os.name)||o,platformVersion:s.os.version||o,platformFullVersion:s.os.version||o};e.exports=u},function(e,t,n){var r;!function(o,i){"use strict";var a="model",s="name",l="type",u="vendor",c="version",p="mobile",f="tablet",d={extend:function(e,t){var n={};for(var r in e)t[r]&&t[r].length%2==0?n[r]=t[r].concat(e[r]):n[r]=e[r];return n},has:function(e,t){return"string"==typeof e&&-1!==t.toLowerCase().indexOf(e.toLowerCase())},lowerize:function(e){return e.toLowerCase()},major:function(e){return"string"==typeof e?e.replace(/[^\d\.]/g,"").split(".")[0]:void 0},trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},h={rgx:function(e,t){for(var n,r,o,i,a,s,l=0;l<t.length&&!a;){var u=t[l],c=t[l+1];for(n=r=0;n<u.length&&!a;)if(a=u[n++].exec(e))for(o=0;o<c.length;o++)s=a[++r],i=c[o],"object"==typeof i&&i.length>0?2==i.length?"function"==typeof i[1]?this[i[0]]=i[1].call(this,s):this[i[0]]=i[1]:3==i.length?"function"!=typeof i[1]||i[1].exec&&i[1].test?this[i[0]]=s?s.replace(i[1],i[2]):void 0:this[i[0]]=s?i[1].call(this,s,i[2]):void 0:4==i.length&&(this[i[0]]=s?i[3].call(this,s.replace(i[1],i[2])):void 0):this[i]=s||void 0;l+=2}},str:function(e,t){for(var n in t)if("object"==typeof t[n]&&t[n].length>0){for(var r=0;r<t[n].length;r++)if(d.has(t[n][r],e))return"?"===n?void 0:n}else if(d.has(t[n],e))return"?"===n?void 0:n;return e}},v={browser:{oldsafari:{version:{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}}},device:{amazon:{model:{"Fire Phone":["SD","KF"]}},sprint:{model:{"Evo Shift 4G":"7373KT"},vendor:{HTC:"APA",Sprint:"Sprint"}}},os:{windows:{version:{ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2000:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"}}}},m={browser:[[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i,/(opera).+version\/([\w\.]+)/i,/(opera)[\/\s]+([\w\.]+)/i],[s,c],[/(opios)[\/\s]+([\w\.]+)/i],[[s,"Opera Mini"],c],[/\s(opr)\/([\w\.]+)/i],[[s,"Opera"],c],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(rekonq)\/([\w\.]+)*/i,/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser)\/([\w\.-]+)/i],[s,c],[/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i],[[s,"IE"],c],[/(edge)\/((\d+)?[\w\.]+)/i],[s,c],[/(yabrowser)\/([\w\.]+)/i],[[s,"Yandex"],c],[/(puffin)\/([\w\.]+)/i],[[s,"Puffin"],c],[/((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],[[s,"UCBrowser"],c],[/(comodo_dragon)\/([\w\.]+)/i],[[s,/_/g," "],c],[/(micromessenger)\/([\w\.]+)/i],[[s,"WeChat"],c],[/(QQ)\/([\d\.]+)/i],[s,c],[/m?(qqbrowser)[\/\s]?([\w\.]+)/i],[s,c],[/xiaomi\/miuibrowser\/([\w\.]+)/i],[c,[s,"MIUI Browser"]],[/;fbav\/([\w\.]+);/i],[c,[s,"Facebook"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],[c,[s,"Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[[s,/(.+)/,"$1 WebView"],c],[/((?:oculus|samsung)browser)\/([\w\.]+)/i],[[s,/(.+(?:g|us))(.+)/,"$1 $2"],c],[/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i],[c,[s,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],[s,c],[/(dolfin)\/([\w\.]+)/i],[[s,"Dolphin"],c],[/((?:android.+)crmo|crios)\/([\w\.]+)/i],[[s,"Chrome"],c],[/(coast)\/([\w\.]+)/i],[[s,"Opera Coast"],c],[/fxios\/([\w\.-]+)/i],[c,[s,"Firefox"]],[/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i],[c,[s,"Mobile Safari"]],[/version\/([\w\.]+).+?(mobile\s?safari|safari)/i],[c,s],[/webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[[s,"GSA"],c],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],[s,[c,h.str,v.browser.oldsafari.version]],[/(konqueror)\/([\w\.]+)/i,/(webkit|khtml)\/([\w\.]+)/i],[s,c],[/(navigator|netscape)\/([\w\.-]+)/i],[[s,"Netscape"],c],[/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]+)*/i,/(ice\s?browser)\/v?([\w\._]+)/i,/(mosaic)[\/\s]([\w\.]+)/i],[s,c]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",d.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",d.lowerize]],[/(sun4\w)[;\)]/i],[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i],[["architecture",d.lowerize]]],device:[[/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i],[a,u,[l,f]],[/applecoremedia\/[\w\.]+ \((ipad)/],[a,[u,"Apple"],[l,f]],[/(apple\s{0,1}tv)/i],[[a,"Apple TV"],[u,"Apple"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad)/i,/(hp).+(tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i],[u,a,[l,f]],[/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i],[a,[u,"Amazon"],[l,f]],[/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i],[[a,h.str,v.device.amazon.model],[u,"Amazon"],[l,p]],[/\((ip[honed|\s\w*]+);.+(apple)/i],[a,u,[l,p]],[/\((ip[honed|\s\w*]+);/i],[a,[u,"Apple"],[l,p]],[/(blackberry)[\s-]?(\w+)/i,/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i],[u,a,[l,p]],[/\(bb10;\s(\w+)/i],[a,[u,"BlackBerry"],[l,p]],[/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i],[a,[u,"Asus"],[l,f]],[/(sony)\s(tablet\s[ps])\sbuild\//i,/(sony)?(?:sgp.+)\sbuild\//i],[[u,"Sony"],[a,"Xperia Tablet"],[l,f]],[/android.+\s([c-g]\d{4}|so[-l]\w+)\sbuild\//i],[a,[u,"Sony"],[l,p]],[/\s(ouya)\s/i,/(nintendo)\s([wids3u]+)/i],[u,a,[l,"console"]],[/android.+;\s(shield)\sbuild/i],[a,[u,"Nvidia"],[l,"console"]],[/(playstation\s[34portablevi]+)/i],[a,[u,"Sony"],[l,"console"]],[/(sprint\s(\w+))/i],[[u,h.str,v.device.sprint.vendor],[a,h.str,v.device.sprint.model],[l,p]],[/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i],[u,a,[l,f]],[/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i,/(zte)-(\w+)*/i,/(alcatel|geeksphone|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i],[u,[a,/_/g," "],[l,p]],[/(nexus\s9)/i],[a,[u,"HTC"],[l,f]],[/d\/huawei([\w\s-]+)[;\)]/i,/(nexus\s6p)/i],[a,[u,"Huawei"],[l,p]],[/(microsoft);\s(lumia[\s\w]+)/i],[u,a,[l,p]],[/[\s\(;](xbox(?:\sone)?)[\s\);]/i],[a,[u,"Microsoft"],[l,"console"]],[/(kin\.[onetw]{3})/i],[[a,/\./g," "],[u,"Microsoft"],[l,p]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,/mot[\s-]?(\w+)*/i,/(XT\d{3,4}) build\//i,/(nexus\s6)/i],[a,[u,"Motorola"],[l,p]],[/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],[a,[u,"Motorola"],[l,f]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[[u,d.trim],[a,d.trim],[l,"smarttv"]],[/hbbtv.+maple;(\d+)/i],[[a,/^/,"SmartTV"],[u,"Samsung"],[l,"smarttv"]],[/\(dtv[\);].+(aquos)/i],[a,[u,"Sharp"],[l,"smarttv"]],[/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,/((SM-T\w+))/i],[[u,"Samsung"],a,[l,f]],[/smart-tv.+(samsung)/i],[u,[l,"smarttv"],a],[/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,/sec-((sgh\w+))/i],[[u,"Samsung"],a,[l,p]],[/sie-(\w+)*/i],[a,[u,"Siemens"],[l,p]],[/(maemo|nokia).*(n900|lumia\s\d+)/i,/(nokia)[\s_-]?([\w-]+)*/i],[[u,"Nokia"],a,[l,p]],[/android\s3\.[\s\w;-]{10}(a\d{3})/i],[a,[u,"Acer"],[l,f]],[/android.+([vl]k\-?\d{3})\s+build/i],[a,[u,"LG"],[l,f]],[/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i],[[u,"LG"],a,[l,f]],[/(lg) netcast\.tv/i],[u,a,[l,"smarttv"]],[/(nexus\s[45])/i,/lg[e;\s\/-]+(\w+)*/i,/android.+lg(\-?[\d\w]+)\s+build/i],[a,[u,"LG"],[l,p]],[/android.+(ideatab[a-z0-9\-\s]+)/i],[a,[u,"Lenovo"],[l,f]],[/linux;.+((jolla));/i],[u,a,[l,p]],[/((pebble))app\/[\d\.]+\s/i],[u,a,[l,"wearable"]],[/android.+;\s(oppo)\s?([\w\s]+)\sbuild/i],[u,a,[l,p]],[/crkey/i],[[a,"Chromecast"],[u,"Google"]],[/android.+;\s(glass)\s\d/i],[a,[u,"Google"],[l,"wearable"]],[/android.+;\s(pixel c)\s/i],[a,[u,"Google"],[l,f]],[/android.+;\s(pixel xl|pixel)\s/i],[a,[u,"Google"],[l,p]],[/android.+(\w+)\s+build\/hm\1/i,/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i,/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i,/android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[a,/_/g," "],[u,"Xiaomi"],[l,p]],[/android.+(mi[\s\-_]*(?:pad)?(?:[\s_]*[\w\s]+)?)\s+build/i],[[a,/_/g," "],[u,"Xiaomi"],[l,f]],[/android.+;\s(m[1-5]\snote)\sbuild/i],[a,[u,"Meizu"],[l,f]],[/android.+a000(1)\s+build/i],[a,[u,"OnePlus"],[l,p]],[/android.+[;\/]\s*(RCT[\d\w]+)\s+build/i],[a,[u,"RCA"],[l,f]],[/android.+[;\/]\s*(Venue[\d\s]*)\s+build/i],[a,[u,"Dell"],[l,f]],[/android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i],[a,[u,"Verizon"],[l,f]],[/android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i],[[u,"Barnes & Noble"],a,[l,f]],[/android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i],[a,[u,"NuVision"],[l,f]],[/android.+[;\/]\s*(zte)?.+(k\d{2})\s+build/i],[[u,"ZTE"],a,[l,f]],[/android.+[;\/]\s*(gen\d{3})\s+build.*49h/i],[a,[u,"Swiss"],[l,p]],[/android.+[;\/]\s*(zur\d{3})\s+build/i],[a,[u,"Swiss"],[l,f]],[/android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i],[a,[u,"Zeki"],[l,f]],[/(android).+[;\/]\s+([YR]\d{2}x?.*)\s+build/i,/android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(.+)\s+build/i],[[u,"Dragon Touch"],a,[l,f]],[/android.+[;\/]\s*(NS-?.+)\s+build/i],[a,[u,"Insignia"],[l,f]],[/android.+[;\/]\s*((NX|Next)-?.+)\s+build/i],[a,[u,"NextBook"],[l,f]],[/android.+[;\/]\s*(Xtreme\_?)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i],[[u,"Voice"],a,[l,p]],[/android.+[;\/]\s*(LVTEL\-?)?(V1[12])\s+build/i],[[u,"LvTel"],a,[l,p]],[/android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i],[a,[u,"Envizen"],[l,f]],[/android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(.*\b)\s+build/i],[u,a,[l,f]],[/android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i],[a,[u,"MachSpeed"],[l,f]],[/android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i],[u,a,[l,f]],[/android.+[;\/]\s*TU_(1491)\s+build/i],[a,[u,"Rotor"],[l,f]],[/android.+(KS(.+))\s+build/i],[a,[u,"Amazon"],[l,f]],[/android.+(Gigaset)[\s\-]+(Q.+)\s+build/i],[u,a,[l,f]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[[l,d.lowerize],u,a],[/(android.+)[;\/].+build/i],[a,[u,"Generic"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],[c,[s,"EdgeHTML"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],[s,c],[/rv\:([\w\.]+).*(gecko)/i],[c,s]],os:[[/microsoft\s(windows)\s(vista|xp)/i],[s,c],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i,/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i],[s,[c,h.str,v.os.windows.version]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[[s,"Windows"],[c,h.str,v.os.windows.version]],[/\((bb)(10);/i],[[s,"BlackBerry"],c],[/(blackberry)\w*\/?([\w\.]+)*/i,/(tizen)[\/\s]([\w\.]+)/i,/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,/linux;.+(sailfish);/i],[s,c],[/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i],[[s,"Symbian"],c],[/\((series40);/i],[s],[/mozilla.+\(mobile;.+gecko.+firefox/i],[[s,"Firefox OS"],c],[/(nintendo|playstation)\s([wids34portablevu]+)/i,/(mint)[\/\s\(]?(\w+)*/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,/(hurd|linux)\s?([\w\.]+)*/i,/(gnu)\s?([\w\.]+)*/i],[s,c],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[[s,"Chromium OS"],c],[/(sunos)\s?([\w\.]+\d)*/i],[[s,"Solaris"],c],[/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i],[s,c],[/(haiku)\s(\w+)/i],[s,c],[/cfnetwork\/.+darwin/i,/ip[honead]+(?:.*os\s([\w]+)\slike\smac|;\sopera)/i],[[c,/_/g,"."],[s,"iOS"]],[/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,/(macintosh|mac(?=_powerpc)\s)/i],[[s,"Mac OS"],[c,/_/g,"."]],[/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,/(unix)\s?([\w\.]+)*/i],[s,c]]},y=function(e,t){if("object"==typeof e&&(t=e,e=void 0),!(this instanceof y))return new y(e,t).getResult();var n=e||(o&&o.navigator&&o.navigator.userAgent?o.navigator.userAgent:""),r=t?d.extend(m,t):m;return this.getBrowser=function(){var e={name:void 0,version:void 0};return h.rgx.call(e,n,r.browser),e.major=d.major(e.version),e},this.getCPU=function(){var e={architecture:void 0};return h.rgx.call(e,n,r.cpu),e},this.getDevice=function(){var e={vendor:void 0,model:void 0,type:void 0};return h.rgx.call(e,n,r.device),e},this.getEngine=function(){var e={name:void 0,version:void 0};return h.rgx.call(e,n,r.engine),e},this.getOS=function(){var e={name:void 0,version:void 0};return h.rgx.call(e,n,r.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return n},this.setUA=function(e){return n=e,this},this};y.VERSION="0.7.17",y.BROWSER={NAME:s,MAJOR:"major",VERSION:c},y.CPU={ARCHITECTURE:"architecture"},y.DEVICE={MODEL:a,VENDOR:u,TYPE:l,CONSOLE:"console",MOBILE:p,SMARTTV:"smarttv",TABLET:f,WEARABLE:"wearable",EMBEDDED:"embedded"},y.ENGINE={NAME:s,VERSION:c},y.OS={NAME:s,VERSION:c},void 0!==t?(void 0!==e&&e.exports&&(t=e.exports=y),t.UAParser=y):n(446)?void 0!==(r=function(){return y}.call(t,n,t,e))&&(e.exports=r):o&&(o.UAParser=y);var g=o&&(o.jQuery||o.Zepto);if(void 0!==g){var b=new y;g.ua=b.getResult(),g.ua.get=function(){return b.getUA()},g.ua.set=function(e){b.setUA(e);var t=b.getResult();for(var n in t)g.ua[n]=t[n]}}}("object"==typeof window?window:this)},function(e,t){(function(t){e.exports=t}).call(t,{})},function(e,t,n){"use strict";function r(e,t){var n=e.split(S);return n.length>1?n.some(function(e){return E.contains(e,t)}):(e=n[0].trim(),o(e,t))}function o(e,t){var n=e.split(x);if(n.length>0&&n.length<=2||C(!1),1===n.length)return i(n[0],t);var r=n[0],o=n[1];return h(r)&&h(o)||C(!1),i(">="+r,t)&&i("<="+o,t)}function i(e,t){if(""===(e=e.trim()))return!0;var n=t.split(w),r=f(e),o=r.modifier,i=r.rangeComponents;switch(o){case"<":return a(n,i);case"<=":return s(n,i);case">=":return u(n,i);case">":return c(n,i);case"~":case"~>":return p(n,i);default:return l(n,i)}}function a(e,t){return-1===b(e,t)}function s(e,t){var n=b(e,t);return-1===n||0===n}function l(e,t){return 0===b(e,t)}function u(e,t){var n=b(e,t);return 1===n||0===n}function c(e,t){return 1===b(e,t)}function p(e,t){var n=t.slice(),r=t.slice();r.length>1&&r.pop();var o=r.length-1,i=parseInt(r[o],10);return d(i)&&(r[o]=i+1+""),u(e,n)&&a(e,r)}function f(e){var t=e.split(w),n=t[0].match(_);return n||C(!1),{modifier:n[1],rangeComponents:[n[2]].concat(t.slice(1))}}function d(e){return!isNaN(e)&&isFinite(e)}function h(e){return!f(e).modifier}function v(e,t){for(var n=e.length;n<t;n++)e[n]="0"}function m(e,t){e=e.slice(),t=t.slice(),v(e,t.length);for(var n=0;n<t.length;n++){var r=t[n].match(/^[x*]$/i);if(r&&(t[n]=e[n]="0","*"===r[0]&&n===t.length-1))for(var o=n;o<e.length;o++)e[o]="0"}return v(t,e.length),[e,t]}function y(e,t){var n=e.match(k)[1],r=t.match(k)[1],o=parseInt(n,10),i=parseInt(r,10);return d(o)&&d(i)&&o!==i?g(o,i):g(e,t)}function g(e,t){return typeof e!=typeof t&&C(!1),e>t?1:e<t?-1:0}function b(e,t){for(var n=m(e,t),r=n[0],o=n[1],i=0;i<o.length;i++){var a=y(r[i],o[i]);if(a)return a}return 0}var C=n(10),w=/\./,S=/\|\|/,x=/\s+\-\s+/,_=/^(<=|<|=|>=|~>|~|>|)?\s*(.+)/,k=/^(\d*)(.*)/,E={contains:function(e,t){return r(e.trim(),t.trim())}};e.exports=E},function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var i in e)o.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=r},function(e,t,n){"use strict";(function(t){function r(e,t){if(!e)return"[empty]";var n=o(e,t);return n.nodeType===Node.TEXT_NODE?n.textContent:(n instanceof Element||d(!1),n.outerHTML)}function o(e,t){var n=void 0!==t?t(e):[];if(e.nodeType===Node.TEXT_NODE){var r=e.textContent.length;return document.createTextNode("[text "+r+(n.length?" | "+n.join(", "):"")+"]")}var i=e.cloneNode();1===i.nodeType&&n.length&&i.setAttribute("data-labels",n.join(", "));for(var a=e.childNodes,s=0;s<a.length;s++)i.appendChild(o(a[s],t));return i}function i(e,t){for(var n=e;n;){if(n instanceof Element&&n.hasAttribute("contenteditable"))return r(n,t);n=n.parentNode}return"Could not find contentEditable parent of node"}function a(e){return null===e.nodeValue?e.childNodes.length:e.nodeValue.length}function s(e,n,r,o,i){if(p(document.documentElement,n)){var a=t.getSelection(),s=e.getAnchorKey(),c=e.getAnchorOffset(),f=e.getFocusKey(),d=e.getFocusOffset(),h=e.getIsBackward();if(!a.extend&&h){var v=s,m=c;s=f,c=d,f=v,d=m,h=!1}var y=s===r&&o<=c&&i>=c,g=f===r&&o<=d&&i>=d;if(y&&g)return a.removeAllRanges(),u(a,n,c-o,e),void l(a,n,d-o,e);if(h){if(g&&(a.removeAllRanges(),u(a,n,d-o,e)),y){var b=a.focusNode,C=a.focusOffset;a.removeAllRanges(),u(a,n,c-o,e),l(a,b,C,e)}}else y&&(a.removeAllRanges(),u(a,n,c-o,e)),g&&l(a,n,d-o,e)}}function l(e,t,n,r){var o=f();if(e.extend&&p(o,t)){n>a(t)&&c.logSelectionStateFailure({anonymizedDom:i(t),extraParams:JSON.stringify({offset:n}),selectionState:JSON.stringify(r.toJS())});var s=t===e.focusNode;try{e.extend(t,n)}catch(a){throw c.logSelectionStateFailure({anonymizedDom:i(t,function(t){var n=[];return t===o&&n.push("active element"),t===e.anchorNode&&n.push("selection anchor node"),t===e.focusNode&&n.push("selection focus node"),n}),extraParams:JSON.stringify({activeElementName:o?o.nodeName:null,nodeIsFocus:t===e.focusNode,nodeWasFocus:s,selectionRangeCount:e.rangeCount,selectionAnchorNodeName:e.anchorNode?e.anchorNode.nodeName:null,selectionAnchorOffset:e.anchorOffset,selectionFocusNodeName:e.focusNode?e.focusNode.nodeName:null,selectionFocusOffset:e.focusOffset,message:a?""+a:null,offset:n},null,2),selectionState:JSON.stringify(r.toJS(),null,2)}),a}}else{var l=e.getRangeAt(0);l.setEnd(t,n),e.addRange(l.cloneRange())}}function u(e,t,n,r){var o=document.createRange();n>a(t)&&c.logSelectionStateFailure({anonymizedDom:i(t),extraParams:JSON.stringify({offset:n}),selectionState:JSON.stringify(r.toJS())}),o.setStart(t,n),e.addRange(o)}var c=n(451),p=n(153),f=n(218),d=n(10);e.exports=s}).call(t,n(24))},function(e,t,n){"use strict";e.exports={logSelectionStateFailure:function(){return null}}},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(453);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e?e.ownerDocument||e:document,n=t.defaultView||window;return!(!e||!("function"==typeof n.Node?e instanceof n.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=r},function(e,t,n){"use strict";function r(e){return null==e?e:String(e)}function o(e,t){var n=void 0;if(window.getComputedStyle&&(n=window.getComputedStyle(e,null)))return r(n.getPropertyValue(a(t)));if(document.defaultView&&document.defaultView.getComputedStyle){if(n=document.defaultView.getComputedStyle(e,null))return r(n.getPropertyValue(a(t)));if("display"===t)return"none"}return r(e.currentStyle?"float"===t?e.currentStyle.cssFloat||e.currentStyle.styleFloat:e.currentStyle[i(t)]:e.style&&e.style[i(t)])}var i=n(455),a=n(456);e.exports=o},function(e,t,n){"use strict";function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;e.exports=r},function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;e.exports=r},function(e,t,n){"use strict";function r(e){var t=o(e);return{x:t.left,y:t.top,width:t.right-t.left,height:t.bottom-t.top}}var o=n(458);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.ownerDocument.documentElement;if(!("getBoundingClientRect"in e&&o(t,e)))return{left:0,right:0,top:0,bottom:0};var n=e.getBoundingClientRect();return{left:Math.round(n.left)-t.clientLeft,right:Math.round(n.right)-t.clientLeft,top:Math.round(n.top)-t.clientTop,bottom:Math.round(n.bottom)-t.clientTop}}var o=n(153);e.exports=r},function(e,t,n){"use strict";function r(e){return e=e||document,e.scrollingElement?e.scrollingElement:o||"CSS1Compat"!==e.compatMode?e.body:e.documentElement}var o="undefined"!=typeof navigator&&navigator.userAgent.indexOf("AppleWebKit")>-1;e.exports=r},function(e,t,n){"use strict";function r(e){return e.Window&&e instanceof e.Window?{x:e.pageXOffset||e.document.documentElement.scrollLeft,y:e.pageYOffset||e.document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=r},function(e,t,n){"use strict";function r(){var e=void 0;return document.documentElement&&(e=document.documentElement.clientWidth),!e&&document.body&&(e=document.body.clientWidth),e||0}function o(){var e=void 0;return document.documentElement&&(e=document.documentElement.clientHeight),!e&&document.body&&(e=document.body.clientHeight),e||0}function i(){return{width:window.innerWidth||r(),height:window.innerHeight||o()}}i.withoutScrollbars=function(){return{width:r(),height:o()}},e.exports=i},function(e,t,n){"use strict";function r(e){e||(e="");var t=void 0,n=arguments.length;if(n>1)for(var r=1;r<n;r++)(t=arguments[r])&&(e=(e?e+" ":"")+t);return e}e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=null,r=null;if("function"==typeof document.caretRangeFromPoint){var o=document.caretRangeFromPoint(e.x,e.y);n=o.startContainer,r=o.startOffset}else{if(!e.rangeParent)return null;n=e.rangeParent,r=e.rangeOffset}n=d(n),r=d(r);var i=d(u(n));return p(t,i,r,i,r)}function o(e,t){var n=s.moveText(e.getCurrentContent(),e.getSelection(),t);return l.push(e,n,"insert-fragment")}function i(e,t,n){var r=s.insertText(e.getCurrentContent(),t,n,e.getCurrentInlineStyle());return l.push(e,r,"insert-fragment")}var a=n(220),s=n(22),l=n(12),u=n(156),c=n(222),p=n(223),f=n(79),d=n(34),h={onDragEnd:function(e){e.exitCurrentMode()},onDrop:function(e,t){var n=new a(t.nativeEvent.dataTransfer),s=e._latestEditorState,l=r(t.nativeEvent,s);if(t.preventDefault(),e.exitCurrentMode(),null!=l){var u=n.getFiles();if(u.length>0){if(e.props.handleDroppedFiles&&f(e.props.handleDroppedFiles(l,u)))return;return void c(u,function(t){t&&e.update(i(s,l,t))})}var p=e._internalDrag?"internal":"external";if(!e.props.handleDrop||!f(e.props.handleDrop(l,n,p)))return e._internalDrag?void e.update(o(s,l)):void e.update(i(s,l,n.getText()))}}};e.exports=h},function(e,t,n){"use strict";function r(e){return e.split("/")}var o={isImage:function(e){return"image"===r(e)[0]},isJpeg:function(e){var t=r(e);return o.isImage(e)&&("jpeg"===t[1]||"pjpeg"===t[1])}};e.exports=o},function(e,t,n){"use strict";function r(e){var t=e.length;if((Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e)&&a(!1),"number"!=typeof t&&a(!1),0===t||t-1 in e||a(!1),"function"==typeof e.callee&&a(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(e){}for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}function o(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function i(e){return o(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=n(10);e.exports=i},function(e,t,n){"use strict";var r=n(467),o=n(470),i=n(471),a=n(472),s=n(473),l=n(474),u=n(475),c=n(476),p=n(477),f=n(478),d=n(492),h=n(497),v={onBeforeInput:r,onBlur:o,onCompositionStart:i,onCopy:a,onCut:s,onDragOver:l,onDragStart:u,onFocus:c,onInput:p,onKeyDown:f,onPaste:d,onSelect:h};e.exports=v},function(e,t,n){"use strict";(function(t){function r(e){return y&&(e==v||e==m)}function o(e,t,n,r){var o=s.replaceText(e.getCurrentContent(),e.getSelection(),t,n,r);return l.push(e,o,"insert-characters")}function i(e,n){void 0!==e._pendingStateFromBeforeInput&&(e.update(e._pendingStateFromBeforeInput),e._pendingStateFromBeforeInput=void 0);var i=e._latestEditorState,s=n.data;if(s){if(e.props.handleBeforeInput&&p(e.props.handleBeforeInput(s,i)))return void n.preventDefault();var u=i.getSelection(),v=u.getStartOffset(),m=u.getEndOffset(),y=u.getAnchorKey();if(!u.isCollapsed()){n.preventDefault();return void(s===i.getCurrentContent().getPlainText().slice(v,m)?e.update(l.forceSelection(i,u.merge({focusOffset:m}))):e.update(o(i,s,i.getCurrentInlineStyle(),c(i.getCurrentContent(),i.getSelection()))))}var g=o(i,s,i.getCurrentInlineStyle(),c(i.getCurrentContent(),i.getSelection())),b=!1;if(b||(b=f(e._latestCommittedEditorState)),!b){var C=t.getSelection();if(C.anchorNode&&C.anchorNode.nodeType===Node.TEXT_NODE){var w=C.anchorNode.parentNode;b="SPAN"===w.nodeName&&w.firstChild.nodeType===Node.TEXT_NODE&&-1!==w.firstChild.nodeValue.indexOf("\t")}}if(!b){b=a.getFingerprint(i.getBlockTree(y))!==a.getFingerprint(g.getBlockTree(y))}if(b||(b=r(s)),b||(b=d(g.getDirectionMap()).get(y)!==d(i.getDirectionMap()).get(y)),b)return n.preventDefault(),void e.update(g);g=l.set(g,{nativelyRenderedContent:g.getCurrentContent()}),e._pendingStateFromBeforeInput=g,h(function(){void 0!==e._pendingStateFromBeforeInput&&(e.update(e._pendingStateFromBeforeInput),e._pendingStateFromBeforeInput=void 0)})}}var a=n(212),s=n(22),l=n(12),u=n(38),c=n(152),p=n(79),f=n(216),d=n(34),h=n(468),v="'",m="/",y=u.isBrowser("Firefox");e.exports=i}).call(t,n(24))},function(e,t,n){"use strict";(function(t){n(157),e.exports=t.setImmediate}).call(t,n(24))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(c===setTimeout)return setTimeout(e,0);if((c===n||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function i(e){if(p===clearTimeout)return clearTimeout(e);if((p===r||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){v&&d&&(v=!1,d.length?h=d.concat(h):m=-1,h.length&&s())}function s(){if(!v){var e=o(a);v=!0;for(var t=h.length;t;){for(d=h,h=[];++m<t;)d&&d[m].run();m=-1,t=h.length}d=null,v=!1,i(e)}}function l(e,t){this.fun=e,this.array=t}function u(){}var c,p,f=e.exports={};!function(){try{c="function"==typeof setTimeout?setTimeout:n}catch(e){c=n}try{p="function"==typeof clearTimeout?clearTimeout:r}catch(e){p=r}}();var d,h=[],v=!1,m=-1;f.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];h.push(new l(e,t)),1!==h.length||v||o(s)},l.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=u,f.addListener=u,f.once=u,f.off=u,f.removeListener=u,f.removeAllListeners=u,f.emit=u,f.prependListener=u,f.prependOnceListener=u,f.listeners=function(e){return[]},f.binding=function(e){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(e){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(e,t,n){"use strict";(function(t){function r(e,n){if(a()===document.body){var r=t.getSelection(),s=e.editor;1===r.rangeCount&&i(s,r.anchorNode)&&i(s,r.focusNode)&&r.removeAllRanges()}var l=e._latestEditorState,u=l.getSelection();if(u.getHasFocus()){var c=u.set("hasFocus",!1);e.props.onBlur&&e.props.onBlur(n),e.update(o.acceptSelection(l,c))}}var o=n(12),i=n(153),a=n(218);e.exports=r}).call(t,n(24))},function(e,t,n){"use strict";function r(e,t){e.setMode("composite"),e.update(o.set(e._latestEditorState,{inCompositionMode:!0})),e._onCompositionStart(t)}var o=n(12);e.exports=r},function(e,t,n){"use strict";function r(e,t){if(e._latestEditorState.getSelection().isCollapsed())return void t.preventDefault();e.setClipboard(o(e._latestEditorState))}var o=n(224);e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=e._latestEditorState,r=n.getSelection(),i=t.target,a=void 0;if(r.isCollapsed())return void t.preventDefault();i instanceof Node&&(a=u(s.getScrollParent(i)));var c=l(n);e.setClipboard(c),e.setMode("cut"),setTimeout(function(){e.restoreEditorDOM(a),e.exitCurrentMode(),e.update(o(n))},0)}function o(e){var t=i.removeRange(e.getCurrentContent(),e.getSelection(),"forward");return a.push(e,t,"remove-range")}var i=n(22),a=n(12),s=n(154),l=n(224),u=n(155);e.exports=r},function(e,t,n){"use strict";function r(e,t){e._internalDrag=!1,e.setMode("drag"),t.preventDefault()}e.exports=r},function(e,t,n){"use strict";function r(e){e._internalDrag=!0,e.setMode("drag")}e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=e._latestEditorState,r=n.getSelection();if(!r.getHasFocus()){var a=r.set("hasFocus",!0);e.props.onFocus&&e.props.onFocus(t),i.isBrowser("Chrome < 60.0.3081.0")?e.update(o.forceSelection(n,a)):e.update(o.acceptSelection(n,a))}}var o=n(12),i=n(38);e.exports=r},function(e,t,n){"use strict";(function(t){function r(e){void 0!==e._pendingStateFromBeforeInput&&(e.update(e._pendingStateFromBeforeInput),e._pendingStateFromBeforeInput=void 0);var n=t.getSelection(),r=n.anchorNode,l=n.isCollapsed,d=r.nodeType!==Node.TEXT_NODE,h=r.nodeType!==Node.TEXT_NODE&&r.nodeType!==Node.ELEMENT_NODE;if(o.draft_killswitch_allow_nontextnodes){if(d)return}else if(h)return;if(r.nodeType===Node.TEXT_NODE&&(null!==r.previousSibling||null!==r.nextSibling)){var v=r.parentNode;r.nodeValue=v.textContent;for(var m=v.firstChild;null!==m;m=m.nextSibling)m!==r&&v.removeChild(m)}var y=r.textContent,g=e._latestEditorState,b=c(u(r)),C=a.decode(b),w=C.blockKey,S=C.decoratorKey,x=C.leafKey,_=g.getBlockTree(w).getIn([S,"leaves",x]),k=_.start,E=_.end,O=g.getCurrentContent(),T=O.getBlockForKey(w),N=T.getText().slice(k,E);if(y.endsWith(f)&&(y=y.slice(0,-1)),y!==N){var P,M,D,I,A=g.getSelection(),j=A.merge({anchorOffset:k,focusOffset:E,isBackward:!1}),R=T.getEntityAt(k),L=R&&O.getEntity(R),K=L&&L.getMutability(),F="MUTABLE"===K,V=F?"spellcheck-change":"apply-entity",z=i.replaceText(O,j,y,T.getInlineStyleAt(k),F?T.getEntityAt(k):null);if(p)P=n.anchorOffset,M=n.focusOffset,D=k+Math.min(P,M),I=D+Math.abs(P-M),P=D,M=I;else{var B=y.length-N.length;D=A.getStartOffset(),I=A.getEndOffset(),P=l?I+B:D,M=I+B}var W=z.merge({selectionBefore:O.getSelectionAfter(),selectionAfter:A.merge({anchorOffset:P,focusOffset:M})});e.update(s.push(g,W,V))}}var o=n(45),i=n(22),a=n(80),s=n(12),l=n(38),u=n(156),c=n(34),p=l.isEngine("Gecko"),f="\n\n";e.exports=r}).call(t,n(24))},function(e,t,n){"use strict";function r(e,t){switch(e){case"redo":return a.redo(t);case"delete":return b(t);case"delete-word":return h(t);case"backspace":return g(t);case"backspace-word":return d(t);case"backspace-to-start-of-line":return f(t);case"split-block":return v(t);case"transpose-characters":return C(t);case"move-selection-to-start-of-block":return y(t);case"move-selection-to-end-of-block":return m(t);case"secondary-cut":return u.cut(t);case"secondary-paste":return u.paste(t);default:return t}}function o(e,t){var n=t.which,o=e._latestEditorState;switch(n){case l.RETURN:if(t.preventDefault(),e.props.handleReturn&&p(e.props.handleReturn(t,o)))return;break;case l.ESC:return t.preventDefault(),void(e.props.onEscape&&e.props.onEscape(t));case l.TAB:return void(e.props.onTab&&e.props.onTab(t));case l.UP:return void(e.props.onUpArrow&&e.props.onUpArrow(t));case l.RIGHT:return void(e.props.onRightArrow&&e.props.onRightArrow(t));case l.DOWN:return void(e.props.onDownArrow&&e.props.onDownArrow(t));case l.LEFT:return void(e.props.onLeftArrow&&e.props.onLeftArrow(t));case l.SPACE:if(x&&S(t)){t.preventDefault();var s=i.replaceText(o.getCurrentContent(),o.getSelection(),"\xa0");return void e.update(a.push(o,s,"insert-characters"))}}var u=e.props.keyBindingFn(t);if(u){if("undo"===u)return void w(t,o,e.update);if(t.preventDefault(),!e.props.handleKeyCommand||!p(e.props.handleKeyCommand(u,o))){var c=r(u,o);c!==o&&e.update(c)}}}var i=n(22),a=n(12),s=n(158),l=n(151),u=n(479),c=n(38),p=n(79),f=n(480),d=n(482),h=n(484),v=n(485),m=n(486),y=n(487),g=n(488),b=n(489),C=n(490),w=n(491),S=s.isOptionKeyCommand,x=c.isBrowser("Chrome");e.exports=o},function(e,t,n){"use strict";var r=n(22),o=n(12),i=n(97),a=n(34),s=null,l={cut:function(e){var t=e.getCurrentContent(),n=e.getSelection(),l=null;if(n.isCollapsed()){var u=n.getAnchorKey(),c=t.getBlockForKey(u).getLength();if(c===n.getAnchorOffset())return e;l=n.set("focusOffset",c)}else l=n;l=a(l),s=i(t,l);var p=r.removeRange(t,l,"forward");return p===t?e:o.push(e,p,"remove-range")},paste:function(e){if(!s)return e;var t=r.replaceWithFragment(e.getCurrentContent(),e.getSelection(),s);return o.push(e,t,"insert-fragment")}};e.exports=l},function(e,t,n){"use strict";(function(t){function r(e){var n=l(e,function(e){var n=e.getSelection();if(n.isCollapsed()&&0===n.getAnchorOffset())return s(e,1);var r=t.getSelection(),o=r.getRangeAt(0);return o=i(o),a(e,null,o.endContainer,o.endOffset,o.startContainer,o.startOffset).selectionState},"backward");return n===e.getCurrentContent()?e:o.push(e,n,"remove-range")}var o=n(12),i=n(481),a=n(226),s=n(159),l=n(81);e.exports=r}).call(t,n(24))},function(e,t,n){"use strict";function r(e){var t=getComputedStyle(e),n=document.createElement("div");n.style.fontFamily=t.fontFamily,n.style.fontSize=t.fontSize,n.style.fontStyle=t.fontStyle,n.style.fontWeight=t.fontWeight,n.style.lineHeight=t.lineHeight,n.style.position="absolute",n.textContent="M";var r=document.body;r||u(!1),r.appendChild(n);var o=n.getBoundingClientRect();return r.removeChild(n),o.height}function o(e,t){for(var n=1/0,r=1/0,o=-1/0,i=-1/0,a=0;a<e.length;a++){var s=e[a];0!==s.width&&1!==s.width&&(n=Math.min(n,s.top),r=Math.min(r,s.bottom),o=Math.max(o,s.top),i=Math.max(i,s.bottom))}return o<=r&&o-n<t&&i-r<t}function i(e){switch(e.nodeType){case Node.DOCUMENT_TYPE_NODE:return 0;case Node.TEXT_NODE:case Node.PROCESSING_INSTRUCTION_NODE:case Node.COMMENT_NODE:return e.length;default:return e.childNodes.length}}function a(e){e.collapsed||u(!1),e=e.cloneRange();var t=e.startContainer;1!==t.nodeType&&(t=t.parentNode);var n=r(t),a=e.endContainer,c=e.endOffset;for(e.setStart(e.startContainer,0);o(l(e),n)&&(a=e.startContainer,c=e.startOffset,a.parentNode||u(!1),e.setStartBefore(a),1!==a.nodeType||"inline"===getComputedStyle(a).display););for(var p=a,f=c-1;;){for(var d=p.nodeValue,h=f;h>=0;h--)if(!(null!=d&&h>0&&s.isSurrogatePair(d,h-1))){if(e.setStart(p,h),!o(l(e),n))break;a=p,c=h}if(-1===h||0===p.childNodes.length)break;p=p.childNodes[h],f=i(p)}return e.setStart(a,c),e}var s=n(55),l=n(225),u=n(10);e.exports=a},function(e,t,n){"use strict";function r(e){var t=s(e,function(e){var t=e.getSelection(),n=t.getStartOffset();if(0===n)return a(e,1);var r=t.getStartKey(),i=e.getCurrentContent(),s=i.getBlockForKey(r).getText().slice(0,n),l=o.getBackward(s);return a(e,l.length||1)},"backward");return t===e.getCurrentContent()?e:i.push(e,t,"remove-range")}var o=n(227),i=n(12),a=n(159),s=n(81);e.exports=r},function(e,t,n){"use strict";e.exports={getPunctuation:function(){return"[.,+*?$|#{}()'\\^\\-\\[\\]\\\\\\/!@%\"~=<>_:;\u30fb\u3001\u3002\u3008-\u3011\u3014-\u301f\uff1a-\uff1f\uff01-\uff0f\uff3b-\uff40\uff5b-\uff65\u2e2e\u061f\u066a-\u066c\u061b\u060c\u060d\ufd3e\ufd3f\u1801\u0964\u104a\u104b\u2010-\u2027\u2030-\u205e\xa1-\xb1\xb4-\xb8\xba\xbb\xbf]"}}},function(e,t,n){"use strict";function r(e){var t=s(e,function(e){var t=e.getSelection(),n=t.getStartOffset(),r=t.getStartKey(),i=e.getCurrentContent(),s=i.getBlockForKey(r).getText().slice(n),l=o.getForward(s);return a(e,l.length||1)},"forward");return t===e.getCurrentContent()?e:i.push(e,t,"remove-range")}var o=n(227),i=n(12),a=n(228),s=n(81);e.exports=r},function(e,t,n){"use strict";function r(e){var t=o.splitBlock(e.getCurrentContent(),e.getSelection());return i.push(e,t,"split-block")}var o=n(22),i=n(12);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.getSelection(),n=t.getEndKey(),r=e.getCurrentContent(),i=r.getBlockForKey(n).getLength();return o.set(e,{selection:t.merge({anchorKey:n,anchorOffset:i,focusKey:n,focusOffset:i,isBackward:!1}),forceSelection:!0})}var o=n(12);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.getSelection(),n=t.getStartKey();return o.set(e,{selection:t.merge({anchorKey:n,anchorOffset:0,focusKey:n,focusOffset:0,isBackward:!1}),forceSelection:!0})}var o=n(12);e.exports=r},function(e,t,n){"use strict";function r(e){var t=s(e,function(e){var t=e.getSelection(),n=e.getCurrentContent(),r=t.getAnchorKey(),o=t.getAnchorOffset(),s=n.getBlockForKey(r).getText()[o-1];return a(e,s?i.getUTF16Length(s,0):1)},"backward");if(t===e.getCurrentContent())return e;var n=e.getSelection();return o.push(e,t.set("selectionBefore",n),n.isCollapsed()?"backspace-character":"remove-range")}var o=n(12),i=n(55),a=n(159),s=n(81);e.exports=r},function(e,t,n){"use strict";function r(e){var t=s(e,function(e){var t=e.getSelection(),n=e.getCurrentContent(),r=t.getAnchorKey(),o=t.getAnchorOffset(),s=n.getBlockForKey(r).getText()[o];return a(e,s?i.getUTF16Length(s,0):1)},"forward");if(t===e.getCurrentContent())return e;var n=e.getSelection();return o.push(e,t.set("selectionBefore",n),n.isCollapsed()?"delete-character":"remove-range")}var o=n(12),i=n(55),a=n(228),s=n(81);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.getSelection();if(!t.isCollapsed())return e;var n=t.getAnchorOffset();if(0===n)return e;var r=t.getAnchorKey(),s=e.getCurrentContent(),l=s.getBlockForKey(r),u=l.getLength();if(u<=1)return e;var c,p;n===u?(c=t.set("anchorOffset",n-1),p=t):(c=t.set("focusOffset",n+1),p=c.set("anchorOffset",n+1));var f=a(s,c),d=o.removeRange(s,c,"backward"),h=d.getSelectionAfter(),v=h.getAnchorOffset()-1,m=h.merge({anchorOffset:v,focusOffset:v}),y=o.replaceWithFragment(d,m,f),g=i.push(e,y,"insert-fragment");return i.acceptSelection(g,p)}var o=n(22),i=n(12),a=n(97);e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=o.undo(t);if("spellcheck-change"===t.getLastChangeType()){var i=r.getCurrentContent();return void n(o.set(r,{nativelyRenderedContent:i}))}if(e.preventDefault(),!t.getNativelyRenderedContent())return void n(r);n(o.set(t,{nativelyRenderedContent:null})),setTimeout(function(){n(r)},0)}var o=n(12);e.exports=r},function(e,t,n){"use strict";function r(e,t){t.preventDefault();var n=new l(t.clipboardData);if(!n.isRichText()){var r=n.getFiles(),y=n.getText();if(r.length>0){if(e.props.handlePastedFiles&&v(e.props.handlePastedFiles(r)))return;return void h(r,function(t){if(t=t||y){var n=e._latestEditorState,r=m(t),o=s.create({style:n.getCurrentInlineStyle(),entity:d(n.getCurrentContent(),n.getSelection())}),i=f.getCurrentBlockType(n),l=c.processText(r,o,i),h=a.createFromArray(l),v=u.replaceWithFragment(n.getCurrentContent(),n.getSelection(),h);e.update(p.push(n,v,"insert-fragment"))}})}}var g=[],b=n.getText(),C=n.getHTML(),w=e._latestEditorState;if(!e.props.handlePastedText||!v(e.props.handlePastedText(b,C,w))){if(b&&(g=m(b)),!e.props.stripPastedStyles){var S=e.getClipboard();if(n.isRichText()&&S){if(-1!==C.indexOf(e.getEditorKey())||1===g.length&&1===S.size&&S.first().getText()===b)return void e.update(o(e._latestEditorState,S))}else if(S&&n.types.includes("com.apple.webarchive")&&!n.types.includes("text/html")&&i(g,S))return void e.update(o(e._latestEditorState,S));if(C){var x=c.processHTML(C,e.props.blockRenderMap);if(x){var _=x.contentBlocks,k=x.entityMap;if(_){var E=a.createFromArray(_);return void e.update(o(e._latestEditorState,E,k))}}}e.setClipboard(null)}if(g.length){var O=s.create({style:w.getCurrentInlineStyle(),entity:d(w.getCurrentContent(),w.getSelection())}),T=f.getCurrentBlockType(w),N=c.processText(g,O,T),P=a.createFromArray(N);e.update(o(e._latestEditorState,P))}}}function o(e,t,n){var r=u.replaceWithFragment(e.getCurrentContent(),e.getSelection(),t);return p.push(e,r.set("entityMap",n),"insert-fragment")}function i(e,t){return e.length===t.size&&t.valueSeq().every(function(t,n){return t.getText()===e[n]})}var a=n(77),s=n(25),l=n(220),u=n(22),c=n(493),p=n(12),f=n(231),d=n(152),h=n(222),v=n(79),m=n(496);e.exports=r},function(e,t,n){"use strict";var r=n(16),o=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=(n(25),n(54)),a=n(28),s=n(45),l=n(11),u=n(229),c=n(39),p=n(230),f=n(148),d=l.List,h=l.Repeat,v=s.draft_tree_data_support,m=v?a:i,y={processHTML:function(e,t){return u(e,p,t)},processText:function(e,t,n){return e.reduce(function(e,r,i){r=f(r);var a=c(),s={key:a,type:n,text:r,characterList:d(h(t,r.length))};if(v&&0!==i){var l=i-1,u=e[l]=e[l].merge({nextSibling:a});s=o({},s,{prevSibling:u.getKey()})}return e.push(new m(s)),e},[])}};e.exports=y},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=function(){function e(t){r(this,e),this._uri=t}return e.prototype.toString=function(){return this._uri},e}();e.exports=o},function(e,t,n){"use strict";function r(e,t,n,r){var o=t.getStartKey(),i=t.getEndKey(),a=e.getBlockMap(),s=a.toSeq().skipUntil(function(e,t){return t===o}).takeUntil(function(e,t){return t===i}).concat([[i,a.get(i)]]).map(function(e){var t=e.getDepth()+n;return t=Math.max(0,Math.min(t,r)),e.set("depth",t)});return a=a.merge(s),e.merge({blockMap:a,selectionBefore:t,selectionAfter:t})}e.exports=r},function(e,t,n){"use strict";function r(e){return e.split(o)}var o=/\r\n?|\n/g;e.exports=r},function(e,t,n){"use strict";function r(e){if(!e._blockSelectEvents&&e._latestEditorState===e.props.editorState){var t=e.props.editorState,n=i.findDOMNode(e.editorContainer);n||s(!1),n.firstChild instanceof HTMLElement||s(!1);var r=a(t,n.firstChild),l=r.selectionState;l!==t.getSelection()&&(t=r.needsRecovery?o.forceSelection(t,l):o.acceptSelection(t,l),e.update(t))}}var o=n(12),i=n(9),a=n(498),s=n(10);e.exports=r},function(e,t,n){"use strict";(function(t){function r(e,n){var r=t.getSelection();return 0===r.rangeCount?{selectionState:e.getSelection().set("hasFocus",!1),needsRecovery:!1}:o(e,n,r.anchorNode,r.anchorOffset,r.focusNode,r.focusOffset)}var o=n(226);e.exports=r}).call(t,n(24))},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(0),s=n(66),l=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.shouldComponentUpdate=function(e){return this.props.text!==e.text||this.props.editorState.getSelection().getHasFocus()!==e.editorState.getSelection().getHasFocus()},t.prototype.render=function(){var e=this.props.editorState.getSelection().getHasFocus(),t=s({"public/DraftEditorPlaceholder/root":!0,"public/DraftEditorPlaceholder/hasFocus":e}),n={whiteSpace:"pre-wrap"};return a.createElement("div",{className:t},a.createElement("div",{className:s("public/DraftEditorPlaceholder/inner"),id:this.props.accessibilityID,style:n},this.props.text))},t}(a.Component);e.exports=l},function(e,t,n){"use strict";var r=n(16),o=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(54),a=n(28),s=n(233),l=n(501),u=n(502),c=n(10),p=function(e,t){return{key:e.getKey(),text:e.getText(),type:e.getType(),depth:e.getDepth(),inlineStyleRanges:u(e),entityRanges:l(e,t),data:e.getData().toObject()}},f=function(e,t,n,r){if(e instanceof i)return void n.push(p(e,t));e instanceof a||c(!1);var s=e.getParentKey(),l=r[e.getKey()]=o({},p(e,t),{children:[]});if(s)return void r[s].children.push(l);n.push(l)},d=function(e,t){var n=t.entityMap,r=[],o={},i={},a=0;return e.getBlockMap().forEach(function(e){e.findEntityRanges(function(e){return null!==e.getEntity()},function(t){var r=e.getEntityAt(t),o=s.stringify(r);i[o]||(i[o]=r,n[o]=""+a,a++)}),f(e,n,r,o)}),{blocks:r,entityMap:n}},h=function(e,t){var n=t.blocks,r=t.entityMap,o={};return Object.keys(r).forEach(function(t,n){var r=e.getEntity(s.unstringify(t));o[n]={type:r.getType(),mutability:r.getMutability(),data:r.getData()}}),{blocks:n,entityMap:o}},v=function(e){var t={entityMap:{},blocks:[]};return t=d(e,t),t=h(e,t)};e.exports=v},function(e,t,n){"use strict";function r(e,t){var n=[];return e.findEntityRanges(function(e){return!!e.getEntity()},function(r,i){var s=e.getText(),l=e.getEntityAt(r);n.push({offset:a(s.slice(0,r)),length:a(s.slice(r,i)),key:Number(t[o.stringify(l)])})}),n}var o=n(233),i=n(55),a=i.strlen;e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=[],o=t.map(function(e){return e.has(n)}).toList();return a(o,s,l,function(t,o){var a=e.getText();r.push({offset:i.strlen(a.slice(0,t)),length:i.strlen(a.slice(t,o)),style:n})}),r}function o(e){var t=e.getCharacterList().map(function(e){return e.getStyle()}).toList(),n=t.flatten().toSet().map(function(n){return r(e,t,n)});return Array.prototype.concat.apply(u,n.toJS())}var i=n(55),a=n(78),s=function(e,t){return e===t},l=function(e){return!!e},u=[];e.exports=o},function(e,t,n){"use strict";var r=n(16),o=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(54),a=n(28),s=n(147),l=n(98),u=n(45),c=n(504),p=n(11),f=n(65),d=n(505),h=n(506),v=n(507),m=n(39),y=n(10),g=u.draft_tree_data_support,b=p.List,C=p.Map,w=p.OrderedMap,S=function(e,t){var n=e.key,r=e.type,o=e.data;return{text:e.text,depth:e.depth||0,type:r||"unstyled",key:n||m(),data:C(o),characterList:x(e,t)}},x=function(e,t){var n=e.text,r=e.entityRanges,i=e.inlineStyleRanges,a=r||[];return d(v(n,i||[]),h(n,a.filter(function(e){return t.hasOwnProperty(e.key)}).map(function(e){return o({},e,{key:t[e.key]})})))},_=function(e){return o({},e,{key:e.key||m()})},k=function(e,t,n){var r=t.map(function(e){return o({},e,{parentRef:n})});return e.concat(r.reverse())},E=function(e,t){return e.map(_).reduce(function(n,r,i){Array.isArray(r.children)||y(!1);var s=r.children.map(_),l=new a(o({},S(r,t),{prevSibling:0===i?null:e[i-1].key,nextSibling:i===e.length-1?null:e[i+1].key,children:b(s.map(function(e){return e.key}))}));n=n.set(l.getKey(),l);for(var u=k([],s,l);u.length>0;){var c=u.pop(),p=c.parentRef,f=p.getChildKeys(),d=f.indexOf(c.key),h=Array.isArray(c.children);if(!h){h||y(!1);break}var v=c.children.map(_),m=new a(o({},S(c,t),{parent:p.getKey(),children:b(v.map(function(e){return e.key})),prevSibling:0===d?null:f.get(d-1),nextSibling:d===f.size-1?null:f.get(d+1)}));n=n.set(m.getKey(),m),u=k(u,v,m)}return n},w())},O=function(e,t){return w(e.map(function(e){var n=new i(S(e,t));return[n.getKey(),n]}))},T=function(e,t){var n=Array.isArray(e.blocks[0].children),r=g&&!n?c.fromRawStateToRawTreeState(e).blocks:e.blocks;return g?E(r,t):O(n?c.fromRawTreeStateToRawState(e).blocks:r,t)},N=function(e){var t=e.entityMap,n={};return Object.keys(t).forEach(function(e){var r=t[e],o=r.type,i=r.mutability,a=r.data;n[e]=l.__create(o,i,a||{})}),n},P=function(e){Array.isArray(e.blocks)||y(!1);var t=N(e),n=T(e,t),r=n.isEmpty()?new f:f.createEmpty(n.first().getKey());return new s({blockMap:n,entityMap:t,selectionBefore:r,selectionAfter:r})};e.exports=P},function(e,t,n){"use strict";var r=n(16),o=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(10),a=function(e,t){for(var n=[].concat(e).reverse();n.length;){var r=n.pop();t(r);var o=r.children;Array.isArray(o)||i(!1),n=n.concat([].concat(o.reverse()))}},s=function(e){if(!e||!e.type)return!1;var t=e.type;return"unordered-list-item"===t||"ordered-list-item"===t},l=function(e){Array.isArray(e.children)&&(e.children=e.children.map(function(t){return t.type===e.type?o({},t,{depth:(e.depth||0)+1}):t}))},u={fromRawTreeStateToRawState:function(e){var t=e.blocks,n=[];return Array.isArray(t)||i(!1),Array.isArray(t)&&t.length?(a(t,function(e){var t=o({},e);s(e)&&(t.depth=t.depth||0,l(e)),delete t.children,n.push(t)}),e.blocks=n,o({},e,{blocks:n})):e},fromRawStateToRawTreeState:function(e){var t={},n=[];return e.blocks.forEach(function(e){var r=s(e),a=e.depth||0,l=o({},e,{children:[]});if(!r)return t={},void n.push(l);if(t[a]=l,a>0){var u=t[a-1];return u||i(!1),void u.children.push(l)}n.push(l)}),o({},e,{blocks:n})}};e.exports=u},function(e,t,n){"use strict";function r(e,t){var n=e.map(function(e,n){var r=t[n];return o.create({style:e,entity:r})});return a(n)}var o=n(25),i=n(11),a=i.List;e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=Array(e.length).fill(null);return t&&t.forEach(function(t){for(var r=i(e,0,t.offset).length,o=r+i(e,t.offset,t.length).length,a=r;a<o;a++)n[a]=t.key}),n}var o=n(55),i=o.substr;e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=Array(e.length).fill(l);return t&&t.forEach(function(t){for(var r=s(e,0,t.offset).length,o=r+s(e,t.offset,t.length).length;r<o;)n[r]=n[r].add(t.style),r++}),n}var o=n(11),i=o.OrderedSet,a=n(55),s=a.substr,l=i();e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.getSelection();if(!t.rangeCount)return null;var n=t.getRangeAt(0),r=o(n),i=r.top,a=r.right,s=r.bottom,l=r.left;return 0===i&&0===a&&0===s&&0===l?null:r}var o=n(509);e.exports=r},function(e,t,n){"use strict";function r(e){var t=o(e),n=0,r=0,i=0,a=0;if(t.length){if(t.length>1&&0===t[0].width){var s=t[1];n=s.top,r=s.right,i=s.bottom,a=s.left}else{var l=t[0];n=l.top,r=l.right,i=l.bottom,a=l.left}for(var u=1;u<t.length;u++){var c=t[u];0!==c.height&&0!==c.width&&(n=Math.min(n,c.top),r=Math.max(r,c.right),i=Math.max(i,c.bottom),a=Math.min(a,c.left))}}return{top:n,right:r,bottom:i,left:a,width:r-a,height:i-n}}var o=n(225);e.exports=r},function(e,t,n){"use strict";(function(e,r){function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){}var l=n(0),u=n.n(l),c=n(5),p=n.n(c),f=n(44),d=(n.n(f),n(67)),h=(n.n(d),n(157)),v=(n.n(h),n(6)),m=n.n(v),y=n(511),g=n(512),b=n(513),C=n(514),w=n(515),S=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},x=f.KeyBindingUtil.hasCommandModifier,_={},k={width:0,opacity:0,border:0,position:"absolute",left:0,top:0},E=Object(y.a)(),O=new g.a,T=function(t){function n(r){o(this,n);var a=i(this,t.call(this,r));a.cancelForceUpdateImmediate=function(){e(a.forceUpdateImmediate),a.forceUpdateImmediate=null},a.handlePastedText=function(e,t){var n=a.state.editorState;if(t){var r=n.getCurrentContent(),o=n.getSelection(),i=Object(w.a)(t,r),s=f.Modifier.replaceWithFragment(r,o,i),l=s.merge({selectionBefore:o,selectionAfter:s.getSelectionAfter().set("hasFocus",!0)});return a.setEditorState(f.EditorState.push(n,l,"insert-fragment"),!0),"handled"}return"not-handled"},a.plugins=Object(d.List)(Object(d.List)(r.plugins).flatten(!0));var s=void 0;return s=void 0!==r.value&&r.value instanceof f.EditorState?r.value||f.EditorState.createEmpty():f.EditorState.createEmpty(),s=a.generatorDefaultValue(s),a.state={plugins:a.reloadPlugins(),editorState:s,customStyleMap:{},customBlockStyleMap:{},compositeDecorator:null},void 0!==r.value&&(a.controlledMode=!0,console.warn("this component is in controllred mode")),a}return a(n,t),n.ToEditorState=function(e){var t=f.ContentState.createFromText(Object(C.a)(e)||""),n=f.EditorState.createWithContent(t);return f.EditorState.forceSelection(n,t.getSelectionAfter())},n.prototype.Reset=function(){var e=this.props.defaultValue,t=e?e.getCurrentContent():f.ContentState.createFromText(""),n=f.EditorState.push(this.state.editorState,t,"remove-range");this.setEditorState(f.EditorState.forceSelection(n,t.getSelectionBefore()))},n.prototype.SetText=function(e){var t=f.ContentState.createFromText(e||""),n=f.EditorState.push(this.state.editorState,t,"change-block-data");this.setEditorState(f.EditorState.moveFocusToEnd(n),!0)},n.prototype.getChildContext=function(){return{getEditorState:this.getEditorState,setEditorState:this.setEditorState}},n.prototype.reloadPlugins=function(){var e=this;return this.plugins&&this.plugins.size?this.plugins.map(function(t){if(t.callbacks)return t;if(t.hasOwnProperty("constructor")){var n=S(e.props.pluginConfig,t.config||{},_);return t.constructor(n)}return console.warn(">> \u63d2\u4ef6: [",t.name,"] \u65e0\u6548\u3002\u63d2\u4ef6\u6216\u8bb8\u5df2\u7ecf\u8fc7\u671f\u3002"),!1}).filter(function(e){return e}).toArray():[]},n.prototype.componentWillMount=function(){var e=this.initPlugins().concat([E]),t={},n={},r=Object(d.Map)(f.DefaultDraftBlockRenderMap),o=Object(d.List)([]),i=new f.CompositeDecorator(e.filter(function(e){return void 0!==e.decorators}).map(function(e){return e.decorators}).reduce(function(e,t){return e.concat(t)},[])),a=Object(d.List)(e.filter(function(e){return!!e.component&&"toolbar"!==e.name}));e.forEach(function(e){var i=e.styleMap,a=e.blockStyleMap,s=e.blockRenderMap,l=e.toHtml;if(i)for(var u in i)i.hasOwnProperty(u)&&(t[u]=i[u]);if(a)for(var c in a)a.hasOwnProperty(c)&&(n[c]=a[c],r=r.set(c,{element:null}));if(l&&(o=o.push(l)),s)for(var p in s)s.hasOwnProperty(p)&&(r=r.set(p,s[p]))}),O.set("customStyleMap",t),O.set("customBlockStyleMap",n),O.set("blockRenderMap",r),O.set("customStyleFn",this.customStyleFn.bind(this)),O.set("toHTMLList",o),this.setState({toolbarPlugins:a,compositeDecorator:i}),this.setEditorState(f.EditorState.set(this.state.editorState,{decorator:i}))},n.prototype.componentWillReceiveProps=function(e){if(this.forceUpdateImmediate&&this.cancelForceUpdateImmediate(),this.controlledMode){var t=e.value.getDecorator(),n=t?e.value:f.EditorState.set(e.value,{decorator:this.state.compositeDecorator});this.setState({editorState:n})}},n.prototype.componentWillUnmount=function(){this.cancelForceUpdateImmediate()},n.prototype.generatorDefaultValue=function(e){var t=this.props.defaultValue;return t||e},n.prototype.getStyleMap=function(){return O.get("customStyleMap")},n.prototype.setStyleMap=function(e){O.set("customStyleMap",e),this.render()},n.prototype.initPlugins=function(){var e=this,t=["focus","getEditorState","setEditorState","getStyleMap","setStyleMap"];return this.getPlugins().map(function(n){return t.forEach(function(t){n.callbacks.hasOwnProperty(t)&&(n.callbacks[t]=e[t].bind(e))}),n})},n.prototype.focusEditor=function(e){this.refs.editor.focus(e),this.props.readOnly&&this._focusDummy.focus(),this.props.onFocus&&this.props.onFocus(e)},n.prototype._focus=function(e){if(e&&e.nativeEvent&&e.nativeEvent.target&&(!document.activeElement||"true"!==document.activeElement.getAttribute("contenteditable")))return this.focus(e)},n.prototype.focus=function(e){var t=this,n=e&&e.nativeEvent;if(n&&n.target===this._editorWrapper){var r=this.state.editorState,o=r.getSelection();if(!o.getHasFocus()&&o.isCollapsed())return this.setState({editorState:f.EditorState.moveSelectionToEnd(r)},function(){t.focusEditor(e)})}this.focusEditor(e)},n.prototype.getPlugins=function(){return this.state.plugins.slice()},n.prototype.getEventHandler=function(){var e=this,t=["onUpArrow","onDownArrow","handleReturn","onFocus","onBlur","onTab","handlePastedText"],n={};return t.forEach(function(t){n[t]=e.generatorEventHandler(t)}),n},n.prototype.getEditorState=function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.refs.editor.focus(),this.state.editorState},n.prototype.setEditorState=function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=e;this.getPlugins().forEach(function(e){if(e.onChange){var t=e.onChange(o);t&&(o=t)}}),this.props.onChange&&(this.props.onChange(o),this.controlledMode&&(this.forceUpdateImmediate=r(function(){return t.setState({editorState:new f.EditorState(t.state.editorState.getImmutable())})}))),this.controlledMode||this.setState({editorState:o},n?function(){return r(function(){return t.refs.editor.focus()})}:s)},n.prototype.handleKeyBinding=function(e){if(this.props.onKeyDown){e.ctrlKey=x(e);var t=this.props.onKeyDown(e);return t||Object(f.getDefaultKeyBinding)(e)}return Object(f.getDefaultKeyBinding)(e)},n.prototype.handleKeyCommand=function(e){return this.props.multiLines?this.eventHandle("handleKeyBinding",e):"split-block"===e?"handled":"not-handled"},n.prototype.getBlockStyle=function(e){var t=O.get("customBlockStyleMap"),n=e.getType();return t.hasOwnProperty(n)?t[n]:""},n.prototype.blockRendererFn=function(e){var t=null;return this.getPlugins().forEach(function(n){if(n.blockRendererFn){var r=n.blockRendererFn(e);r&&(t=r)}}),t},n.prototype.eventHandle=function(e){for(var t,n=this.getPlugins(),r=arguments.length,o=Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];for(var a=0;a<n.length;a++){var s=n[a];if(s.callbacks[e]&&"function"==typeof s.callbacks[e]){var l;if(!0===(l=s.callbacks)[e].apply(l,o))return"handled"}}return this.props.hasOwnProperty(e)&&!0===(t=this.props)[e].apply(t,o)?"handled":"not-handled"},n.prototype.generatorEventHandler=function(e){var t=this;return function(){for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];return t.eventHandle.apply(t,[e].concat(r))}},n.prototype.customStyleFn=function(e){if(0===e.size)return{};for(var t=this.getPlugins(),n={},r=0;r<t.length;r++)if(t[r].customStyleFn){var o=t[r].customStyleFn(e);o&&S(n,o)}return n},n.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.toolbars,i=n.style,a=n.readOnly,s=n.multiLines,l=this.state,c=l.editorState,p=l.toolbarPlugins,d=O.get("customStyleMap"),h=O.get("blockRenderMap"),v=this.getEventHandler(),y=E.component,g=m()((e={},e[r+"-editor"]=!0,e.readonly=a,e.oneline=!s,e));return u.a.createElement("div",{style:i,className:g,onClick:this._focus.bind(this)},u.a.createElement(y,{editorState:c,prefixCls:r,className:r+"-toolbar",plugins:p,toolbars:o}),u.a.createElement("div",{className:r+"-editor-wrapper",ref:function(e){return t._editorWrapper=e},style:i,onClick:function(e){return e.preventDefault()}},u.a.createElement(f.Editor,S({},this.props,v,{ref:"editor",customStyleMap:d,customStyleFn:this.customStyleFn.bind(this),editorState:c,handleKeyCommand:this.handleKeyCommand.bind(this),keyBindingFn:this.handleKeyBinding.bind(this),onChange:this.setEditorState.bind(this),blockStyleFn:this.getBlockStyle.bind(this),blockRenderMap:h,handlePastedText:this.handlePastedText,blockRendererFn:this.blockRendererFn.bind(this)})),a?u.a.createElement("input",{style:k,ref:function(e){return t._focusDummy=e},onBlur:v.onBlur}):null,this.props.children))},n}(u.a.Component);T.GetText=C.b,T.GetHTML=Object(b.a)(O),T.defaultProps={multiLines:!0,plugins:[],prefixCls:"rc-editor-core",pluginConfig:{},toolbars:[],spilitLine:"enter"},T.childContextTypes={getEditorState:p.a.func,setEditorState:p.a.func},t.a=T}).call(t,n(234).clearImmediate,n(234).setImmediate)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(){}function c(e){}function p(){function e(e){}var t=(arguments.length>0&&void 0!==arguments[0]&&arguments[0],{onChange:e,onUpArrow:c,onDownArrow:c,getEditorState:c,setEditorState:c,handleReturn:c});return{name:"toolbar",decorators:[],callbacks:t,onChange:function(e){return t.onChange?t.onChange(e):e},component:g}}var f=n(0),d=n.n(f),h=n(67),v=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.render=function(){return d.a.createElement("div",null,this.props.children)},t}(d.a.Component),m=v,y=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n)),o={};return n.plugins.forEach(function(e){o[e.name]=e}),r.pluginsMap=Object(h.Map)(o),r.state={editorState:n.editorState,toolbars:[]},r}return l(t,e),t.prototype.renderToolbarItem=function(e,t){var n=this.pluginsMap.get(e);if(n&&n.component){var r=n.component,o={key:"toolbar-item-"+t,onClick:r.props?r.props.onClick:u};return d.a.isValidElement(r)?d.a.cloneElement(r,o):d.a.createElement(r,o)}return null},t.prototype.conpomentWillReceiveProps=function(e){this.render()},t.prototype.render=function(){var e=this,t=this.props,n=t.toolbars,r=t.prefixCls;return d.a.createElement("div",{className:r+"-toolbar"},n.map(function(t,n){var r=d.a.Children.map(t,e.renderToolbarItem.bind(e));return d.a.createElement(m,{key:"toolbar-"+n},r)}))},t}(d.a.Component),g=y;t.a=p},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(67),i=(n.n(o),function(){function e(){r(this,e),this._store=Object(o.Map)()}return e.prototype.set=function(e,t){this._store=this._store.set(e,t)},e.prototype.get=function(e){return this._store.get(e)},e}());t.a=i},function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}function o(e){return e.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;").split("\xa0").join("&nbsp;").split("\n").join("<br >\n")}function i(e){return e.replace(C,"-$1").toLowerCase().replace(g,"-$1-")}function a(e,t){var n=void 0;return"string"==typeof t?n=b.test(t):(n=!0,t=String(t)),n&&"0"!==t&&!0!==h[e]?t+"px":t}function s(e){return e?Object.keys(e).map(function(t){return i(t)+":"+a(t,e[t])}).join(";"):""}function l(e){return function(t){var n=t.getCurrentContent(),r=n.getBlockMap(),i=e.get("customStyleMap")||{},a=e.get("blockRenderMap")||{},l=e.get("customStyleFn"),c=e.get("toHTMLList");return v(i,y),r.map(function(e){var t="<div>",r="</div>",p=e.getText(),f=e.getType(),d=a.get(f);if(d){var h="function"==typeof d.element?d.elementTag||"div":"div";t="<"+(h||"div")+' style="'+s(a.get(f).style||{})+'">',r="</"+(h||"div")+">"}for(var m=e.getCharacterList(),y=null,g=null,b=[],C=0,w=0,S=p.length;w<S;w++){g=y;var x=m.get(w);y=x?x.getEntity():null,w>0&&y!==g&&(b.push([g,u(p.slice(C,w),m.slice(C,w))]),C=w)}return b.push([y,u(p.slice(C),m.slice(C))]),b.map(function(e){var r=e[0],a=e[1],u=a.map(function(e){return e[0]}).join(""),p=a.map(function(e){var t=e[0],n=e[1],r=o(t);if(n.size){var a={};n.forEach(function(e){if(i.hasOwnProperty(e)){var t=i[e];a=v(a,t)}});var u=l(n);return a=v(a,u),'<span style="'+s(a)+'">'+r+"</span>"}return"<span>"+r+"</span>"}).join("");if(r){var f=n.getEntity(r),d=f.getData();if(d&&d.export)t+=d.export(p,d);else{var h="";c.forEach(function(e){var t=e(u,f,n);t&&(h=t)}),h&&(t+=h)}}else t+=p}),t+=r}).join("\n")}}function u(e,t){for(var n=m,r=m,o=[],i=0,a=0,s=e.length;a<s;a++){r=n;var l=t.get(a);n=l?l.getStyle():m,a>0&&!Object(p.is)(n,r)&&(o.push([e.slice(i,a),r]),i=a)}return o.push([e.slice(i),n]),o}var c=n(44),p=n(67),f={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},d=["Webkit","ms","Moz","O"];Object.keys(f).forEach(function(e){d.forEach(function(t){f[r(t,e)]=f[e]})});var h=f;t.a=l;var v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},m=Object(p.OrderedSet)(),y=c.DefaultDraftInlineStyle,g=/^(moz|ms|o|webkit)-/,b=/^\d+$/,C=/([A-Z])/g},function(e,t,n){"use strict";function r(e){return e.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;").split("\xa0").join("&nbsp;").split("\n").join("<br />\n")}function o(e){return e.split("<br />\n").join("\n")}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{encode:!1},n=e.getCurrentContent(),o=n.getBlockMap(),i=t.encode;return o.map(function(e){var t="",o=0,a=e.getText();return e.findEntityRanges(function(e){return!!e.getEntity()},function(r,i){var s=e.getEntityAt(r),l=n.getEntity(s).getData();t+=a.slice(o,r),t+=l&&l.export?l.export(l):a.slice(r,i),o=i}),t+=a.slice(o),i?r(t):t}).join(i?"<br />\n":"\n")}t.a=o,t.b=i},function(e,t,n){"use strict";function r(e,t){var n=(new DOMParser).parseFromString(e,"text/html");a()(n.querySelectorAll("img")).forEach(f);var r=Object(o.convertFromHTML)(n.body.innerHTML),i=r.contentBlocks;return i=i.reduce(function(e,n){if("blockquote"!==n.getType())return e.concat(n);var r=JSON.parse(n.getText());t.createEntity("IMAGE-ENTITY","IMMUTABLE",r);var i=t.getLastCreatedEntityKey(),a=o.CharacterMetadata.create({entity:i}),l=[new o.ContentBlock({key:Object(o.genKey)(),type:"image-block",text:" ",characterList:Object(s.List)(Object(s.Repeat)(a,a.count()))}),new o.ContentBlock({key:Object(o.genKey)(),type:"unstyled",text:"",characterList:Object(s.List)()})];return e.concat(l)},[]),n=null,o.BlockMapBuilder.createFromArray(i)}t.a=r;var o=n(44),i=(n.n(o),n(516)),a=n.n(i),s=n(67),l=(n.n(s),function(e){return{contentType:"image",src:e.getAttribute("src"),width:e.getAttribute("width"),height:e.getAttribute("height"),align:e.style.cssFloat}}),u=function(e){if(null==e)return null;var t=document.createElement("blockquote");return t.innerText=JSON.stringify(e),t},c=function(e,t){if(t instanceof HTMLElement){return e.parentNode.replaceChild(t,e)}},p=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=arguments,o=r.length-1;return function(){for(var e=o,t=r[o].apply(this,arguments);e--;)t=r[e].call(this,t);return t}}(u,l),f=function(e){return c(e,p(e))}},function(e,t,n){function r(e){if(!e)return[];if(s(e))return l(e)?f(e):i(e);if(m&&e[m])return u(e[m]());var t=a(e);return(t==h?c:t==v?p:d)(e)}var o=n(72),i=n(202),a=n(235),s=n(76),l=n(520),u=n(521),c=n(237),p=n(99),f=n(522),d=n(526),h="[object Map]",v="[object Set]",m=o?o.iterator:void 0;e.exports=r},function(e,t,n){var r=n(53),o=n(33),i=r(o,"DataView");e.exports=i},function(e,t,n){var r=n(53),o=n(33),i=r(o,"Promise");e.exports=i},function(e,t,n){var r=n(53),o=n(33),i=r(o,"WeakMap");e.exports=i},function(e,t,n){function r(e){return"string"==typeof e||!i(e)&&a(e)&&o(e)==s}var o=n(52),i=n(37),a=n(43),s="[object String]";e.exports=r},function(e,t){function n(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}e.exports=n},function(e,t,n){function r(e){return i(e)?a(e):o(e)}var o=n(523),i=n(524),a=n(525);e.exports=r},function(e,t){function n(e){return e.split("")}e.exports=n},function(e,t){function n(e){return r.test(e)}var r=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");e.exports=n},function(e,t){function n(e){return e.match(p)||[]}var r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",o="\\ud83c[\\udffb-\\udfff]",i="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",s="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",l="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",i,a].join("|")+")[\\ufe0e\\ufe0f]?"+s+")*",u="[\\ufe0e\\ufe0f]?"+s+l,c="(?:"+["[^\\ud800-\\udfff]"+r+"?",r,i,a,"[\\ud800-\\udfff]"].join("|")+")",p=RegExp(o+"(?="+o+")|"+c+u,"g");e.exports=n},function(e,t,n){function r(e){return null==e?[]:o(e,i(e))}var o=n(527),i=n(160);e.exports=r},function(e,t,n){function r(e,t){return o(t,function(t){return e[t]})}var o=n(192);e.exports=r},function(e,t,n){function r(e){if(!o(e))return i(e);var t=[];for(var n in Object(e))s.call(e,n)&&"constructor"!=n&&t.push(n);return t}var o=n(143),i=n(529),a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){var r=n(204),o=r(Object.keys,Object);e.exports=o},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t,n){function r(e,t){return e&&e.length?i(e,o(t,2)):[]}var o=n(532),i=n(554);e.exports=r},function(e,t,n){function r(e){return"function"==typeof e?e:null==e?a:"object"==typeof e?s(e)?i(e[0],e[1]):o(e):l(e)}var o=n(533),i=n(548),a=n(146),s=n(37),l=n(551);e.exports=r},function(e,t,n){function r(e){var t=i(e);return 1==t.length&&t[0][2]?a(t[0][0],t[0][1]):function(n){return n===e||o(n,e,t)}}var o=n(534),i=n(547),a=n(243);e.exports=r},function(e,t,n){function r(e,t,n,r){var l=n.length,u=l,c=!r;if(null==e)return!u;for(e=Object(e);l--;){var p=n[l];if(c&&p[2]?p[1]!==e[p[0]]:!(p[0]in e))return!1}for(;++l<u;){p=n[l];var f=p[0],d=e[f],h=p[1];if(c&&p[2]){if(void 0===d&&!(f in e))return!1}else{var v=new o;if(r)var m=r(d,h,f,e,t,v);if(!(void 0===m?i(h,d,a|s,r,v):m))return!1}}return!0}var o=n(141),i=n(238),a=1,s=2;e.exports=r},function(e,t,n){function r(e,t,n,r,m,g){var b=u(e),C=u(t),w=b?h:l(e),S=C?h:l(t);w=w==d?v:w,S=S==d?v:S;var x=w==v,_=S==v,k=w==S;if(k&&c(e)){if(!c(t))return!1;b=!0,x=!1}if(k&&!x)return g||(g=new o),b||p(e)?i(e,t,n,r,m,g):a(e,t,w,n,r,m,g);if(!(n&f)){var E=x&&y.call(e,"__wrapped__"),O=_&&y.call(t,"__wrapped__");if(E||O){var T=E?e.value():e,N=O?t.value():t;return g||(g=new o),m(T,N,n,r,g)}}return!!k&&(g||(g=new o),s(e,t,n,r,m,g))}var o=n(141),i=n(239),a=n(539),s=n(540),l=n(235),u=n(37),c=n(144),p=n(145),f=1,d="[object Arguments]",h="[object Array]",v="[object Object]",m=Object.prototype,y=m.hasOwnProperty;e.exports=r},function(e,t){function n(e){return this.__data__.set(e,r),this}var r="__lodash_hash_undefined__";e.exports=n},function(e,t){function n(e){return this.__data__.has(e)}e.exports=n},function(e,t){function n(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}e.exports=n},function(e,t,n){function r(e,t,n,r,o,x,k){switch(n){case S:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case w:return!(e.byteLength!=t.byteLength||!x(new i(e),new i(t)));case f:case d:case m:return a(+e,+t);case h:return e.name==t.name&&e.message==t.message;case y:case b:return e==t+"";case v:var E=l;case g:var O=r&c;if(E||(E=u),e.size!=t.size&&!O)return!1;var T=k.get(e);if(T)return T==t;r|=p,k.set(e,t);var N=s(E(e),E(t),r,o,x,k);return k.delete(e),N;case C:if(_)return _.call(e)==_.call(t)}return!1}var o=n(72),i=n(201),a=n(74),s=n(239),l=n(237),u=n(99),c=1,p=2,f="[object Boolean]",d="[object Date]",h="[object Error]",v="[object Map]",m="[object Number]",y="[object RegExp]",g="[object Set]",b="[object String]",C="[object Symbol]",w="[object ArrayBuffer]",S="[object DataView]",x=o?o.prototype:void 0,_=x?x.valueOf:void 0;e.exports=r},function(e,t,n){function r(e,t,n,r,a,l){var u=n&i,c=o(e),p=c.length;if(p!=o(t).length&&!u)return!1;for(var f=p;f--;){var d=c[f];if(!(u?d in t:s.call(t,d)))return!1}var h=l.get(e);if(h&&l.get(t))return h==t;var v=!0;l.set(e,t),l.set(t,e);for(var m=u;++f<p;){d=c[f];var y=e[d],g=t[d];if(r)var b=u?r(g,y,d,t,e,l):r(y,g,d,e,t,l);if(!(void 0===b?y===g||a(y,g,n,r,l):b)){v=!1;break}m||(m="constructor"==d)}if(v&&!m){var C=e.constructor,w=t.constructor;C!=w&&"constructor"in e&&"constructor"in t&&!("function"==typeof C&&C instanceof C&&"function"==typeof w&&w instanceof w)&&(v=!1)}return l.delete(e),l.delete(t),v}var o=n(541),i=1,a=Object.prototype,s=a.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){return o(e,a,i)}var o=n(542),i=n(544),a=n(160);e.exports=r},function(e,t,n){function r(e,t,n){var r=t(e);return i(e)?r:o(r,n(e))}var o=n(543),i=n(37);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}e.exports=n},function(e,t,n){var r=n(545),o=n(546),i=Object.prototype,a=i.propertyIsEnumerable,s=Object.getOwnPropertySymbols,l=s?function(e){return null==e?[]:(e=Object(e),r(s(e),function(t){return a.call(e,t)}))}:o;e.exports=l},function(e,t){function n(e,t){for(var n=-1,r=null==e?0:e.length,o=0,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[o++]=a)}return i}e.exports=n},function(e,t){function n(){return[]}e.exports=n},function(e,t,n){function r(e){for(var t=i(e),n=t.length;n--;){var r=t[n],a=e[r];t[n]=[r,a,o(a)]}return t}var o=n(242),i=n(160);e.exports=r},function(e,t,n){function r(e,t){return s(e)&&l(t)?u(c(e),t):function(n){var r=i(n,e);return void 0===r&&r===t?a(n,e):o(t,r,p|f)}}var o=n(238),i=n(137),a=n(549),s=n(131),l=n(242),u=n(243),c=n(75),p=1,f=2;e.exports=r},function(e,t,n){function r(e,t){return null!=e&&i(e,t,o)}var o=n(550),i=n(190);e.exports=r},function(e,t){function n(e,t){return null!=e&&t in Object(e)}e.exports=n},function(e,t,n){function r(e){return a(e)?o(s(e)):i(e)}var o=n(552),i=n(553),a=n(131),s=n(75);e.exports=r},function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}e.exports=n},function(e,t,n){function r(e){return function(t){return o(t,e)}}var o=n(193);e.exports=r},function(e,t,n){function r(e,t,n){var r=-1,p=i,f=e.length,d=!0,h=[],v=h;if(n)d=!1,p=a;else if(f>=c){var m=t?null:l(e);if(m)return u(m);d=!1,p=s,v=new o}else v=t?[]:h;e:for(;++r<f;){var y=e[r],g=t?t(y):y;if(y=n||0!==y?y:0,d&&g===g){for(var b=v.length;b--;)if(v[b]===g)continue e;t&&v.push(g),h.push(y)}else p(v,g,n)||(v!==h&&v.push(g),h.push(y))}return h}var o=n(240),i=n(555),a=n(560),s=n(241),l=n(561),u=n(99),c=200;e.exports=r},function(e,t,n){function r(e,t){return!!(null==e?0:e.length)&&o(e,t,0)>-1}var o=n(556);e.exports=r},function(e,t,n){function r(e,t,n){return t===t?a(e,t,n):o(e,i,n)}var o=n(557),i=n(558),a=n(559);e.exports=r},function(e,t){function n(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}e.exports=n},function(e,t){function n(e){return e!==e}e.exports=n},function(e,t){function n(e,t,n){for(var r=n-1,o=e.length;++r<o;)if(e[r]===t)return r;return-1}e.exports=n},function(e,t){function n(e,t,n){for(var r=-1,o=null==e?0:e.length;++r<o;)if(n(t,e[r]))return!0;return!1}e.exports=n},function(e,t,n){var r=n(236),o=n(562),i=n(99),a=r&&1/i(new r([,-0]))[1]==1/0?function(e){return new r(e)}:o;e.exports=a},function(e,t){function n(){}e.exports=n},function(e,t){e.exports={name:"antd",version:"3.3.3",title:"Ant Design",description:"An enterprise-class UI design language and React-based implementation",homepage:"http://ant.design/",keywords:["ant","design","react","react-component","component","components","ui","framework","frontend"],contributors:["ant"],repository:{type:"git",url:"https://github.com/ant-design/ant-design"},bugs:{url:"https://github.com/ant-design/ant-design/issues"},main:"lib/index.js",module:"es/index.js",files:["dist","lib","es"],typings:"lib/index.d.ts",license:"MIT",peerDependencies:{react:">=16.0.0","react-dom":">=16.0.0"},dependencies:{"array-tree-filter":"^2.0.0","babel-runtime":"6.x",classnames:"~2.2.0","create-react-class":"^15.6.0","css-animation":"^1.2.5","dom-closest":"^0.2.0","enquire.js":"^2.1.1",lodash:"^4.17.5",moment:"^2.19.3","omit.js":"^1.0.0","prop-types":"^15.5.7","rc-animate":"^2.4.1","rc-calendar":"~9.6.0","rc-cascader":"~0.12.0","rc-checkbox":"~2.1.5","rc-collapse":"~1.8.0","rc-dialog":"~7.1.0","rc-dropdown":"~2.1.0","rc-editor-mention":"^1.0.2","rc-form":"^2.1.0","rc-input-number":"~4.0.0","rc-menu":"~6.2.0","rc-notification":"~3.0.0","rc-pagination":"~1.16.0","rc-progress":"~2.2.2","rc-rate":"~2.4.0","rc-select":"~7.7.0","rc-slider":"~8.6.0","rc-steps":"~3.1.0","rc-switch":"~1.6.0","rc-table":"~6.1.0","rc-tabs":"~9.2.0","rc-time-picker":"~3.3.0","rc-tooltip":"~3.7.0","rc-tree":"~1.7.11","rc-tree-select":"~1.12.0","rc-upload":"~2.4.0","rc-util":"^4.0.4","react-lazy-load":"^3.0.12","react-slick":"~0.21.0",shallowequal:"^1.0.1",warning:"~3.0.0"},devDependencies:{"@types/react":"^16.0.0","@types/react-dom":"^16.0.0","ansi-styles":"^3.2.0","ant-design-palettes":"^1.0.0","antd-tools":"^5.1.2","babel-cli":"^6.18.0","babel-eslint":"^8.1.1","babel-plugin-import":"^1.0.0","babel-plugin-transform-runtime":"^6.23.0","babel-preset-es2015":"^6.18.0","babel-preset-react":"^6.16.0","babel-preset-stage-0":"^6.16.0","bezier-easing":"^2.0.3",bisheng:"^0.28.0","bisheng-plugin-antd":"^0.16.0","bisheng-plugin-description":"^0.1.1","bisheng-plugin-react":"^0.6.0","bisheng-plugin-toc":"^0.4.0",commander:"^2.11.0","cross-env":"^5.0.3","css-split-webpack-plugin":"^0.2.3",dekko:"^0.2.0",delegate:"^3.1.2","docsearch.js":"^2.5.2","dora-plugin-upload":"^0.3.1","enquire-js":"^0.1.2",enzyme:"^3.1.0","enzyme-adapter-react-16":"^1.0.0","enzyme-to-json":"^3.1.2",eslint:"^4.8.0","eslint-config-airbnb":"latest","eslint-plugin-babel":"^4.0.0","eslint-plugin-import":"^2.2.0","eslint-plugin-jsx-a11y":"^6.0.2","eslint-plugin-markdown":"~1.0.0-beta.4","eslint-plugin-react":"7.7.0","eslint-tinker":"^0.4.0","fetch-jsonp":"^1.0.3",glob:"^7.1.1","immutability-helper":"^2.5.0","intersection-observer":"^0.5.0",jest:"^22.4.2","jsonml.js":"^0.1.0","lint-staged":"^7.0.0","lz-string":"^1.4.4",majo:"^0.4.1",mockdate:"^2.0.1","moment-timezone":"^0.5.5","pre-commit":"^1.2.2",preact:"^8.2.5","preact-compat":"^3.17.0",querystring:"^0.2.0","rc-drawer-menu":"^0.5.3","rc-queue-anim":"^1.4.1","rc-scroll-anim":"^2.2.1","rc-tween-one":"^1.7.2",react:"^16.0.0","react-color":"^2.11.7","react-copy-to-clipboard":"^5.0.0","react-dnd":"^2.5.4","react-dnd-html5-backend":"^2.5.4","react-document-title":"^2.0.1","react-dom":"^16.0.0","react-github-button":"^0.1.1","react-infinite-scroller":"^1.0.15","react-intl":"^2.0.1","react-sublime-video":"^0.2.0","react-virtualized":"~9.18.5","remark-frontmatter":"^1.1.0","remark-parse":"^5.0.0","remark-stringify":"^5.0.0","remark-yaml-config":"^4.0.1",reqwest:"^2.0.5",rimraf:"^2.5.4",scrollama:"^1.4.1",stylelint:"^9.1.1","stylelint-config-standard":"^18.0.0",typescript:"~2.7.2",unified:"^6.1.5","values.js":"^1.0.3",xhr2:"^0.1.3"},scripts:{test:"jest --config .jest.js","test-node":"jest --config .jest.node.js","test-all":"./scripts/test-all.sh",lint:"npm run lint:ts && npm run lint:es && npm run lint:demo && npm run lint:style","lint:ts":"npm run tsc && antd-tools run ts-lint","lint:es":"eslint tests site scripts components ./.eslintrc.js ./webpack.config.js --ext '.js,.jsx'","lint:demo":"cross-env RUN_ENV=DEMO eslint components/*/demo/*.md --ext '.md'","lint:style":'stylelint "{site,components}/**/*.less" --syntax less',"lint-fix:ts":"npm run tsc && antd-tools run ts-lint-fix","lint-fix":"npm run lint-fix:code && npm run lint-fix:demo","lint-fix:code":"eslint --fix tests site scripts components ./.eslintrc.js ./webpack.config.js --ext '.js,.jsx'","lint-fix:demo":"eslint-tinker ./components/*/demo/*.md","sort-api":"node ./scripts/sort-api-table.js",dist:"antd-tools run dist",compile:"antd-tools run compile",tsc:"tsc",start:"rimraf _site && node ./scripts/generateColorLess.js && cross-env NODE_ENV=development bisheng start -c ./site/bisheng.config.js","start:preact":"node ./scripts/generateColorLess.js && cross-env NODE_ENV=development REACT_ENV=preact bisheng start -c ./site/bisheng.config.js",site:"cross-env NODE_ENV=production bisheng build --ssr -c ./site/bisheng.config.js && node ./scripts/generateColorLess.js",predeploy:"antd-tools run clean && npm run site",deploy:"bisheng gh-pages --push-only",pub:"antd-tools run pub",prepublish:"antd-tools run guard","pre-publish":"npm run test-all && node ./scripts/prepub",authors:"git log --format='%aN <%aE>' | sort -u | grep -v 'users.noreply.github.com' | grep -v 'gitter.im' | grep -v '.local>' | grep -v 'alibaba-inc.com' | grep -v 'alipay.com' | grep -v 'taobao.com' > AUTHORS.txt","lint-staged":"lint-staged","lint-staged:ts":"tsc && node node_modules/tslint/bin/tslint -c node_modules/antd-tools/lib/tslint.json","lint-staged:es":"eslint ./.eslintrc.js ./webpack.config.js","lint-staged:demo":"cross-env RUN_ENV=DEMO eslint --ext '.md'"},"lint-staged":{"components/**/*.tsx":["npm run lint-staged:ts"],"{tests,site,scripts,components}/**/*.{js,jsx}":["npm run lint-staged:es"],"{site,components}/**/*.less":"stylelint --syntax less","components/*/demo/*.md":["npm run lint-staged:demo"]},"pre-commit":["lint-staged"]}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(596));n.n(o)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(607));n.n(o),n(101)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(610));n.n(o),n(161)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(636));n.n(o)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(637));n.n(o)},function(e,t,n){e.exports=n(570)},function(e,t,n){function r(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-(\w)/g,function(e,t){return t.toUpperCase()})}var o=n(571);o.keys().forEach(function(e){var n=o(e);n&&n.default&&(n=n.default);var i=e.match(/^\.\/([^_][\w-]+)\/index\.tsx?$/);i&&i[1]&&("message"===i[1]||"notification"===i[1]?t[i[1]]=n:t[r(i[1])]=n)}),e.exports=n(252)},function(e,t,n){function r(e){return n(o(e))}function o(e){var t=i[e];if(!(t+1))throw new Error("Cannot find module '"+e+"'.");return t}var i={"./affix/style/index.tsx":572,"./alert/style/index.tsx":574,"./anchor/style/index.tsx":576,"./auto-complete/style/index.tsx":578,"./avatar/style/index.tsx":583,"./back-top/style/index.tsx":585,"./badge/style/index.tsx":587,"./breadcrumb/style/index.tsx":589,"./button/style/index.tsx":161,"./calendar/style/index.tsx":591,"./card/style/index.tsx":594,"./carousel/style/index.tsx":597,"./cascader/style/index.tsx":599,"./checkbox/style/index.tsx":164,"./col/style/index.tsx":602,"./collapse/style/index.tsx":603,"./date-picker/style/index.tsx":605,"./divider/style/index.tsx":608,"./dropdown/style/index.tsx":566,"./form/style/index.tsx":611,"./grid/style/index.tsx":249,"./icon/style/index.tsx":613,"./input-number/style/index.tsx":614,"./input/style/index.tsx":101,"./layout/style/index.tsx":616,"./list/style/index.tsx":618,"./locale-provider/style/index.tsx":622,"./mention/style/index.tsx":624,"./menu/style/index.tsx":626,"./message/style/index.tsx":629,"./modal/style/index.tsx":631,"./notification/style/index.tsx":633,"./pagination/style/index.tsx":251,"./popconfirm/style/index.tsx":635,"./popover/style/index.tsx":567,"./progress/style/index.tsx":568,"./radio/style/index.tsx":247,"./rate/style/index.tsx":638,"./row/style/index.tsx":640,"./select/style/index.tsx":163,"./slider/style/index.tsx":641,"./spin/style/index.tsx":250,"./steps/style/index.tsx":643,"./switch/style/index.tsx":645,"./table/style/index.tsx":647,"./tabs/style/index.tsx":564,"./tag/style/index.tsx":649,"./time-picker/style/index.tsx":565,"./timeline/style/index.tsx":651,"./tooltip/style/index.tsx":245,"./transfer/style/index.tsx":653,"./tree-select/style/index.tsx":655,"./tree/style/index.tsx":657,"./upload/style/index.tsx":659,"./version/style/index.tsx":661};r.keys=function(){return Object.keys(i)},r.resolve=o,e.exports=r,r.id=571},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(573));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(575));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(577));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(579));n.n(o),n(163)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(584));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(586));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(588));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(590));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(592));n.n(o),n(163),n(247)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(595));n.n(o),n(564)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(598));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(600));n.n(o),n(101)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(248));n.n(o)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(604));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(606));n.n(o),n(101),n(565)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(609));n.n(o)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(612));n.n(o),n(249)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13);n.n(r)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(615));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(617));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(619));n.n(o),n(250),n(251),n(249)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(623);n.n(r)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(625);n.n(r)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(627));n.n(o),n(245)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(630));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(632));n.n(o),n(161)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(634));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13);n.n(r),n(567),n(161)},function(e,t){},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(639));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(248));n.n(o)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(642));n.n(o),n(245)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(644));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(646));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(648));n.n(o),n(247),n(164),n(566),n(250),n(251)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(650));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(652));n.n(o)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(654));n.n(o),n(164),n(161),n(101)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(656));n.n(o),n(163),n(164)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(658));n.n(o),n(164)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13),o=(n.n(r),n(660));n.n(o),n(568),n(245)},function(e,t){},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(13);n.n(r)}])}); //# sourceMappingURL=antd.min.js.map
src/client/songs/songlinklazy.react.js
steida/songary
import Component from '../components/component.react'; import React from 'react'; import SongLink from '../songs/songlink.react'; import listenSong from './listensong'; @listenSong export default class SongLinkLazy extends Component { static propTypes = { actions: React.PropTypes.object.isRequired, params: React.PropTypes.object.isRequired, song: React.PropTypes.object } render() { const {song} = this.props; if (!song) return null; return ( <SongLink song={song} /> ); } }
ajax/libs/yui/3.16.0/event-focus/event-focus-debug.js
stefanneculai/cdnjs
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-focus', function (Y, NAME) { /** * Adds bubbling and delegation support to DOM events focus and blur. * * @module event * @submodule event-focus */ var Event = Y.Event, YLang = Y.Lang, isString = YLang.isString, arrayIndex = Y.Array.indexOf, useActivate = (function() { // Changing the structure of this test, so that it doesn't use inline JS in HTML, // which throws an exception in Win8 packaged apps, due to additional security restrictions: // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences var supported = false, doc = Y.config.doc, p; if (doc) { p = doc.createElement("p"); p.setAttribute("onbeforeactivate", ";"); // onbeforeactivate is a function in IE8+. // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below). // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test). // onbeforeactivate is undefined in Webkit/Gecko. // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick). supported = (p.onbeforeactivate !== undefined); } return supported; }()); function define(type, proxy, directEvent) { var nodeDataKey = '_' + type + 'Notifiers'; Y.Event.define(type, { _useActivate : useActivate, _attach: function (el, notifier, delegate) { if (Y.DOM.isWindow(el)) { return Event._attach([type, function (e) { notifier.fire(e); }, el]); } else { return Event._attach( [proxy, this._proxy, el, this, notifier, delegate], { capture: true }); } }, _proxy: function (e, notifier, delegate) { var target = e.target, currentTarget = e.currentTarget, notifiers = target.getData(nodeDataKey), yuid = Y.stamp(currentTarget._node), defer = (useActivate || target !== currentTarget), directSub; notifier.currentTarget = (delegate) ? target : currentTarget; notifier.container = (delegate) ? currentTarget : null; // Maintain a list to handle subscriptions from nested // containers div#a>div#b>input #a.on(focus..) #b.on(focus..), // use one focus or blur subscription that fires notifiers from // #b then #a to emulate bubble sequence. if (!notifiers) { notifiers = {}; target.setData(nodeDataKey, notifiers); // only subscribe to the element's focus if the target is // not the current target ( if (defer) { directSub = Event._attach( [directEvent, this._notify, target._node]).sub; directSub.once = true; } } else { // In old IE, defer is always true. In capture-phase browsers, // The delegate subscriptions will be encountered first, which // will establish the notifiers data and direct subscription // on the node. If there is also a direct subscription to the // node's focus/blur, it should not call _notify because the // direct subscription from the delegate sub(s) exists, which // will call _notify. So this avoids _notify being called // twice, unnecessarily. defer = true; } if (!notifiers[yuid]) { notifiers[yuid] = []; } notifiers[yuid].push(notifier); if (!defer) { this._notify(e); } }, _notify: function (e, container) { var currentTarget = e.currentTarget, notifierData = currentTarget.getData(nodeDataKey), axisNodes = currentTarget.ancestors(), doc = currentTarget.get('ownerDocument'), delegates = [], // Used to escape loops when there are no more // notifiers to consider count = notifierData ? Y.Object.keys(notifierData).length : 0, target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret; // clear the notifications list (mainly for delegation) currentTarget.clearData(nodeDataKey); // Order the delegate subs by their placement in the parent axis axisNodes.push(currentTarget); // document.get('ownerDocument') returns null // which we'll use to prevent having duplicate Nodes in the list if (doc) { axisNodes.unshift(doc); } // ancestors() returns the Nodes from top to bottom axisNodes._nodes.reverse(); if (count) { // Store the count for step 2 tmp = count; axisNodes.some(function (node) { var yuid = Y.stamp(node), notifiers = notifierData[yuid], i, len; if (notifiers) { count--; for (i = 0, len = notifiers.length; i < len; ++i) { if (notifiers[i].handle.sub.filter) { delegates.push(notifiers[i]); } } } return !count; }); count = tmp; } // Walk up the parent axis, notifying direct subscriptions and // testing delegate filters. while (count && (target = axisNodes.shift())) { yuid = Y.stamp(target); notifiers = notifierData[yuid]; if (notifiers) { for (i = 0, len = notifiers.length; i < len; ++i) { notifier = notifiers[i]; sub = notifier.handle.sub; match = true; e.currentTarget = target; if (sub.filter) { match = sub.filter.apply(target, [target, e].concat(sub.args || [])); // No longer necessary to test against this // delegate subscription for the nodes along // the parent axis. delegates.splice( arrayIndex(delegates, notifier), 1); } if (match) { // undefined for direct subs e.container = notifier.container; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } delete notifiers[yuid]; count--; } if (e.stopped !== 2) { // delegates come after subs targeting this specific node // because they would not normally report until they'd // bubbled to the container node. for (i = 0, len = delegates.length; i < len; ++i) { notifier = delegates[i]; sub = notifier.handle.sub; if (sub.filter.apply(target, [target, e].concat(sub.args || []))) { e.container = notifier.container; e.currentTarget = target; ret = notifier.fire(e); } if (ret === false || e.stopped === 2 || // If e.stopPropagation() is called, notify any // delegate subs from the same container, but break // once the container changes. This emulates // delegate() behavior for events like 'click' which // won't notify delegates higher up the parent axis. (e.stopped && delegates[i+1] && delegates[i+1].container !== notifier.container)) { break; } } } if (e.stopped) { break; } } }, on: function (node, sub, notifier) { sub.handle = this._attach(node._node, notifier); }, detach: function (node, sub) { sub.handle.detach(); }, delegate: function (node, sub, notifier, filter) { if (isString(filter)) { sub.filter = function (target) { return Y.Selector.test(target._node, filter, node === target ? null : node._node); }; } sub.handle = this._attach(node._node, notifier, true); }, detachDelegate: function (node, sub) { sub.handle.detach(); } }, true); } // For IE, we need to defer to focusin rather than focus because // `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate, // el.onfocusin, doSomething, then el.onfocus. All others support capture // phase focus, which executes before doSomething. To guarantee consistent // behavior for this use case, IE's direct subscriptions are made against // focusin so subscribers will be notified before js following el.focus() is // executed. if (useActivate) { // name capture phase direct subscription define("focus", "beforeactivate", "focusin"); define("blur", "beforedeactivate", "focusout"); } else { define("focus", "focus", "focus"); define("blur", "blur", "blur"); } }, '3.16.0', {"requires": ["event-synthetic"]});
docs/app/Examples/elements/Rail/Variations/RailExampleClose.js
clemensw/stardust
import React from 'react' import { Grid, Image, Rail, Segment } from 'semantic-ui-react' const RailExampleClose = () => ( <Grid centered columns={3}> <Grid.Column> <Segment> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> <Rail close position='left'> <Segment>Left Rail Content</Segment> </Rail> <Rail close position='right'> <Segment>Right Rail Content</Segment> </Rail> </Segment> </Grid.Column> </Grid> ) export default RailExampleClose
node_modules/react-icons/md/adb.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdAdb = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m25 15c0.9 0 1.6-0.7 1.6-1.6s-0.7-1.8-1.6-1.8-1.6 0.8-1.6 1.8 0.7 1.6 1.6 1.6z m-10 0c0.9 0 1.6-0.7 1.6-1.6s-0.7-1.8-1.6-1.8-1.6 0.8-1.6 1.8 0.7 1.6 1.6 1.6z m11.9-7.7c2.9 2.1 4.7 5.5 4.7 9.3v1.8h-23.2v-1.8c0-3.8 1.8-7.2 4.7-9.3l-3.5-3.6 1.4-1.3 3.8 3.9c1.6-0.8 3.3-1.3 5.2-1.3s3.6 0.5 5.2 1.3l3.8-3.9 1.4 1.4z m-18.5 19.3v-6.6h23.2v6.6c0 6.5-5.1 11.8-11.6 11.8s-11.6-5.3-11.6-11.8z"/></g> </Icon> ) export default MdAdb
ajax/libs/react/18.0.0-alpha-d174d063d-20210922/cjs/react-jsx-runtime.development.js
cdnjs/cdnjs
/** @license React vundefined * react-jsx-runtime.development.js * * 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. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var React = require('react'); var _assign = require('object-assign'); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; exports.Fragment = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; var REACT_CACHE_TYPE = 0xeae4; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); exports.Fragment = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); REACT_CACHE_TYPE = symbolFor('react.cache'); } var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableCache = false; // Only used in www builds. var enableScopeAPI = false; // Experimental Create Event Handle API. var REACT_MODULE_REFERENCE = 0; if (typeof Symbol === 'function') { REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCache ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { return true; } } return false; } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case exports.Fragment: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; case REACT_CACHE_TYPE: return 'Cache'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } } } return null; } // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: _assign({}, props, { value: prevLog }), info: _assign({}, props, { value: prevInfo }), warn: _assign({}, props, { value: prevWarn }), error: _assign({}, props, { value: prevError }), group: _assign({}, props, { value: prevGroup }), groupCollapsed: _assign({}, props, { value: prevGroupCollapsed }), groupEnd: _assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var hasOwnProperty = Object.prototype.hasOwnProperty; var loggedTypeFailures = {}; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; var didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function warnIfStringRefCannotBeAutoConverted(config, self) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); didWarnAboutStringRefs[componentName] = true; } } } } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ function jsxDEV(type, config, maybeKey, source, self) { { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { key = '' + maybeKey; } if (hasValidKey(config)) { key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; warnIfStringRefCannotBeAutoConverted(config, self); } // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } } function getSourceInfoErrorAddendum(source) { { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { { if (typeof node !== 'object') { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentNameFromType(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(source); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { var children = props.children; if (children !== undefined) { if (isStaticChildren) { if (isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); } } else { validateChildKeys(children, type); } } } if (type === exports.Fragment) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } // These two functions exist to still get child warnings in dev // even with the prod transform. This means that jsxDEV is purely // opt-in behavior for better messages but that we won't stop // giving you warnings if you use production apis. function jsxWithValidationStatic(type, props, key) { { return jsxWithValidation(type, props, key, true); } } function jsxWithValidationDynamic(type, props, key) { { return jsxWithValidation(type, props, key, false); } } var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children. // for now we can ship identical prod functions var jsxs = jsxWithValidationStatic ; exports.jsx = jsx; exports.jsxs = jsxs; })(); }
src/components/DrawerLayout/index.js
r1cebank/react-native-boilerplate
/* eslint-disable no-return-assign */ /* eslint-disable no-underscore-dangle */ import React from 'react'; import { DrawerLayoutAndroid } from 'react-native'; class F8DrawerLayout extends React.Component { _drawer: ?DrawerLayoutAndroid; constructor(props: any, context: any) { super(props, context); this.openDrawer = this.openDrawer.bind(this); this.closeDrawer = this.closeDrawer.bind(this); this.onDrawerOpen = this.onDrawerOpen.bind(this); this.onDrawerClose = this.onDrawerClose.bind(this); this.handleBackButton = this.handleBackButton.bind(this); } render() { const { drawerPosition, ...props } = this.props; const { Right, Left } = DrawerLayoutAndroid.positions; return ( <DrawerLayoutAndroid ref={(drawer) => this._drawer = drawer} {...props} drawerPosition={drawerPosition === 'right' ? Right : Left} onDrawerOpen={this.onDrawerOpen} onDrawerClose={this.onDrawerClose} /> ); } componentWillUnmount() { this.context.removeBackButtonListener(this.handleBackButton); this._drawer = null; } handleBackButton(): boolean { this.closeDrawer(); return true; } onDrawerOpen() { this.context.addBackButtonListener(this.handleBackButton); if (this.props.onDrawerOpen) { this.props.onDrawerOpen(); } } onDrawerClose() { this.context.removeBackButtonListener(this.handleBackButton); if (this.props.onDrawerClose) { this.props.onDrawerClose(); } } closeDrawer() { if (this._drawer) { this._drawer.closeDrawer(); } } openDrawer() { if (this._drawer) { this._drawer.openDrawer(); } } } F8DrawerLayout.contextTypes = { addBackButtonListener: React.PropTypes.func, removeBackButtonListener: React.PropTypes.func }; module.exports = F8DrawerLayout;
src/Parser/MistweaverMonk/Modules/Spells/EnvelopingMists.js
mwwscott0/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatNumber } from 'common/format'; import Module from 'Parser/Core/Module'; import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing'; import Combatants from 'Parser/Core/Modules/Combatants'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; const debug = false; const EVM_HEALING_INCREASE = 0.3; const UNAFFECTED_SPELLS = [ SPELLS.CRANE_HEAL.id, ]; class EnvelopingMists extends Module { static dependencies = { combatants: Combatants, }; healing = 0; on_byPlayer_heal(event) { const targetId = event.targetID; const spellId = event.ability.guid; if (UNAFFECTED_SPELLS.indexOf(spellId) !== -1) { debug && console.log('Exiting'); return; } if (this.combatants.players[targetId]) { if (this.combatants.players[targetId].hasBuff(SPELLS.ENVELOPING_MISTS.id, event.timestamp, 0, 0) === true) { this.healing += calculateEffectiveHealing(event, EVM_HEALING_INCREASE); } } } on_finished() { if (debug) { console.log(`EvM Healing Contribution: ${this.healing}`); } } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.ENVELOPING_MISTS.id} />} value={`${formatNumber(this.healing)}`} label={( <dfn data-tip={'This is the effective healing contributed by the Eveloping Mists buff.'}> Healing Contributed </dfn> )} /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(50); } export default EnvelopingMists;
src/routes/Device/components/Device.js
KozlovDmitriy/Pos.Hierarchy.Net
import React from 'react' import PropTypes from 'prop-types' import Paper from '@material-ui/core/Paper' import Typography from '@material-ui/core/Typography' import { withStyles } from '@material-ui/core/styles' import Table from '@material-ui/core/Table' import TableBody from '@material-ui/core/TableBody' import TableCell from '@material-ui/core/TableCell' import TableRow from '@material-ui/core/TableRow' import TableHead from '@material-ui/core/TableHead' import DeviceLink from 'src/components/LogicalDeviceLink' import reactMixin from 'react-mixin' import ReactRethinkdb, { r } from 'react-rethinkdb' import Localization from 'localization' import ActionDelete from '@material-ui/icons/Delete' import StatusCode from 'src/components/StatusCode' import IconButton from '@material-ui/core/IconButton' import colors from 'src/components/colors' import ResolveEventDialog from 'src/containers/ResolveEventDialogContainer' import { LOST_TERMINAL } from 'src/actions/codes' import Timer from 'src/components/Timer' import DeviceSoftwareStatus from './DeviceSoftwareStatus' import DeviceConfigStatus from './DeviceConfigStatus' import CircularProgressbar from 'react-circular-progressbar' import 'react-circular-progressbar/dist/styles.css' import blue from '@material-ui/core/colors/blue' import grey from '@material-ui/core/colors/grey' const styles = theme => ({ root: { marginTop: theme.spacing.unit * 2, marginLeft: theme.spacing.unit * 2, marginRight: theme.spacing.unit * 2, paddingTop: theme.spacing.unit, paddingBottom: theme.spacing.unit }, icon: { padding: 5, marginRight: 24, color: theme.palette.common.white }, errorRow: { backgroundColor: colors.error, color: theme.palette.common.white, }, warningRow: { backgroundColor: colors.warning, color: theme.palette.common.white, }, colorPrimary: { backgroundColor: grey[200], }, barColorPrimary: { backgroundColor: blue[400], } }) class Device extends React.Component { static propTypes = { params: PropTypes.object, deviceId: PropTypes.number, data: PropTypes.object, setDeviceId: PropTypes.func, classes: PropTypes.object.isRequired } constructor (props) { super(props) // ReactRethinkdb.DefaultSession.connect(config.rethinkConfig) this.state = { openResolveDialog: false, event: null } this.onResolveClick = this.onResolveClick.bind(this) this.onCloseResolveDialog = this.onCloseResolveDialog.bind(this) } onCloseResolveDialog (event) { this.setState({ ...this.state, event: null, openResolveDialog: false }) } onResolveClick (event) { this.setState({ ...this.state, event, openResolveDialog: true }) } observe (props, state) { return { events: new ReactRethinkdb.QueryRequest({ query: r.table('Events') .orderBy({ index: r.desc('acceptedAt') }) .filter((row) => r.and( r.expr(['error', 'warning']).contains(row.getField('type')), r.or( r.not(row.hasFields('resolved')), row.getField('resolved').ne(true), ), row.getField('logicalDeviceId').eq(props.deviceId) ) ) .limit(10), // RethinkDB query changes: true, // subscribe to realtime changefeed initial: [] // return [] while loading }), lastStatusEvent: new ReactRethinkdb.QueryRequest({ query: r.table('Events') .orderBy({ index: r.desc('acceptedAt') }) .filter((row) => r.and( row.getField('type').eq('info'), row.getField('subtype').eq('device-status'), row.getField('logicalDeviceId').eq(props.deviceId), row.getField('code').ne(LOST_TERMINAL) )) .limit(1), // RethinkDB query changes: true, // subscribe to realtime changefeed initial: [] // return [] while loading }), lastEvent: new ReactRethinkdb.QueryRequest({ query: r.table('Events') .orderBy({ index: r.desc('acceptedAt') }) .filter((row) => r.and( row.getField('logicalDeviceId').eq(props.deviceId), row.getField('code').ne(LOST_TERMINAL) )) .limit(1), // RethinkDB query changes: true, // subscribe to realtime changefeed initial: [] // return [] while loading }) } } componentDidMount () { const { id } = this.props.params const intId = parseInt(id) if (this.props.deviceId !== intId) { this.props.setDeviceId(intId) } } render () { const { classes, data } = this.props if (data === null || this.props.deviceId !== parseInt(this.props.params.id)) { return (<div />) } const events = (this.data.events.value() || []) .sort((x, y) => x.acceptedAt <= y.acceptedAt ? 1 : -1) const lastEvent = this.data.lastEvent.value()[0] const lastStatusEvent = this.data.lastStatusEvent.value()[0] const lastQueryDate = lastEvent ? <Timer start={new Date(lastEvent.acceptedAt * 1000)} /> : Localization.DeviceNotInitialized const lastEventContent = lastStatusEvent && lastStatusEvent.content ? lastStatusEvent.content.value : {} const { filledRamMemory, emptyRamMemory } = lastEventContent const allRam = filledRamMemory && emptyRamMemory ? filledRamMemory + emptyRamMemory : void 0 const ramFilled = allRam ? Math.round(filledRamMemory / allRam * 100) : void 0 const eventsGrid = events.length > 0 ? ( <Paper className={classes.root}> <div style={{ padding: '0px 20px 0 20px' }}> <Typography component='h6' variant='subtitle1' > {Localization.Events} </Typography> </div> <Table> <TableHead> <TableRow> <TableCell tooltip={Localization.AcceptedAt}>{Localization.AcceptedAt}</TableCell> <TableCell tooltip={Localization.NumberOfEventUpdates}>{Localization.NumberOfEventUpdates}</TableCell> <TableCell tooltip={Localization.Type}>{Localization.Type}</TableCell> <TableCell tooltip={Localization.MessageEmitter}>{Localization.MessageEmitter}</TableCell> <TableCell tooltip={Localization.Description}>{Localization.Description}</TableCell> <TableCell style={{ width: '130px' }} /> </TableRow> </TableHead> <TableBody> { events.map((row, index) => { const className = row.type === 'error' ? classes.errorRow : classes.warningRow return ( <TableRow key={index}> <TableCell className={className}> {new Date(row['acceptedAt'] * 1000).toLocaleString()} </TableCell> <TableCell className={className}> {row.count} </TableCell> <TableCell className={className}> {row.type === 'error' ? Localization.Error : Localization.Warning} </TableCell> <TableCell className={className}>{Localization.Terminal}</TableCell> <TableCell className={className}> <StatusCode code={row.code} /> </TableCell> <TableCell style={{ width: '130px' }} className={className}> <IconButton className={classes.icon} onClick={e => this.onResolveClick(row)} > <ActionDelete /> </IconButton> </TableCell> </TableRow> ) }) } </TableBody> </Table> <ResolveEventDialog event={this.state.event} open={this.state.openResolveDialog} onClose={this.onCloseResolveDialog} /> </Paper> ) : void 0 const merchant = data.MerchantNumberX && data.MerchantName ? `${data.MerchantName} (${data.MerchantNumberX})` : data.MerchantName ? data.MerchantName : <i>{Localization.Unknown}</i> const customer = data.CustomerNumberX && data.CustomerName ? `${data.CustomerName} (${data.CustomerNumberX})` : data.CustomerName ? data.CustomerName : <i>{Localization.Unknown}</i> const account = data.AccountNumberX && data.AccountName ? `${data.AccountName} (${data.AccountNumberX})` : data.AccountName ? data.AccountName : <i>{Localization.Unknown}</i> return ( <div> <Paper className={classes.root} elevation={1}> <Typography component='h5' variant='h6' align='center'>{Localization.Device}</Typography> <Typography component='h6' variant='subtitle1' align='center'> {data.SimpleModelName} </Typography> <Table> <TableHead> <TableRow> <TableCell><b>{Localization.TerminalId}</b></TableCell> <TableCell><b>{Localization.Merchant}</b></TableCell> <TableCell><b>{Localization.Customer}</b></TableCell> <TableCell><b>{Localization.Account}</b></TableCell> <TableCell><b>{Localization.SerialNumber}</b></TableCell> <TableCell><b>{Localization.Complex}</b></TableCell> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell> <DeviceLink deviceId={data.Id} name={data.TerminalId} /> </TableCell> <TableCell>{merchant}</TableCell> <TableCell>{customer}</TableCell> <TableCell>{account}</TableCell> <TableCell>{data.SerialNumber}</TableCell> <TableCell>{data.ModelName}</TableCell> </TableRow> </TableBody> </Table> <div style={{ display: 'flex', alignItems: 'stretch', padding: '6px 20px 0 20px' }}> <div style={{ flexGrow: 1 }}> <Typography component='h6' variant='subtitle1' > {Localization.StatusOfWork} </Typography> <p> {Localization.TimeSinceLastRequest}: <code>{lastQueryDate}</code> </p> </div> { ramFilled ? ( <div style={{ flexGrow: 1 }}> <div style={{ display: 'flex', alignItems: 'stretch' }}> <div style={{ flexGrow: void 0, padding: '5px 10px' }}> <div style={{ display: 'inline-block', width: 50 }}> <CircularProgressbar text={`${ramFilled}%`} percentage={ramFilled} strokeWidth={12} initialAnimation styles={{ text: { fontSize: '26px', fontWeight: 600 } }} /> </div> </div> <div style={{ flexGrow: 1 }}> <Typography component='h6' variant='subtitle1' > {'RAM'} </Typography> <p> {Localization.FilledMemory}:&nbsp;{Math.floor(filledRamMemory / (1024 * 1024))} MB </p> </div> </div> </div> ) : void 0 } </div> </Paper> <div style={{ display: 'flex', alignItems: 'stretch' }}> <DeviceSoftwareStatus version={lastEventContent ? lastEventContent.softwareVersion : void 0} deviceId={data.Id} className={classes.root} /> <DeviceConfigStatus version={lastEventContent ? lastEventContent.configVersion : void 0} deviceId={data.Id} className={classes.root} /> </div> {eventsGrid} </div> ) } } reactMixin(Device.prototype, ReactRethinkdb.DefaultMixin) export default withStyles(styles)(Device)
src/shared-components/NotFoundPage.js
jch254/audio-insights
import React from 'react'; import { Box } from 'reflexbox'; import { PageHeader, Blockquote, Container, } from 'rebass'; import FadeInTransition from './FadeInTransition'; const NotFoundPage = () => ( <FadeInTransition> <Box key="unknown" style={{ flex: '1 0 auto' }}> <Container py={3}> <PageHeader my={2} py={2} description="Sorry mate, that page does not exist" heading="404!" /> <Blockquote source="J.R.R. Tolkien"> All that is gold does not glitter,<br /> Not all those who wander are lost;<br /> The old that is strong does not wither,<br /> Deep roots are not reached by the frost. </Blockquote> </Container> </Box> </FadeInTransition> ); export default NotFoundPage;
frontend/eyeballing/src/components/inline-style.js
linea-it/dri
import React from 'react'; import Proptypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; const styles = { textBig: { fontSize: '10vw', }, }; class Inline extends React.Component { static propTypes = { classes: Proptypes.object.isRequired, }; render() { const { classes } = this.props; return <div className={classes.textBig}>TEST</div>; } } export default withStyles(styles)(Inline);
index.android.js
bestofsong/rn-nav-tab-redux
'use strict' import React from 'react'; import {AppRegistry} from 'react-native'; import App from './app/app' AppRegistry.registerComponent('navExpRedux', () => App)
src/components/app/Help.js
Miroku87/pogo-raids-organizer
import React, { Component } from 'react'; import { Button } from "react-bootstrap"; export default class Help extends Component { render() { return ( <div className="help"></div> ); } }
examples/auth-flow/app.js
BerkeleyTrue/react-router
import React from 'react' import { render, findDOMNode } from 'react-dom' import { Router, Route, Link, History } from 'react-router' import { createHistory, useBasename } from 'history' import auth from './auth' const history = useBasename(createHistory)({ basename: '/auth-flow' }) var App = React.createClass({ getInitialState() { return { loggedIn: auth.loggedIn() } }, updateAuth(loggedIn) { this.setState({ loggedIn: loggedIn }) }, componentWillMount() { auth.onChange = this.updateAuth auth.login() }, render() { return ( <div> <ul> <li> {this.state.loggedIn ? ( <Link to="/logout">Log out</Link> ) : ( <Link to="/login">Sign in</Link> )} </li> <li><Link to="/about">About</Link></li> <li><Link to="/dashboard">Dashboard</Link> (authenticated)</li> </ul> {this.props.children} </div> ) } }) var Dashboard = React.createClass({ render() { var token = auth.getToken() return ( <div> <h1>Dashboard</h1> <p>You made it!</p> <p>{token}</p> </div> ) } }) var Login = React.createClass({ mixins: [ History ], getInitialState() { return { error: false } }, handleSubmit(event) { event.preventDefault() var email = findDOMNode(this.refs.email).value var pass = findDOMNode(this.refs.pass).value auth.login(email, pass, (loggedIn) => { if (!loggedIn) return this.setState({ error: true }) var { location } = this.props if (location.state && location.state.nextPathname) { this.history.replaceState(null, location.state.nextPathname) } else { this.history.replaceState(null, '/about') } }) }, render() { return ( <form onSubmit={this.handleSubmit}> <label><input ref="email" placeholder="email" defaultValue="[email protected]" /></label> <label><input ref="pass" placeholder="password" /></label> (hint: password1)<br /> <button type="submit">login</button> {this.state.error && ( <p>Bad login information</p> )} </form> ) } }) var About = React.createClass({ render() { return <h1>About</h1> } }) var Logout = React.createClass({ componentDidMount() { auth.logout() }, render() { return <p>You are now logged out</p> } }) function requireAuth(nextState, replaceState) { if (!auth.loggedIn()) replaceState({ nextPathname: nextState.location.pathname }, '/login') } render(( <Router history={history}> <Route path="/" component={App}> <Route path="login" component={Login} /> <Route path="logout" component={Logout} /> <Route path="about" component={About} /> <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> </Route> </Router> ), document.getElementById('example'))
svg-icons/image/brightness-3.js
janmarsicek/material-ui
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ImageBrightness3 = function ImageBrightness3(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54 0 4.48-2.94 8.27-7 9.54.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2z' }) ); }; ImageBrightness3 = (0, _pure2.default)(ImageBrightness3); ImageBrightness3.displayName = 'ImageBrightness3'; ImageBrightness3.muiName = 'SvgIcon'; exports.default = ImageBrightness3;
imanhua-muban/js/jquery-1.7.2.min.js
liudih/manhua
/*! jQuery v1.7.2 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function( a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f .clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
ajax/libs/yui/3.5.1/simpleyui/simpleyui.js
gogoleva/cdnjs
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. If YUI is already defined, the existing YUI object will not be overwritten so that defined namespaces are preserved. It is the constructor for the object the end user interacts with. As indicated below, each instance has full custom event support, but only if the event system is available. This is a self-instantiable factory function. You can invoke it directly like this: YUI().use('*', function(Y) { // ready }); But it also works like this: var Y = YUI(); Configuring the YUI object: YUI({ debug: true, combine: false }).use('node', function(Y) { //Node is ready to use }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. @class YUI @constructor @global @uses EventTarget @param [o]* {Object} 0..n optional configuration objects. these values are store in Y.config. See <a href="config.html">Config</a> for the list of supported properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** YUI.GlobalConfig is a master configuration that might span multiple contexts in a non-browser environment. It is applied first to all instances in all contexts. @property GlobalConfig @type {Object} @global @static @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** YUI_config is a page-level config. It is applied to all instances created on the page. This is applied after YUI.GlobalConfig, and before the instance level configuration objects. @global @property YUI_config @type {Object} @example //Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, [ 'loader-base', 'loader-rollup', 'loader-yui3' ])); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {Object} o the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get','features','intl-base','yui-log','yui-later'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, //extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later']; extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a module with the YUI global. The easiest way to create a first-class YUI module is to use the YUI component build tool. http://yuilibrary.com/projects/builder The build system will produce the `YUI.add` wrapper for you module, along with any configuration info required for the module. @method add @param name {String} module name. @param fn {Function} entry point into the module that is used to bind module to the YUI instance. @param {YUI} fn.Y The YUI instance this module is executed in. @param {String} fn.name The name of the module @param version {String} version string. @param details {Object} optional config data: @param details.requires {Array} features that must be present before this module can be attached. @param details.optional {Array} optional features that should be present if loadOptional is defined. Note: modules are not often loaded this way in YUI 3, but this field is still useful to inform the user that certain features in the component will require additional dependencies. @param details.use {Array} features that are included within this module which need to be attached automatically when this module is attached. This supports the YUI 3 rollup system -- a module with submodules defined will need to have the submodules listed in the 'use' config. The YUI component build tool does this for you. @return {YUI} the YUI instance. @example YUI.add('davglass', function(Y, name) { Y.davglass = function() { alert('Dav was here!'); }; }, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] }); */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @param {Array} r The array of modules to attach * @param {Boolean} [moot=false] Don't throw a warning if the module is not attached * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { Y.Object.each(loader.conditions[name], function(def) { var go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } }); } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String|Array} 1-n modules to bind (uses arguments array). * @param [callback] {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * @param callback.Y {YUI} The `YUI` instance created for this sandbox * @param callback.data {Object} Object data returned from `Loader`. * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, a = [], name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = []; if (!names.length) { return; } if (aliases) { for (i = 0; i < names.length; i++) { if (aliases[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } if (mods['loader'] && !Y.Loader) { Y._attach(['loader']); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Adds a namespace object onto the YUI global if called statically. // creates YUI.your.namespace.here as nested objects YUI.namespace("your.namespace.here"); If called as a method on a YUI <em>instance</em>, it creates the namespace on the instance. // creates Y.property.package Y.namespace("property.package"); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", the token is discarded. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace("really.long.nested.namespace"); <em>Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function.</em> @method namespace @param {String} namespace* namespaces to create. @return {Object} A reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controlled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown. If an `errorFn` is specified in the config * it must return `true` to keep the error from being thrown. * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param src Optional additional info (passed to `Y.config.errorFn` and `Y.message`) * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @param o {Object} The object to check. * @param type {Object} The class to check against. * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Static method on the Global YUI object to apply a config to all YUI instances. It's main use case is "mashups" where several third party scripts are trying to write to a global YUI config at the same time. This way they can all call `YUI.applyConfig({})` instead of overwriting other scripts configs. @static @since 3.5.0 @method applyConfig @param {Object} o the configuration object. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function(Y) { //Module davglass will be available here.. }); */ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Turns on writing Ylog messages to the browser console. * * @property debug * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default list). * * @property core * @type Array * @default [ get,features,intl-base,yui-log,yui-later,loader-base, loader-rollup, loader-yui3 ] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: '/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: '/mymod2/mymod2.js' * }, * mymod3: '/js/mymod3.js', * mycssmod: '/css/mycssmod.css' * } * * * @property modules * @type object */ /** * Aliases are dynamic groups of modules that can be used as * shortcuts. * * YUI({ * aliases: { * davglass: [ 'node', 'yql', 'dd' ], * mine: [ 'davglass', 'autocomplete'] * } * }).use('mine', function(Y) { * //Node, YQL, DD &amp; AutoComplete available here.. * }); * * @property aliases * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // The comboSeperator to use with this group's combo handler * comboSep: ';', * * // The maxURLLength for this server * maxURLLength: 500, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.9.0 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 4 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. Returning `true` from this * function will stop the Error from being thrown. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * Whether or not YUI should use native ES5 functionality when available for * features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will * always use its own fallback implementations instead of relying on ES5 * functionality, even when it's available. * * @method useNativeES5 * @type Boolean * @default true * @since 3.5.0 */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0 }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process == 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = process.versions.node; } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["app-base","app-transitions","model","model-list","router","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatable-deprecated": ["datatable-base-deprecated","datatable-datasource-deprecated","datatable-sort-deprecated","datatable-scroll-deprecated"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@' ); YUI.add('get', function(Y) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes async: doc && doc.createElement('script').async === true, // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+. cssFail: ua.gecko >= 9 || ua.webkit >= 535.24, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ((!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.webkit >= 535.24) && !(ua.chrome && ua.chrome <=18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(function () { item.callback && item.callback.apply(this, arguments); Get._pending = null; Get._next(); }); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._waiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._waiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } for (i = 0, len = requests.length; i < len; ++i) { req = self.requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, cachedNode, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && ua.ie < 9) { // Script on IE6, 7, and 8. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. node.onerror = onError; node.onload = onLoad; // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this._waiting += 1; this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._waiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._waiting -= 1; this._next(); } }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // io-nodejs add('load', '0', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // graphics-canvas-default add('load', '1', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // autocomplete-list-keys add('load', '2', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-svg add('load', '3', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // graphics-vml-default add('load', '5', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-svg-default add('load', '6', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // history-hash-ie add('load', '7', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // transition-timer add('load', '8', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // dom-style-ie add('load', '9', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // selector-css2 add('load', '10', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // widget-base-ie add('load', '11', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // event-base-ie add('load', '12', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // dd-gestures add('load', '13', { "name": "dd-gestures", "test": function(Y) { return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6)); }, "trigger": "dd-drag" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // app-transitions-native add('load', '15', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style); } return false; }, "trigger": "app-transitions" }); // graphics-canvas add('load', '16', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-vml add('load', '17', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later']}); YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // io-nodejs add('load', '0', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // graphics-canvas-default add('load', '1', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // autocomplete-list-keys add('load', '2', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-svg add('load', '3', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // graphics-vml-default add('load', '5', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-svg-default add('load', '6', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // history-hash-ie add('load', '7', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // transition-timer add('load', '8', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // dom-style-ie add('load', '9', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // selector-css2 add('load', '10', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // widget-base-ie add('load', '11', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // event-base-ie add('load', '12', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // dd-gestures add('load', '13', { "name": "dd-gestures", "test": function(Y) { return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6)); }, "trigger": "dd-drag" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // app-transitions-native add('load', '15', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style); } return false; }, "trigger": "app-transitions" }); // graphics-canvas add('load', '16', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-vml add('load', '17', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('dom-core', function(Y) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS]) { if (Y.UA.opera || needle[NODE_TYPE] === 1) { // IE & SAF contains fail if needle not an ELEMENT_NODE ret = element[CONTAINS](needle); } else { ret = Y_DOM._bruteContains(element, needle); } } else if (element[COMPARE_DOCUMENT_POSITION]) { // gecko if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.alert && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@' ,{requires:['oop','features']}); YUI.add('dom-base', function(Y) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } } } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; } creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@' ,{requires:['dom-core']}); YUI.add('dom-style', function(Y) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('dom-style-ie', function(Y) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@' ,{requires:['dom-style']}); YUI.add('dom-screen', function(Y) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@' ,{requires:['dom-base', 'dom-style']}); YUI.add('selector-native', function(Y) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector } }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(',', '\uE007', 'g'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('selector', function(Y) { }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.extend(Y.EventFacade, Object, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; if (self.stoppedFn) { events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } // if (subCount) { if (subs[0]) { // self._procSubs(Y.merge(self.subscribers), args, ef); self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; // self.bubbling = true; es.bubbling = self.type; // if (host !== ef.target || es.type != self.type) { if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); // self.bubbling = false; es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('node-core', function(Y) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a Node instance of nodes based on the given CSS selector. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node} A Node instance for the matching HTMLElement. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** Called on each Node instance * @method destroy * @see Node.destroy */ 'destroy', /** Called on each Node instance * @method empty * @see Node.empty */ 'empty', /** Called on each Node instance * @method remove * @see Node.remove */ 'remove', /** Called on each Node instance * @method set * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr); } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@' ,{requires:['dom-core', 'selector']}); YUI.add('node-base', function(Y) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** Called on each Node instance * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** Called on each Node instance * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** Called on each Node instance * @method prepend * @see Node.prepend */ 'prepend', /** Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML */ 'setContent', /** Called on each Node instance * @method getContent * @deprecated Use getHTML */ 'getContent', /** Called on each Node instance * @method setHTML * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. */ 'setHTML', /** Called on each Node instance * @method getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { var name = this.DATA_PREFIX + name, node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@' ,{requires:['dom-base', 'node-core', 'event-base']}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function(Y) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.subCount && !this.afterCount) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } add(win, "unload", onUnload); Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('pluginhost-base', function(Y) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config this[ns].setAttrs(config); } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namepsace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { this[ns].destroy(); delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('pluginhost-config', function(Y) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@' ,{requires:['pluginhost-base']}); YUI.add('event-delegate', function(Y) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('node-event-delegate', function(Y) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@' ,{requires:['node-base', 'event-delegate']}); YUI.add('node-pluginhost', function(Y) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); }; Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); }; }, '@VERSION@' ,{requires:['node-base', 'pluginhost']}); YUI.add('node-screen', function(Y) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config winHeight * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@' ,{requires:['node-base', 'dom-screen']}); YUI.add('node-style', function(Y) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@' ,{requires:['dom-style', 'node-base']}); YUI.add('querystring-stringify-simple', function(Y) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple * @for QueryString * @static */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; /** * <p>Converts a simple object to a Query String representation.</p> * <p>Nested objects, Arrays, and so on, are not supported.</p> * * @method stringify * @for QueryString * @public * @submodule querystring-stringify-simple * @param obj {Object} A single-level object to convert to a querystring. * @param cfg {Object} (optional) Configuration object. In the simple * module, only the arrayKey setting is * supported. When set to true, the key of an * array will have the '[]' notation appended * to the key;. * @static */ QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('io-base', function(Y) { /** Base IO functionality. Provides basic XHR transport support. @module io-base @main io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie ? 'xdr' : null; } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize an map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { data = Y.QueryString.stringify(data); } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials) { if (!Y.UA.ie) { transaction.c.withCredentials = true; } } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject; Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@' ,{requires:['event-custom-base', 'querystring-stringify-simple']}); YUI.add('json-parse', function(Y) { /** * <p>The JSON module adds support for serializing JavaScript objects into * JSON strings and parsing JavaScript objects from strings in JSON format.</p> * * <p>The JSON namespace is added to your YUI instance including static methods * Y.JSON.parse(..) and Y.JSON.stringify(..).</p> * * <p>The functionality and method signatures follow the ECMAScript 5 * specification. In browsers with native JSON support, the native * implementation is used.</p> * * <p>The <code>json</code> module is a rollup of <code>json-parse</code> and * <code>json-stringify</code>.</p> * * <p>As their names suggest, <code>json-parse</code> adds support for parsing * JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing * JavaScript data into JSON strings (Y.JSON.stringify). You may choose to * include either of the submodules individually if you don't need the * complementary functionality, or include the rollup for both.</p> * * @module json * @main json * @class JSON * @static */ /** * Provides Y.JSON.parse method to accept JSON strings and return native * JavaScript objects. * * @module json * @submodule json-parse * @for JSON * @static */ // All internals kept private for security reasons function fromGlobal(ref) { return (Y.config.win || this || {})[ref]; } /** * Alias to native browser implementation of the JSON object if available. * * @property Native * @type {Object} * @private */ var _JSON = fromGlobal('JSON'), Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON), useNative = !!Native, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences. * IMPORTANT NOTE: This regex will be used to modify the input if a match is * found. * * @property _UNICODE_EXCEPTIONS * @type {RegExp} * @private */ _UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, /** * First step in the safety evaluation. Regex used to replace all escape * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character). * * @property _ESCAPES * @type {RegExp} * @private */ _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, /** * Second step in the safety evaluation. Regex used to replace all simple * values with ']' characters. * * @property _VALUES * @type {RegExp} * @private */ _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, /** * Third step in the safety evaluation. Regex used to remove all open * square brackets following a colon, comma, or at the beginning of the * string. * * @property _BRACKETS * @type {RegExp} * @private */ _BRACKETS = /(?:^|:|,)(?:\s*\[)+/g, /** * Final step in the safety evaluation. Regex used to test the string left * after all previous replacements for invalid characters. * * @property _UNSAFE * @type {RegExp} * @private */ _UNSAFE = /[^\],:{}\s]/, /** * Replaces specific unicode characters with their appropriate \unnnn * format. Some browsers ignore certain characters during eval. * * @method escapeException * @param c {String} Unicode character * @return {String} the \unnnn escapement of the character * @private */ _escapeException = function (c) { return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4); }, /** * Traverses nested objects, applying a reviver function to each (key,value) * from the scope if the key:value's containing object. The value returned * from the function will replace the original value in the key:value pair. * If the value returned is undefined, the key will be omitted from the * returned object. * * @method _revive * @param data {MIXED} Any JavaScript data * @param reviver {Function} filter or mutation function * @return {MIXED} The results of the filtered data * @private */ _revive = function (data, reviver) { var walk = function (o,key) { var k,v,value = o[key]; if (value && typeof value === 'object') { for (k in value) { if (value.hasOwnProperty(k)) { v = walk(value, k); if (v === undefined) { delete value[k]; } else { value[k] = v; } } } } return reviver.call(o,key,value); }; return typeof reviver === 'function' ? walk({'':data},'') : data; }, /** * Parse a JSON string, returning the native JavaScript representation. * * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @method parse * @static */ // JavaScript implementation in lieu of native browser support. Based on // the json2.js library from http://json.org _parse = function (s,reviver) { // Replace certain Unicode characters that are otherwise handled // incorrectly by some browser implementations. // NOTE: This modifies the input if such characters are found! s = s.replace(_UNICODE_EXCEPTIONS, _escapeException); // Test for any remaining invalid characters if (!_UNSAFE.test(s.replace(_ESCAPES,'@'). replace(_VALUES,']'). replace(_BRACKETS,''))) { // Eval the text into a JavaScript data structure, apply any // reviver function, and return return _revive( eval('(' + s + ')'), reviver ); } throw new SyntaxError('JSON.parse'); }; Y.namespace('JSON').parse = function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && Y.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( Native ) { try { useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { useNative = false; } } /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ Y.JSON.useNativeParse = useNative; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('transition', function(Y) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', TRANSITION = 'transition', TRANSITION_CAMEL = 'Transition', TRANSITION_PROPERTY_CAMEL, TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, TRANSFORM_CAMEL, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + TRANSITION_CAMEL; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + TRANSITION_CAMEL; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform'; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration != 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay != 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur); return dur + 's'; }, _runNative: function(time) { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name == 'boolean') { // no transition, just toggle on = name; name = null; } name = name || Y.Transition.DEFAULT_TOGGLE; if (typeof on == 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(name, on, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); Transition.DEFAULT_TOGGLE = 'fade'; }, '@VERSION@' ,{requires:['node-style']}); YUI.add('selector-css2', function(Y) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('selector-css3', function(Y) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@' ,{requires:['selector-native', 'selector-css2']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('dump', function(Y) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('transition-timer', function(Y) { /* * The Transition Utility provides an API for creating advanced transitions. * @module transition */ /* * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@' ,{requires:['transition']}); YUI.add('simpleyui', function(Y) { // empty }, '@VERSION@' ,{use:['yui','oop','dom','event-custom-base','event-base','pluginhost','node','event-delegate','io-base','json-parse','transition','selector-css3','dom-style-ie','querystring-stringify-simple']}); var Y = YUI().use('*');
react-ui/src/components/game-diff.js
tdfranklin/retrocade
import React, { Component } from 'react'; import Canvas from './helpers/canvas'; import { SetCanvasText, LoadImg } from './helpers/helpers'; import { PongInstructions, SnakeInstructions } from './helpers/instructions'; import GameHome from './game-home'; import ThumbsUp from '../assets/img/thumbs-up.jpg'; class GameDifficulty extends Component { constructor(props) { super(props); this.state = { difficulty: 'Easy', diffSelected: false }; } static defaultProps = { } componentDidMount() { LoadImg('canvas', ThumbsUp, 215, 125, 400, 400); const text = `pick your poison for ${this.props.game}`; SetCanvasText('deeppink', text.toUpperCase(), '25px', 75, 50, 'canvas'); SetCanvasText('aqua', 'Easy', '40px', 10, 45, 'Easy'); SetCanvasText('aqua', 'Medium', '40px', 10, 45, 'Medium'); SetCanvasText('aqua', 'Hard', '40px', 10, 45, 'Hard'); } handleClick(e) { this.setState({ difficulty: e.target.id, diffSelected: true }); } handleMouseEnter(e) { const canvasName = e.target.id; SetCanvasText('orange', canvasName, '40px', 10, 45, canvasName); } handleMouseLeave(e) { const canvasName = e.target.id; SetCanvasText('aqua', canvasName, '40px', 10, 45, canvasName); } render() { const easyStyle = { //border: '2px solid black', margin: 'auto auto', position: 'absolute', top: '25%', left: '40%' } const medStyle = { //border: '2px solid black', margin: 'auto auto', position: 'absolute', top: '46%', left: '35%' } const hardStyle = { //border: '2px solid black', margin: 'auto auto', position: 'absolute', top: '65%', left: '40%' } return ( <div className="GameDifficulty"> {!this.state.diffSelected && <div> <Canvas id={'Easy'} width={175} height={50} onClick={this.handleClick.bind(this)} onMouseEnter={this.handleMouseEnter.bind(this)} onMouseLeave={this.handleMouseLeave.bind(this)} canvasStyle={easyStyle} /> <Canvas id={'Medium'} width={250} height={50} onClick={this.handleClick.bind(this)} onMouseEnter={this.handleMouseEnter.bind(this)} onMouseLeave={this.handleMouseLeave.bind(this)} canvasStyle={medStyle} /> <Canvas id={'Hard'} width={175} height={50} onClick={this.handleClick.bind(this)} onMouseEnter={this.handleMouseEnter.bind(this)} onMouseLeave={this.handleMouseLeave.bind(this)} canvasStyle={hardStyle} /> </div> } {this.props.game === 'Pong' && this.state.diffSelected && <GameHome instructions={PongInstructions} game={this.props.game} difficulty={this.state.difficulty} /> } {this.props.game === 'Snake' && this.state.diffSelected && <GameHome instructions={SnakeInstructions} game={this.props.game} difficulty={this.state.difficulty} /> } </div> ); } } export default GameDifficulty;
frontend/containers/tracks/TrackRowContainer.js
matiasgarcia/tubify
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { downloadTrack } from '../../actions/tracks'; import TrackRow from '../../components/tracks/TrackRow'; function mapStateToProps(state, ownProps) { return { track: state.tracks[ownProps.id], trackSearch: state.trackSearch[ownProps.id], trackDownload: state.trackDownloads[ownProps.id] }; } function mapDispatchToProps(dispatch, ownProps) { return { onTrackDownloadClick: bindActionCreators(downloadTrack, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(TrackRow);
src/.templates/js/component.js
Astrocoders/astroman
const { stripIndent } = require('common-tags') const chalk = require('chalk') const fs = require('fs') module.exports.args = { name: 'Component name' } module.exports.where = (name) => { if (!fs.existsSync('components')){ fs.mkdirSync('components') return `components/${name}.js` } else { return `components/${name}.js` } } module.exports.postBuild = (name) => console.log('✅ ', chalk.green(`Component ${name} successfully created`)) module.exports.gen = (name) => stripIndent` import React from 'react' import PropTypes from 'prop-types' const ${name} = ({prop}) => ( <div data-testid="${name}Wrapper">{prop}</div> ) ${name}.defaultProps = { prop: '', } ${name}.propTypes = { prop: PropTypes.string.isRequired, } export default ${name} `
www/js/jquery-1.11.3.min.js
bigeyessolution/FestivalEdesioApp
/*! jQuery v1.11.3 | (c) 2005, 2015 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.3",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)+1>=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="length"in a&&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"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),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=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),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")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=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)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){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 ga(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||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(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 H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(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 ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(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 pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.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.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);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 p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' 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(".#.+[+~]")}),ja(function(a){var b=g.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=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),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===g||a.ownerDocument===v&&t(v,a)?-1:b===g||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,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(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?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.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 ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.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},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.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=ga.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=ga.selectors={cacheLength:50,createPseudo:ia,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(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===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]||ga.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]&&ga.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(ca,da).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=ga.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(Q," ")+" ").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()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(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:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(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:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).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:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(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]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.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?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(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 ta(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 ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(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 wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(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=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(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=[sa(ta(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 wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(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]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.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(ca,da),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(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(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}),ga}(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 aa(){return!0}function ba(){return!1}function ca(){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!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&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?aa:ba):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:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,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=ba;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=ba),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 da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={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>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(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,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(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 xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(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 Ba(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?(xa(b).text=a.text,ya(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)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(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=da(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(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.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(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.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=wa(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=wa(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(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(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(ua(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(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(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(ua(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&&na.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(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.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(qa,"")));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 Ca,Da={};function Ea(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 Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[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 Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.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&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.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 La(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.removeChild(i)),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 Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(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",Fa(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 Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(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 Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(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]=Ua(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=Qa.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]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[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?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(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 Na.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(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[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}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),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=Ia(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 Va(this,!0)},hide:function(){return Va(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 Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,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=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.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):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.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}}},Za.propHooks.scrollTop=Za.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=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.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 fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(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 hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(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")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(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],ab.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?Fa(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=hb(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 jb(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 kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),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:$a||fb(),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(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,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(kb,{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],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.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=kb(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&&cb.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(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("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($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=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(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=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 lb=/\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(lb,""):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 mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=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)?nb:mb)),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)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?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}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&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=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={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}},ob.id=ob.name=ob.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:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.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 sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?: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):sb.test(a.nodeName)||tb.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 ub=/[\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(ub," "):" ")){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(ub," "):"")){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(ub," ").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 vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\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(xb,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 yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(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 Mb(a,b,c,d){var e={},f=a===Ib;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 Nb(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 Ob(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 Pb(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:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,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?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),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=Cb.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||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),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]?", "+Jb+"; 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=Mb(Ib,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=Ob(k,v,c)),u=Pb(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._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 Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(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)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},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")&&Ub.test(this.nodeName)&&!Tb.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(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;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 Xb[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=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){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 _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.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(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.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,_b.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 bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.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.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(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=dc(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||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),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=dc(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]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.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 ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
www/pages/components/home/ValueProps.js
danielmahon/keystone
import React, { Component } from 'react'; import Container from '../../../components/Container'; import { Col, Row } from '../../../components/Grid'; import { compose } from 'glamor'; import theme from '../../../theme'; import { EntypoLeaf, EntypoShuffle, EntypoImages, EntypoLightBulb, EntypoPencil, EntypoDocument, EntypoUsers, EntypoPaperPlane, } from 'react-entypo'; const ValueProp = ({ icon, text, title, text2, marginTop }) => { return ( <div {...compose(styles.base, { marginTop })}> <i {...compose(styles.icon_inner)}>{icon}</i> <div {...compose(styles.content)}> <h3 {...compose(styles.title)}>{title}</h3> <p {...compose(styles.text)}>{text}</p> {text2 ? <p {...compose(styles.text)}>{text2}</p> : null} </div> </div> ); }; ValueProp.defaultProps = { marginTop: '4em', }; export default class ValueProps extends Component { render () { return ( <Container style={styles.container}> <div className={compose(styles.preamble)}> <h2 className={compose(styles.heading)}>Get a head-start on the features you need</h2> <p className={compose(styles.subheading)}>KeystoneJS is the easiest way to build database-driven websites, applications and APIs in Node.js.</p> </div> <Row medium="1" large="1/2"> <Col> <ValueProp title="Express.js and MongoDB" text="Keystone will configure express - the de facto web server for node.js - for you and connect to your MongoDB database using Mongoose, the leading ODM package." icon={<EntypoLeaf style={styles.icon} />} /> </Col> <Col> <ValueProp title="Dynamic Routes" text="Keystone starts with best practices for setting up your MV* application, and makes it easy to manage your templates, views and routes." icon={<EntypoShuffle style={styles.icon} />} /> </Col> </Row> <Row medium="1" large="1/2"> <Col> <ValueProp title="Database Fields" text="IDs, Strings, Booleans, Dates and Numbers are the building blocks of your database. Keystone builds on these with useful, real-world field types like name, email, password, address, image and relationship fields (and more)" icon={<EntypoImages style={styles.icon} />} /> </Col> <Col> <ValueProp title="Auto-generated Admin UI" text="Whether you use it while you're building out your application, or in production as a database content management system, Keystone's Admin UI will save you time and make managing your data easy." icon={<EntypoLightBulb style={styles.icon} />} /> </Col> </Row> <Row medium="1" large="1/2"> <Col> <ValueProp title="Simpler Code" text="Sometimes, async code can get complicated to do simple things. Keystone helps keep simple things - like loading data before displaying it in a view - simple." icon={<EntypoPencil style={styles.icon} />} /> </Col> <Col> <ValueProp title="Form Processing" text="Want to validate a form, upload an image, and update your database with a single line? Keystone can do that, based on the data models you've already defined." icon={<EntypoDocument style={styles.icon} />} /> </Col> </Row> <Row medium="1" large="1/2"> <Col> <ValueProp title="Session Management" text="Keystone comes ready out of the box with session management and authentication features, including automatic encryption for password fields." icon={<EntypoUsers style={styles.icon} />} /> </Col> <Col> <ValueProp title="Email Sending" text="Keystone makes it easy to set up, preview and send template-based emails for your application. It also integrates with Mandrill (Mailchimp's excellent transaction email sending service)" icon={<EntypoPaperPlane style={styles.icon} />} /> </Col> </Row> </Container> ); } }; const styles = { container: { borderBottom: `1px solid ${theme.color.gray10}` }, icon: { width: '30px', height: '30px', fill: theme.color.blue, }, preamble: { textAlign: 'center', }, heading: { fontSize: '2.6em', }, subheading: { fontSize: '1.8em', lineHeight: '1.2em', color: theme.color.gray40, }, base: { display: 'flex', }, content: { flexGrow: 1, }, icon_inner: { marginRight: '1em', }, title: { color: 'inherit', fontWeight: '400', marginTop: '0.2em', }, text: { paddingTop: '1em', fontWeight: '300', }, };
examples/react-backbone/js/todos.js
arthurvr/todomvc
/*global Backbone */ var app = app || {}; (function () { 'use strict'; // Todo Collection // --------------- // The collection of todos is backed by *localStorage* instead of a remote // server. var Todos = Backbone.Collection.extend({ // Reference to this collection's model. model: app.Todo, // Save all of the todo items under the `"todos"` namespace. localStorage: new Backbone.LocalStorage('todos-react-backbone'), // Filter down the list of all todo items that are finished. completed: function () { return this.where({completed: true}); }, // Filter down the list to only todo items that are still not finished. remaining: function () { return this.where({completed: false}); }, // We keep the Todos in sequential order, despite being saved by unordered // GUID in the database. This generates the next order number for new items. nextOrder: function () { return this.length ? this.last().get('order') + 1 : 1; }, // Todos are sorted by their original insertion order. comparator: 'order' }); // Create our global collection of **Todos**. app.todos = new Todos(); })();
universal_api_project_template/server.js
Mikeysax/mikey
// Server Dependencies import Express from 'express'; import cluster from 'express-cluster'; import fs from 'fs'; import path from 'path'; import React from 'react'; import { renderToString, renderToStaticNodeStream } from 'react-dom/server'; import compression from 'compression'; import serialize from 'serialize-javascript'; import cors from 'cors'; // Database Dependencies import bodyParser from 'body-parser'; import cookieParser from 'cookie-parser'; import methodOverride from 'method-override'; // For Server Fetch. require('isomorphic-fetch'); // Router Dependencies import { RouterContext, match } from 'react-router'; import { Provider } from 'react-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-connect'; import routes from './shared/routes'; // Store Dependencies import configureStore from './client/store'; // Initial HTML Page import InitialPage from './initialPage'; let app; cluster(worker => { // Initialize Express App app = new Express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cookieParser()); app.use(methodOverride()); app.use(compression()); app.use(Express.static(__dirname + '/dist')); const corsSettings = { origin: __DEVELOPMENT__ ? 'http://localhost:8080' : 'http://productionURL.com', methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'], credentials: true, preflightContinue: false }; app.use(cors(corsSettings)); app.use('/api', require('./api/controllers')); // See env.js to add secrets. app.secret = process.env.APP_SECRET; // Server Side Rendering app.use((req, res) => { if (__DEVELOPMENT__) webpackIsomorphicTools.refresh(); const initialState = {}; const store = configureStore(initialState); // Initial HTML const initialPage = (html, store, assets) => '<!doctype html>\n' + renderToString( <InitialPage assets={assets} component={html} store={store} /> ); // Error Rendering const renderError = error => { const pad = '&#32;&#32;&#32;&#32;'; const errorTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre>${pad}${error.stack.replace( /\n/g, `<br>${pad}` )}</pre>` : ''; res.send( initialPage( `<h1>Server Error:</h1> ${errorTrace}`, {}, webpackIsomorphicTools.assets() ) ); }; // Rendering match( { routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error) { console.error('Error: ' + error); return res.status(500).end(renderError(error)); } else if (redirectLocation) { res.redirect( 302, redirectLocation.pathname + redirectLocation.search ); } else if (renderProps) { loadOnServer({ ...renderProps, store }) .then(() => Promise.resolve( renderToString( <Provider store={store}> <ReduxAsyncConnect {...renderProps} /> </Provider> ) ) ) .then(components => { const htmlStream = renderToNodeStream( <InitialPage assets={webpackIsomorphicTools.assets()} component={components} store={store} /> ); res.write('<!DOCTYPE html>\n'); htmlStream.pipe(res, { end: false }); htmlStream.on('end', () => res.end()); }) .catch(err => console.error('Caught Error in Server Render: ', err) ); } else { res.status(404).send('Not Found'); } } ); }); const PORT = process.env.PORT || 3000; app.listen(PORT, error => { if (error) return console.error('Server Express Error:', error); console.log(`Server ${worker.id} listening on: ${PORT}`); }); }); export default app;
web/test/components/DataStoreForm_test.js
boundlessgeo/spatialconnect-server
/* global describe, it, before, after */ import React from 'react'; import expect from 'expect'; import { shallow } from 'enzyme'; import { DataStoreForm, validate } from '../../components/DataStoreForm'; import mockDataStores from '../data/mockDataStores'; describe('DataStoreForm', () => { function setup(props = {}) { const defaultProps = { store: mockDataStores[0], onSubmit: () => {}, cancel: () => {}, }; const newProps = Object.assign(defaultProps, props); const component = shallow(<DataStoreForm {...newProps} />); return { component }; } it('should render correctly', () => { const { component } = setup(); expect(component.type()).toBe('div'); expect(component.find('input').length).toBe(3); expect(component.find('select').length).toBe(1); }); it('should validate', () => { expect(validate(mockDataStores[0])).toEqual({}); }); it('should return errors on validate', () => { expect(validate({})).toEqual({ name: 'Required', store_type: 'Required', version: 'Required', }); }); });