path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
stories/github-issues.stories.js
joshwcomeau/react-flip-move
/* eslint-disable no-plusplus */ import React, { Component } from 'react'; import { storiesOf } from '@storybook/react'; import range from 'lodash/range'; import FlipMoveWrapper from './helpers/FlipMoveWrapper'; import FlipMove from '../src/FlipMove'; const sampleItems = [ { name: 'Potent Potables' }, { name: 'The Pen is Mightier' }, { name: 'Famous Horsemen' }, { name: 'A Petit Déjeuner' }, ]; storiesOf('Github Issues', module) .add('#31', () => <Controls duration={400} />) .add('#120', () => { class Example extends React.Component { counter = 0; constructor(props) { super(props); this.state = { items: [], }; } onRemoveItem = () => { const { items } = this.state; this.setState({ items: sampleItems.slice(0, items.length - 1), }); }; onAddItem = () => { this.setState({ items: this.state.items.concat([`item${++this.counter}`]), }); }; handleAddItems = calls => { const items = []; for (let i = 0; i < calls; i++) { items.push(`item${++this.counter}`); } this.setState(() => ({ items, })); }; onAddItems = () => { setTimeout(this.handleAddItems(50), 0); setTimeout(this.handleAddItems(50), 20); }; render() { const { items } = this.state; return ( <div> <section> <button onClick={this.onRemoveItem}>Remove item</button> <button onClick={this.onAddItem}>Add item</button> <button onClick={() => this.onAddItems()}>Add many items</button> </section> <FlipMove typeName={'ul'} duration="200" enterAnimation={{ from: { transform: 'translateX(-10%)', opacity: 0.1, }, to: { transform: 'translateX(0)', opacity: 1, }, }} leaveAnimation={{ from: { transform: 'translateX(0)', opacity: 1, }, to: { transform: 'translateX(-10%)', opacity: 0.0, }, }} > {items.map(item => ( <li key={item} id={item}> {item} </li> ))} </FlipMove> </div> ); } } return ( <div> <legend> Spam &quot;add many items&quot; button, then inspect first element. it will be overlayed by a zombie element that wasnt correctle removed from the DOM </legend> <Example /> </div> ); }) .add('#141', () => ( <FlipMoveWrapper items={range(100).map(i => ({ id: `${i}`, text: `Header ${i}` }))} flipMoveContainerStyles={{ position: 'relative', height: '500px', overflow: 'scroll', }} listItemStyles={{ position: 'sticky', top: 0, height: 20, backgroundColor: 'black', color: 'white', }} /> )); // eslint-disable-next-line react/no-multi-comp class Controls extends Component { constructor() { super(); this.state = { items: [...sampleItems] }; } buttonClickHandler = () => { const newItems = this.state.items.slice(); newItems.splice(1, 1); this.setState({ items: newItems }); }; listItemClickHandler = clickedItem => { this.setState({ items: this.state.items.filter(item => item !== clickedItem), }); }; restore = () => { this.setState({ items: sampleItems }); }; renderItems() { const answerWrapperStyle = { backgroundColor: '#FFF', borderRadius: '20px', padding: '1em 2em', marginBottom: '1em', minWidth: 400, }; const answerStyle = { fontSize: '16px', }; return this.state.items.map(item => ( // eslint-disable-next-line jsx-a11y/no-static-element-interactions <div style={answerWrapperStyle} key={item.name} onClick={() => this.listItemClickHandler(item)} > <div style={answerStyle}>{item.name}</div> </div> )); } render() { return ( <div style={{ display: 'flex', alignItems: 'center', minHeight: '600px', background: '#DDD', }} > <div style={{ marginBottom: '50px' }}> <button onClick={this.buttonClickHandler}>Remove</button> <button onClick={this.restore}>add</button> </div> <FlipMove enterAnimation="elevator" leaveAnimation="elevator"> {this.renderItems()} </FlipMove> </div> ); } }
src/helpers/connectData.js
Boelensman1/championpick2
import React, { Component } from 'react'; import hoistStatics from 'hoist-non-react-statics'; /* Note: When this decorator is used, it MUST be the first (outermost) decorator. Otherwise, we cannot find and call the fetchData and fetchDataDeffered methods. */ export default function connectData(fetchData, fetchDataDeferred) { return function wrapWithFetchData(WrappedComponent) { class ConnectData extends Component { render() { return <WrappedComponent {...this.props} />; } } ConnectData.fetchData = fetchData; ConnectData.fetchDataDeferred = fetchDataDeferred; return hoistStatics(ConnectData, WrappedComponent); }; }
src/BreadcrumbItem.js
mmartche/boilerplate-shop
import classNames from 'classnames'; import React from 'react'; import warning from 'warning'; import SafeAnchor from './SafeAnchor'; const BreadcrumbItem = React.createClass({ propTypes: { /** * If set to true, renders `span` instead of `a` */ active: React.PropTypes.bool, /** * HTML id for the wrapper `li` element */ id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), /** * HTML id for the inner `a` element */ linkId: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), /** * `href` attribute for the inner `a` element */ href: React.PropTypes.string, /** * `title` attribute for the inner `a` element */ title: React.PropTypes.node, /** * `target` attribute for the inner `a` element */ target: React.PropTypes.string }, getDefaultProps() { return { active: false, }; }, render() { const { active, className, id, linkId, children, href, title, target, ...props } = this.props; warning(!(href && active), '[react-bootstrap] `href` and `active` properties cannot be set at the same time'); const linkProps = { href, title, target, id: linkId }; return ( <li id={id} className={classNames(className, { active })}> { active ? <span {...props}> { children } </span> : <SafeAnchor {...props} {...linkProps}> { children } </SafeAnchor> } </li> ); } }); export default BreadcrumbItem;
force_dir/node_modules/react-bootstrap/es/Accordion.js
wolfiex/VisACC
import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PanelGroup from './PanelGroup'; var Accordion = function (_React$Component) { _inherits(Accordion, _React$Component); function Accordion() { _classCallCheck(this, Accordion); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Accordion.prototype.render = function render() { return React.createElement( PanelGroup, _extends({}, this.props, { accordion: true }), this.props.children ); }; return Accordion; }(React.Component); export default Accordion;
packages/shared/forks/object-assign.umd.js
flarnie/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; const ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; export default ReactInternals.assign;
frontend/src/Components/Error/ErrorBoundary.js
lidarr/Lidarr
import * as sentry from '@sentry/browser'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; class ErrorBoundary extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { error: null, info: null }; } componentDidCatch(error, info) { this.setState({ error, info }); sentry.captureException(error); } // // Render render() { const { children, errorComponent: ErrorComponent, ...otherProps } = this.props; const { error, info } = this.state; if (error) { return ( <ErrorComponent error={error} info={info} {...otherProps} /> ); } return children; } } ErrorBoundary.propTypes = { children: PropTypes.node.isRequired, errorComponent: PropTypes.elementType.isRequired }; export default ErrorBoundary;
client/src/index.js
yegor-sytnyk/contoso-express
import '../styles/app.css'; import React from 'react'; import {render} from 'react-dom'; import configureStore from './store/configureStore'; import {Provider} from 'react-redux'; import {Router} from 'react-router'; import {browserHistory} from 'react-router'; import routes from './routes'; import {loadDepartments} from './actions/departmentActions'; import {loadInstructors} from './actions/instructorActions'; const store = configureStore(); //TODO move into componentWillMount (as for about page) store.dispatch(loadDepartments()); store.dispatch(loadInstructors()); render( <Provider store={store}> <Router history={browserHistory} routes={routes}/> </Provider>, document.getElementById('root') );
test/Parallax.spec.js
react-materialize/react-materialize
import React from 'react'; // import { shallow, mount } from 'enzyme'; import Parallax from '../src/Parallax'; import mocker from './helper/new-mocker'; describe.skip('<Parallax />', () => { test('should render a Parallax', () => { expect(shallow(<Parallax />)).toMatchSnapshot(); }); describe('initialises', () => { const parallaxInitMock = jest.fn(); const parallaxInstanceDestroyMock = jest.fn(); const parallaxMock = { init: (el, options) => { parallaxInitMock(options); return { destroy: parallaxInstanceDestroyMock }; } }; const restore = mocker('Parallax', parallaxMock); beforeEach(() => { parallaxInitMock.mockClear(); parallaxInstanceDestroyMock.mockClear(); }); afterAll(() => { restore(); }); test('calls Parallax', () => { mount(<Parallax />); expect(parallaxInitMock).toHaveBeenCalledTimes(1); }); test('should have default options if none are given', () => { mount(<Parallax />); expect(parallaxInitMock).toHaveBeenCalledWith({ responsiveThreshold: 0 }); }); test('should call Parallax with the given options', () => { const options = { responsiveThreshold: 200 }; mount(<Parallax options={options} />); expect(parallaxInitMock).toHaveBeenCalledWith(options); }); test('can render children element', () => { const wrapper = shallow( <Parallax imageSrc="image.jpg"> <h1>Test</h1> </Parallax> ); expect(wrapper).toMatchSnapshot(); }); test('can render a picture element', () => { const pictureTag = ( <picture> <source srcSet="#" type="image/webp" /> <source srcSet="#" type="image/jpg" /> <img src="#" alt="" /> </picture> ); expect(shallow(<Parallax image={pictureTag} />)).toMatchSnapshot(); }); }); });
src/components/DataEntry/Figure/components/Figure.js
Aus0049/react-component
/** * Created by Aus on 2017/7/6. */ import React from 'react' import classNames from 'classnames' import '../style/figure.scss' // Figure就是每个图片的容器 以及实现预览的容器 class Figure extends React.Component { constructor(props) { super(props); this.state = {}; this.handlePreview = this.handlePreview.bind(this); this.handleDelete = this.handleDelete.bind(this); this.handleReUpload = this.handleReUpload.bind(this); this.handleClosePreview = this.handleClosePreview.bind(this); } componentWillUnmount () { const {id} = this.props; const mask = document.getElementById('preview-' + id); if(mask) mask.remove(); } handlePreview () { const {prefixCls, id, imgUrl, dataUrl, canPreview} = this.props; const src = imgUrl ? imgUrl : dataUrl; // 打开预览 if(!canPreview) return; // 动态插入dom const img = document.createElement('img'); img.src = src; img.onclick = this.handleClosePreview; const mask = document.createElement('div'); mask.id = 'preview-' + id; mask.className = `${prefixCls}-preview-container`; mask.onclick = this.handleClosePreview; mask.appendChild(img); document.body.appendChild(mask); } handleDelete (e) { const {id, onDelete} = this.props; e.stopPropagation(); document.getElementById(id).className += ' deleted'; const timer = setTimeout(() => { clearTimeout(timer); onDelete(id); }, 300); } handleReUpload () { const {id, onError} = this.props; onError(id); } handleClosePreview (e) { const {id} = this.props; document.getElementById('preview-' + id).remove(); e.stopPropagation(); } getPreviewBoxDOM () { const {prefixCls, id, status, imgUrl, dataUrl, canDelete} = this.props; const src = imgUrl ? imgUrl : dataUrl; switch (status) { case 1: { // 上传中 return ( <div id={id} className={`${prefixCls}-preview-box loading`} onClick={this.handlePreview} > <div className="img-box"><img src={src}/></div> <div className="progress-text" id={`text-${id}`} /> {canDelete ? <div className="close" onClick={this.handleDelete}><span className="fa fa-times" /></div> : null} </div> ); } case 2: { // 上传成功 return ( <div id={id} className={`${prefixCls}-preview-box loaded`} onClick={this.handlePreview} > <div className="img-box"><img src={src}/></div> <div className="progress-text" id={`text-${id}`} /> {canDelete ? <div className="close" onClick={this.handleDelete}><span className="fa fa-times" /></div> : null} </div> ); } case 3: { // 上传失败 return ( <div id={id} className={`${prefixCls}-preview-box error`} onClick={this.handleReUpload} > <div className="img-box"><img src={src}/></div> <div className="progress-text" id={`text-${id}`} ><span className="fa fa-refresh" /></div> {canDelete ? <div className="close" onClick={this.handleDelete}><span className="fa fa-times" /></div> : null} </div> ); } default: break; } } render() { const {prefixCls} = this.props; const previewBoxDOM = this.getPreviewBoxDOM(); return ( <div className={classNames([prefixCls, `${prefixCls}-with-preview`])}> {previewBoxDOM} </div> ); } } function empty() {} Figure.propTypes = { id: React.PropTypes.string.isRequired, // 图片的id status: React.PropTypes.oneOf([1,2,3]).isRequired, // 此图片上传的状态 1:上传中,2:上传成功,3:上传失败 prefixCls: React.PropTypes.string, // class前缀 canPreview: React.PropTypes.bool, // 是否使用预览功能 canDelete: React.PropTypes.bool, // 是否可以删除 dataUrl: React.PropTypes.string, // 图片的base64编码 imgUrl: React.PropTypes.string, // 图片的路径 onDelete: React.PropTypes.func, // 删除的回调 onError: React.PropTypes.func, // 上传失败的回调 }; Figure.defaultProps = { prefixCls: 'zby-figure', canPreview: true, canDelete: true, dataUrl: '', imgUrl: '', onDelete: empty, onError: empty }; export default Figure;
src/svg-icons/file/folder.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileFolder = (props) => ( <SvgIcon {...props}> <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/> </SvgIcon> ); FileFolder = pure(FileFolder); FileFolder.displayName = 'FileFolder'; export default FileFolder;
src/svg-icons/action/feedback.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFeedback = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 12h-2v-2h2v2zm0-4h-2V6h2v4z"/> </SvgIcon> ); ActionFeedback = pure(ActionFeedback); ActionFeedback.displayName = 'ActionFeedback'; ActionFeedback.muiName = 'SvgIcon'; export default ActionFeedback;
src/pages/uses.js
Oluwasetemi/Oluwasetemi.github.io
import Bio from 'components/Bio' import SEO from 'components/seo' import React from 'react' import styled from 'styled-components' const AboutPageStyles = styled.div` color: var(--color); ` function UsesPage() { return ( <AboutPageStyles> <SEO title="Uses" location /> <Bio footer /> <h2>Uses WIP</h2> <p>Please check back later</p> </AboutPageStyles> ) } export default UsesPage
admin/client/App/components/Navigation/Mobile/ListItem.js
matthewstyers/keystone
/** * A list item of the mobile navigation */ import React from 'react'; import { Link } from 'react-router'; const MobileListItem = React.createClass({ displayName: 'MobileListItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, href: React.PropTypes.string.isRequired, onClick: React.PropTypes.func, }, render () { return ( <Link className={this.props.className} to={this.props.href} onClick={this.props.onClick} tabIndex="-1" > {this.props.children} </Link> ); }, }); module.exports = MobileListItem;
submissions/jas-chen/src/component/dashboard.js
sensduo/flux-challenge
import React from 'react'; import { dom } from 'react-reactive-class'; import { Observable, Subject } from 'rx'; import { TOTAL_SLOT_COUNT } from '../constants.js'; import { allEmpty, isMatchCurrentPlanet } from '../utils.js'; const { h1: H1, li: Li, button: Button } = dom; function slots(state$) { const elements = []; for ( let i = 0 ; i < TOTAL_SLOT_COUNT ; i += 1) { const redStyle = { color: 'red' }; const emptySlot = [<h3></h3>, <h6></h6>]; // only re-render when slot changes const slot$ = state$ .map(state => state.slots[i]) .distinctUntilChanged(); const obiWanPlanetId$ = state$ .map(state => state.obiWanLocation.id); const style$ = Observable.combineLatest( slot$, obiWanPlanetId$, (slot, obiWanPlanetId) => { return (slot && obiWanPlanetId === slot.homeworld.id) ? redStyle : null; } ); const content$ = slot$.map((slot) => { if (!slot) { return emptySlot; } return [ <h3>{slot.name}</h3>, <h6>{'Homeworld: ' + slot.homeworld.name}</h6> ]; }); elements.push( <Li key={'slot' + i} className="css-slot" style={style$}>{content$}</Li> ); } return elements; } function upButton(state$) { const normalClassName = "css-button-up"; const disabledClassName = "css-button-up css-button-disabled"; const disabled$ = state$.map((state) => { const { slots } = state; return ( allEmpty(slots) || isMatchCurrentPlanet(state) || (slots[slots.length - 1] && !slots[slots.length - 2]) || (slots[slots.length - 2] && !slots[slots.length - 3]) ); }) .distinctUntilChanged(); const className$ = disabled$.map((disabled) => { return disabled ? disabledClassName : normalClassName; }); const event$ = new Subject(); const element = ( <Button className={className$} onClick={event$.onNext.bind(event$)} disabled={disabled$}></Button> ); return { element, event$ }; } function downButton(state$) { const normalClassName = "css-button-down"; const disabledClassName = "css-button-down css-button-disabled"; const disabled$ = state$.map((state) => { const { slots } = state; return ( allEmpty(slots) || isMatchCurrentPlanet(state) || (slots[0] && !slots[1]) || (slots[1] && !slots[2]) ); }) .distinctUntilChanged(); const className$ = disabled$.map((disabled) => { return disabled ? disabledClassName : normalClassName; }); const event$ = new Subject(); const element = ( <Button className={className$} onClick={event$.onNext.bind(event$)} disabled={disabled$}></Button> ); return { element, event$ }; } function dashboard(state$) { const planetMonitorText$ = state$.map(state => { return state.obiWanLocation.name ? 'Obi-Wan currently on ' + state.obiWanLocation.name : ''; }); const slots$ = slots(state$); const { element: UpButton, event$: upClick$ } = upButton(state$); const { element: DownButton, event$: downClick$ } = downButton(state$); const element = ( <div className="css-root"> <H1 className="css-planet-monitor">{planetMonitorText$}</H1> <section className="css-scrollable-list"> <ul className="css-slots"> { slots$ } </ul> <div className="css-scroll-buttons"> { UpButton } { DownButton } </div> </section> </div> ); return { element, events: { upClick$, downClick$ } } } export default dashboard;
src/components/Queue/__tests__/Queue-test.js
elurye/ReactJestBoiler
jest.dontMock('../Queue'); describe('Queue', function() { var React = require('react/addons'); var TestUtils = React.addons.TestUtils; var ToDoApp = require('../Queue'); var Component = TestUtils.renderIntoDocument(React.createElement(ToDoApp)); var state = { queue: [ { value: 'Be awesome', done: false }, { value: 'Learn React', done: true }, { value: 'Use JSX in my CodePens', done: true } ] }; it('sets class name and state info', function() { var element = TestUtils.findRenderedDOMComponentWithClass(Component, 'ToDoApp').getDOMNode(); expect(element).toBeDefined(); expect(element.className).toBe('ToDoApp'); expect(Component.state).toEqual(state); }); it('adds item to list when called', function() { Component.state.inputValue = "Test Input"; var todoItem = { value: Component.state.inputValue, done: false }; state.todos.push(todoItem); //Call the actual method to test Component.addTodo(); expect(Component.state.todos).toEqual(state.todos); }); it('marks toDoItem done', function() { expect(Component.state.todos[0].done).toBe(false); Component.markTodoDone(0); expect(Component.state.todos[0].done).toBe(true); }); });
src/Input/InputLabel.js
dsslimshaddy/material-ui
// @flow import React from 'react'; import type { Element } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import { FormLabel } from '../Form'; export const styles = (theme: Object) => ({ root: { transformOrigin: 'top left', }, formControl: { position: 'absolute', left: 0, top: 0, // slight alteration to spec spacing to match visual spec result transform: `translate(0, ${theme.spacing.unit * 3 - 1}px) scale(1)`, }, shrink: { transform: 'translate(0, 1.5px) scale(0.75)', transformOrigin: 'top left', }, animated: { transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut, }), }, disabled: { color: theme.palette.input.disabled, }, }); type DefaultProps = { classes: Object, disabled: boolean, disableAnimation: boolean, }; export type Props = { /** * The contents of the `InputLabel`. */ children?: Element<*>, /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * If `true`, the transition animation is disabled. */ disableAnimation?: boolean, /** * If `true`, apply disabled class. */ disabled?: boolean, /** * If `true`, the label will be displayed in an error state. */ error?: boolean, /** * If `true`, the input of this label is focused. */ focused?: boolean, /** * if `true`, the label will indicate that the input is required. */ required?: boolean, /** * If `true`, the label is shrunk. */ shrink?: boolean, }; type AllProps = DefaultProps & Props; function InputLabel(props: AllProps, context: { muiFormControl: Object }) { const { disabled, disableAnimation, children, classes, className: classNameProp, shrink: shrinkProp, ...other } = props; const { muiFormControl } = context; let shrink = shrinkProp; if (typeof shrink === 'undefined' && muiFormControl) { shrink = muiFormControl.dirty || muiFormControl.focused; } const className = classNames( classes.root, { [classes.formControl]: muiFormControl, [classes.animated]: !disableAnimation, [classes.shrink]: shrink, [classes.disabled]: disabled, }, classNameProp, ); return ( <FormLabel className={className} {...other}> {children} </FormLabel> ); } InputLabel.defaultProps = { disabled: false, disableAnimation: false, }; InputLabel.contextTypes = { muiFormControl: PropTypes.object, }; export default withStyles(styles, { name: 'MuiInputLabel' })(InputLabel);
examples/basic/components/Bar.js
reactjs/react-router-redux
import React from 'react' export default function Bar() { return <div>And I am Bar!</div> }
src/components/page/index.js
octoblu/app-store
import React, { PropTypes } from 'react'; import classNames from 'classnames'; import './index.css'; import PageHeader from './header' import PageTitle from './title' import PageActions from './actions' const Page = ({ children, className }) => { const componentClass = classNames('Page', className); return <div className={componentClass}>{children}</div> }; export {Page, PageHeader, PageTitle, PageActions}
test/fixtures/webpack-message-formatting/src/AppLintError.js
GreenGremlin/create-react-app
import React, { Component } from 'react'; function foo() { const a = b; } class App extends Component { render() { return <div />; } } export default App;
spec/javascripts/jsx/external_apps/components/ConfigureExternalToolButtonSpec.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import $ from 'jquery' import React from 'react' import {mount} from 'enzyme' import ConfigureExternalToolButton from 'jsx/external_apps/components/ConfigureExternalToolButton' let tool let event let el QUnit.module('ConfigureExternalToolButton screenreader functionality', { setup() { ENV.LTI_LAUNCH_FRAME_ALLOWANCES = ['midi', 'media'] tool = { name: 'test tool', tool_configuration: { url: 'http://example.com/launch' } } event = { preventDefault() {} } }, teardown() { $('.ReactModalPortal').remove() ENV.LTI_LAUNCH_FRAME_ALLOWANCES = undefined } }) test('uses the tool configuration "url" when present', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} modalIsOpen />) ok( wrapper .instance() .getLaunchUrl({url: 'https://my.tool.com', target_link_uri: 'https://advantage.tool.com'}) .includes('url=https%3A%2F%2Fmy.tool.com&display=borderless') ) wrapper.unmount() }) test('uses the tool configuration "target_link_uri" when "url" is not present', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} modalIsOpen />) ok( wrapper .instance() .getLaunchUrl({target_link_uri: 'https://advantage.tool.com'}) .includes('url=https%3A%2F%2Fadvantage.tool.com&display=borderless') ) wrapper.unmount() }) test('shows beginning info alert and adds styles to iframe', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} modalIsOpen />) wrapper.instance().handleAlertFocus({target: {className: 'before'}}) equal(wrapper.state().beforeExternalContentAlertClass, '') deepEqual(wrapper.state().iframeStyle, {border: '2px solid #008EE2', width: '300px'}) wrapper.unmount() }) test('shows ending info alert and adds styles to iframe', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} modalIsOpen />) wrapper.instance().handleAlertFocus({target: {className: 'after'}}) equal(wrapper.state().afterExternalContentAlertClass, '') deepEqual(wrapper.state().iframeStyle, {border: '2px solid #008EE2', width: '300px'}) wrapper.unmount() }) test('hides beginning info alert and adds styles to iframe', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} />) wrapper.instance().openModal(event) el = $('.ReactModalPortal') wrapper.instance().handleAlertBlur({target: {className: 'before'}}) equal(wrapper.state().beforeExternalContentAlertClass, 'screenreader-only') deepEqual(wrapper.state().iframeStyle, {border: 'none', width: '100%'}) wrapper.unmount() }) test('hides ending info alert and adds styles to iframe', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} />) wrapper.instance().openModal(event) wrapper.instance().handleAlertBlur({target: {className: 'after'}}) equal(wrapper.state().afterExternalContentAlertClass, 'screenreader-only') deepEqual(wrapper.state().iframeStyle, {border: 'none', width: '100%'}) wrapper.unmount() }) test("doesn't show alerts or add border to iframe by default", () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} />) wrapper.instance().openModal(event) equal(wrapper.state().beforeExternalContentAlertClass, 'screenreader-only') equal(wrapper.state().afterExternalContentAlertClass, 'screenreader-only') deepEqual(wrapper.state().iframeStyle, {}) wrapper.unmount() }) test('sets the iframe allowances', () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} modalIsOpen />) wrapper.instance().handleAlertFocus({target: {className: 'before'}}) equal(wrapper.state().beforeExternalContentAlertClass, '') ok(wrapper.instance().iframe.getAttribute('allow'), ENV.LTI_LAUNCH_FRAME_ALLOWANCES.join('; ')) wrapper.unmount() }) test("sets the 'data-lti-launch' attribute on the iframe", () => { const wrapper = mount(<ConfigureExternalToolButton tool={tool} modalIsOpen />) equal(wrapper.instance().iframe.getAttribute('data-lti-launch'), 'true') wrapper.unmount() })
app/scripts/utils/delayed-show.js
hustbill/network-verification-ui
import React from 'react'; export default class DelayedShow extends React.Component { constructor(props, context) { super(props, context); this.state = { show: false }; } componentWillMount() { if (this.props.show) { this.scheduleShow(); } } componentWillUnmount() { this.cancelShow(); } componentWillReceiveProps(nextProps) { if (nextProps.show === this.props.show) { return; } if (nextProps.show) { this.scheduleShow(); } else { this.cancelShow(); this.setState({ show: false }); } } scheduleShow() { this.showTimeout = setTimeout(() => this.setState({ show: true }), this.props.delay); } cancelShow() { clearTimeout(this.showTimeout); } render() { const { children } = this.props; const { show } = this.state; const style = { opacity: show ? 1 : 0, transition: 'opacity 0.5s ease-in-out', }; return ( <div style={style}> {children} </div> ); } } DelayedShow.defaultProps = { delay: 1000 };
ajax/libs/can.js/4.0.0-pre.5/can.js
holtkamp/cdnjs
/*[global-shim-start]*/ (function(exports, global, doEval) { // jshint ignore:line var origDefine = global.define; var get = function(name) { var parts = name.split("."), cur = global, i; for (i = 0; i < parts.length; i++) { if (!cur) { break; } cur = cur[parts[i]]; } return cur; }; var set = function(name, val) { var parts = name.split("."), cur = global, i, part, next; for (i = 0; i < parts.length - 1; i++) { part = parts[i]; next = cur[part]; if (!next) { next = cur[part] = {}; } cur = next; } part = parts[parts.length - 1]; cur[part] = val; }; var useDefault = function(mod) { if (!mod || !mod.__esModule) return false; var esProps = { __esModule: true, default: true }; for (var p in mod) { if (!esProps[p]) return false; } return true; }; var hasCjsDependencies = function(deps) { return ( deps[0] === "require" && deps[1] === "exports" && deps[2] === "module" ); }; var modules = (global.define && global.define.modules) || (global._define && global._define.modules) || {}; var ourDefine = (global.define = function(moduleName, deps, callback) { var module; if (typeof deps === "function") { callback = deps; deps = []; } var args = [], i; for (i = 0; i < deps.length; i++) { args.push( exports[deps[i]] ? get(exports[deps[i]]) : modules[deps[i]] || get(deps[i]) ); } // CJS has no dependencies but 3 callback arguments if (hasCjsDependencies(deps) || (!deps.length && callback.length)) { module = { exports: {} }; args[0] = function(name) { return exports[name] ? get(exports[name]) : modules[name]; }; args[1] = module.exports; args[2] = module; } else if (!args[0] && deps[0] === "exports") { // Babel uses the exports and module object. module = { exports: {} }; args[0] = module.exports; if (deps[1] === "module") { args[1] = module; } } else if (!args[0] && deps[0] === "module") { args[0] = { id: moduleName }; } global.define = origDefine; var result = callback ? callback.apply(null, args) : undefined; global.define = ourDefine; // Favor CJS module.exports over the return value result = module && module.exports ? module.exports : result; modules[moduleName] = result; // Set global exports var globalExport = exports[moduleName]; if (globalExport && !get(globalExport)) { if (useDefault(result)) { result = result["default"]; } set(globalExport, result); } }); global.define.orig = origDefine; global.define.modules = modules; global.define.amd = true; ourDefine("@loader", [], function() { // shim for @@global-helpers var noop = function() {}; return { get: function() { return { prepareGlobal: noop, retrieveGlobal: noop }; }, global: global, __exec: function(__load) { doEval(__load.source, global); } }; }); })( { jquery: "jQuery", "can-util/namespace": "can", kefir: "Kefir", "validate.js": "validate", react: "React" }, typeof self == "object" && self.Object == Object ? self : window, function(__$source__, __$global__) { // jshint ignore:line eval("(function() { " + __$source__ + " \n }).call(__$global__);"); } ); /*can-namespace@1.0.0#can-namespace*/ define('can-namespace', function (require, exports, module) { module.exports = {}; }); /*can-util@3.10.18#namespace*/ define('can-util/namespace', [ 'require', 'exports', 'module', 'can-namespace' ], function (require, exports, module) { module.exports = require('can-namespace'); }); /*can-assign@1.1.1#can-assign*/ define('can-assign', function (require, exports, module) { module.exports = function (d, s) { for (var prop in s) { d[prop] = s[prop]; } return d; }; }); /*can-util@3.10.18#js/assign/assign*/ define('can-util/js/assign/assign', [ 'require', 'exports', 'module', 'can-assign' ], function (require, exports, module) { 'use strict'; module.exports = require('can-assign'); }); /*can-util@3.10.18#js/is-function/is-function*/ define('can-util/js/is-function/is-function', function (require, exports, module) { 'use strict'; var isFunction = function () { if (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') { return function (value) { return Object.prototype.toString.call(value) === '[object Function]'; }; } return function (value) { return typeof value === 'function'; }; }(); module.exports = isFunction; }); /*can-util@3.10.18#js/is-plain-object/is-plain-object*/ define('can-util/js/is-plain-object/is-plain-object', function (require, exports, module) { 'use strict'; var core_hasOwn = Object.prototype.hasOwnProperty; function isWindow(obj) { return obj !== null && obj == obj.window; } function isPlainObject(obj) { if (!obj || typeof obj !== 'object' || obj.nodeType || isWindow(obj) || obj.constructor && obj.constructor.shortName) { return false; } try { if (obj.constructor && !core_hasOwn.call(obj, 'constructor') && !core_hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } } catch (e) { return false; } var key; for (key in obj) { } return key === undefined || core_hasOwn.call(obj, key); } module.exports = isPlainObject; }); /*can-util@3.10.18#js/deep-assign/deep-assign*/ define('can-util/js/deep-assign/deep-assign', [ 'require', 'exports', 'module', 'can-util/js/is-function/is-function', 'can-util/js/is-plain-object/is-plain-object' ], function (require, exports, module) { 'use strict'; var isFunction = require('can-util/js/is-function/is-function'); var isPlainObject = require('can-util/js/is-plain-object/is-plain-object'); function deepAssign() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length; if (typeof target !== 'object' && !isFunction(target)) { target = {}; } if (length === i) { target = this; --i; } for (; i < length; i++) { if ((options = arguments[i]) != null) { for (name in options) { src = target[name]; copy = options[name]; if (target === copy) { continue; } if (copy && (isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && Array.isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } target[name] = deepAssign(clone, copy); } else if (copy !== undefined) { target[name] = copy; } } } } return target; } module.exports = deepAssign; }); /*can-log@0.1.2#can-log*/ define('can-log', function (require, exports, module) { 'use strict'; exports.warnTimeout = 5000; exports.logLevel = 0; exports.warn = function (out) { var ll = this.logLevel; if (ll < 2) { Array.prototype.unshift.call(arguments, 'WARN:'); if (typeof console !== 'undefined' && console.warn) { this._logger('warn', Array.prototype.slice.call(arguments)); } else if (typeof console !== 'undefined' && console.log) { this._logger('log', Array.prototype.slice.call(arguments)); } else if (window && window.opera && window.opera.postError) { window.opera.postError('CanJS WARNING: ' + out); } } }; exports.log = function (out) { var ll = this.logLevel; if (ll < 1) { if (typeof console !== 'undefined' && console.log) { Array.prototype.unshift.call(arguments, 'INFO:'); this._logger('log', Array.prototype.slice.call(arguments)); } else if (window && window.opera && window.opera.postError) { window.opera.postError('CanJS INFO: ' + out); } } }; exports.error = function (out) { var ll = this.logLevel; if (ll < 1) { if (typeof console !== 'undefined' && console.error) { Array.prototype.unshift.call(arguments, 'ERROR:'); this._logger('error', Array.prototype.slice.call(arguments)); } else if (window && window.opera && window.opera.postError) { window.opera.postError('ERROR: ' + out); } } }; exports._logger = function (type, arr) { try { console[type].apply(console, arr); } catch (e) { console[type](arr); } }; }); /*can-log@0.1.2#dev/dev*/ define('can-log/dev/dev', [ 'require', 'exports', 'module', 'can-log' ], function (require, exports, module) { 'use strict'; var canLog = require('can-log'); module.exports = { warnTimeout: 5000, logLevel: 0, stringify: function (value) { var flagUndefined = function flagUndefined(key, value) { return value === undefined ? '/* void(undefined) */' : value; }; return JSON.stringify(value, flagUndefined, ' ').replace(/"\/\* void\(undefined\) \*\/"/g, 'undefined'); }, warn: function () { canLog.warn.apply(this, arguments); }, log: function () { canLog.log.apply(this, arguments); }, error: function () { canLog.error.apply(this, arguments); }, _logger: canLog._logger }; }); /*can-util@3.10.18#js/dev/dev*/ define('can-util/js/dev/dev', [ 'require', 'exports', 'module', 'can-log/dev/dev' ], function (require, exports, module) { 'use strict'; module.exports = require('can-log/dev/dev'); }); /*can-util@3.10.18#js/is-array-like/is-array-like*/ define('can-util/js/is-array-like/is-array-like', function (require, exports, module) { 'use strict'; function isArrayLike(obj) { var type = typeof obj; if (type === 'string') { return true; } else if (type === 'number') { return false; } var length = obj && type !== 'boolean' && typeof obj !== 'number' && 'length' in obj && obj.length; return typeof obj !== 'function' && (length === 0 || typeof length === 'number' && length > 0 && length - 1 in obj); } module.exports = isArrayLike; }); /*can-symbol@1.4.2#can-symbol*/ define('can-symbol', [ 'require', 'exports', 'module', 'can-namespace' ], function (require, exports, module) { (function (global, require, exports, module) { var namespace = require('can-namespace'); var CanSymbol; if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { CanSymbol = Symbol; } else { var symbolNum = 0; CanSymbol = function CanSymbolPolyfill(description) { var symbolValue = '@@symbol' + symbolNum++ + description; var symbol = {}; Object.defineProperties(symbol, { toString: { value: function () { return symbolValue; } } }); return symbol; }; var descriptionToSymbol = {}; var symbolToDescription = {}; CanSymbol.for = function (description) { var symbol = descriptionToSymbol[description]; if (!symbol) { symbol = descriptionToSymbol[description] = CanSymbol(description); symbolToDescription[symbol] = description; } return symbol; }; CanSymbol.keyFor = function (symbol) { return symbolToDescription[symbol]; }; [ 'hasInstance', 'isConcatSpreadable', 'iterator', 'match', 'prototype', 'replace', 'search', 'species', 'split', 'toPrimitive', 'toStringTag', 'unscopables' ].forEach(function (name) { CanSymbol[name] = CanSymbol.for(name); }); } [ 'isMapLike', 'isListLike', 'isValueLike', 'isFunctionLike', 'getOwnKeys', 'getOwnKeyDescriptor', 'proto', 'getOwnEnumerableKeys', 'hasOwnKey', 'size', 'getName', 'getIdentity', 'assignDeep', 'updateDeep', 'getValue', 'setValue', 'getKeyValue', 'setKeyValue', 'updateValues', 'addValue', 'removeValues', 'apply', 'new', 'onValue', 'offValue', 'onKeyValue', 'offKeyValue', 'getKeyDependencies', 'getValueDependencies', 'keyHasDependencies', 'valueHasDependencies', 'onKeys', 'onKeysAdded', 'onKeysRemoved' ].forEach(function (name) { CanSymbol.for('can.' + name); }); module.exports = namespace.Symbol = CanSymbol; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#js/is-iterable/is-iterable*/ define('can-util/js/is-iterable/is-iterable', [ 'require', 'exports', 'module', 'can-symbol' ], function (require, exports, module) { 'use strict'; var canSymbol = require('can-symbol'); module.exports = function (obj) { return obj && !!obj[canSymbol.iterator || canSymbol.for('iterator')]; }; }); /*can-util@3.10.18#js/each/each*/ define('can-util/js/each/each', [ 'require', 'exports', 'module', 'can-util/js/is-array-like/is-array-like', 'can-util/js/is-iterable/is-iterable', 'can-symbol' ], function (require, exports, module) { 'use strict'; var isArrayLike = require('can-util/js/is-array-like/is-array-like'); var has = Object.prototype.hasOwnProperty; var isIterable = require('can-util/js/is-iterable/is-iterable'); var canSymbol = require('can-symbol'); function each(elements, callback, context) { var i = 0, key, len, item; if (elements) { if (isArrayLike(elements)) { for (len = elements.length; i < len; i++) { item = elements[i]; if (callback.call(context || item, item, i, elements) === false) { break; } } } else if (isIterable(elements)) { var iter = elements[canSymbol.iterator || canSymbol.for('iterator')](); var res, value; while (!(res = iter.next()).done) { value = res.value; callback.call(context || elements, Array.isArray(value) ? value[1] : value, value[0]); } } else if (typeof elements === 'object') { for (key in elements) { if (has.call(elements, key) && callback.call(context || elements[key], elements[key], key, elements) === false) { break; } } } } return elements; } module.exports = each; }); /*can-util@3.10.18#js/make-array/make-array*/ define('can-util/js/make-array/make-array', [ 'require', 'exports', 'module', 'can-util/js/each/each', 'can-util/js/is-array-like/is-array-like' ], function (require, exports, module) { 'use strict'; var each = require('can-util/js/each/each'); var isArrayLike = require('can-util/js/is-array-like/is-array-like'); function makeArray(element) { var ret = []; if (isArrayLike(element)) { each(element, function (a, i) { ret[i] = a; }); } else if (element === 0 || element) { ret.push(element); } return ret; } module.exports = makeArray; }); /*can-util@3.10.18#js/is-container/is-container*/ define('can-util/js/is-container/is-container', function (require, exports, module) { 'use strict'; module.exports = function (current) { return /^f|^o/.test(typeof current); }; }); /*can-util@3.10.18#js/get/get*/ define('can-util/js/get/get', [ 'require', 'exports', 'module', 'can-util/js/is-container/is-container' ], function (require, exports, module) { 'use strict'; var isContainer = require('can-util/js/is-container/is-container'); function get(obj, name) { var parts = typeof name !== 'undefined' ? (name + '').replace(/\[/g, '.').replace(/]/g, '').split('.') : [], length = parts.length, current, i, container; if (!length) { return obj; } current = obj; for (i = 0; i < length && isContainer(current); i++) { container = current; current = container[parts[i]]; } return current; } module.exports = get; }); /*can-util@3.10.18#js/is-array/is-array*/ define('can-util/js/is-array/is-array', [ 'require', 'exports', 'module', 'can-log/dev/dev' ], function (require, exports, module) { 'use strict'; var dev = require('can-log/dev/dev'); var hasWarned = false; module.exports = function (arr) { if (!hasWarned) { dev.warn('js/is-array/is-array is deprecated; use Array.isArray'); hasWarned = true; } return Array.isArray(arr); }; }); /*can-util@3.10.18#js/string/string*/ define('can-util/js/string/string', [ 'require', 'exports', 'module', 'can-util/js/get/get', 'can-util/js/is-container/is-container', 'can-log/dev/dev', 'can-util/js/is-array/is-array' ], function (require, exports, module) { 'use strict'; var get = require('can-util/js/get/get'); var isContainer = require('can-util/js/is-container/is-container'); var canDev = require('can-log/dev/dev'); var isArray = require('can-util/js/is-array/is-array'); var strUndHash = /_|-/, strColons = /\=\=/, strWords = /([A-Z]+)([A-Z][a-z])/g, strLowUp = /([a-z\d])([A-Z])/g, strDash = /([a-z\d])([A-Z])/g, strReplacer = /\{([^\}]+)\}/g, strQuote = /"/g, strSingleQuote = /'/g, strHyphenMatch = /-+(.)?/g, strCamelMatch = /[a-z][A-Z]/g, convertBadValues = function (content) { var isInvalid = content === null || content === undefined || isNaN(content) && '' + content === 'NaN'; return '' + (isInvalid ? '' : content); }, deleteAtPath = function (data, path) { var parts = path ? path.replace(/\[/g, '.').replace(/]/g, '').split('.') : []; var current = data; for (var i = 0; i < parts.length - 1; i++) { if (current) { current = current[parts[i]]; } } if (current) { delete current[parts[parts.length - 1]]; } }; var string = { esc: function (content) { return convertBadValues(content).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(strQuote, '&#34;').replace(strSingleQuote, '&#39;'); }, getObject: function (name, roots) { canDev.warn('string.getObject is deprecated, please use can-util/js/get/get instead.'); roots = isArray(roots) ? roots : [roots || window]; var result, l = roots.length; for (var i = 0; i < l; i++) { result = get(roots[i], name); if (result) { return result; } } }, capitalize: function (s, cache) { return s.charAt(0).toUpperCase() + s.slice(1); }, camelize: function (str) { return convertBadValues(str).replace(strHyphenMatch, function (match, chr) { return chr ? chr.toUpperCase() : ''; }); }, hyphenate: function (str) { return convertBadValues(str).replace(strCamelMatch, function (str, offset) { return str.charAt(0) + '-' + str.charAt(1).toLowerCase(); }); }, underscore: function (s) { return s.replace(strColons, '/').replace(strWords, '$1_$2').replace(strLowUp, '$1_$2').replace(strDash, '_').toLowerCase(); }, sub: function (str, data, remove) { var obs = []; str = str || ''; obs.push(str.replace(strReplacer, function (whole, inside) { var ob = get(data, inside); if (remove === true) { deleteAtPath(data, inside); } if (ob === undefined || ob === null) { obs = null; return ''; } if (isContainer(ob) && obs) { obs.push(ob); return ''; } return '' + ob; })); return obs === null ? obs : obs.length <= 1 ? obs[0] : obs; }, replacer: strReplacer, undHash: strUndHash }; module.exports = string; }); /*can-construct@3.2.3#can-construct*/ define('can-construct', [ 'require', 'exports', 'module', 'can-util/js/assign/assign', 'can-util/js/deep-assign/deep-assign', 'can-util/js/dev/dev', 'can-util/js/make-array/make-array', 'can-namespace', 'can-util/js/string/string' ], function (require, exports, module) { 'use strict'; var assign = require('can-util/js/assign/assign'); var deepAssign = require('can-util/js/deep-assign/deep-assign'); var dev = require('can-util/js/dev/dev'); var makeArray = require('can-util/js/make-array/make-array'); var namespace = require('can-namespace'); var CanString = require('can-util/js/string/string'); var reservedWords = { 'abstract': true, 'boolean': true, 'break': true, 'byte': true, 'case': true, 'catch': true, 'char': true, 'class': true, 'const': true, 'continue': true, 'debugger': true, 'default': true, 'delete': true, 'do': true, 'double': true, 'else': true, 'enum': true, 'export': true, 'extends': true, 'false': true, 'final': true, 'finally': true, 'float': true, 'for': true, 'function': true, 'goto': true, 'if': true, 'implements': true, 'import': true, 'in': true, 'instanceof': true, 'int': true, 'interface': true, 'let': true, 'long': true, 'native': true, 'new': true, 'null': true, 'package': true, 'private': true, 'protected': true, 'public': true, 'return': true, 'short': true, 'static': true, 'super': true, 'switch': true, 'synchronized': true, 'this': true, 'throw': true, 'throws': true, 'transient': true, 'true': true, 'try': true, 'typeof': true, 'var': true, 'void': true, 'volatile': true, 'while': true, 'with': true }; var constructorNameRegex = /[^A-Z0-9_]/gi; var initializing = 0; var namedCtor = function (cache) { return function (name, fn) { return (name in cache ? cache[name] : cache[name] = new Function('__', 'function ' + name + '(){return __.apply(this,arguments)};return ' + name))(fn); }; }({}); var Construct = function () { if (arguments.length) { return Construct.extend.apply(Construct, arguments); } }; var canGetDescriptor; try { Object.getOwnPropertyDescriptor({}); canGetDescriptor = true; } catch (e) { canGetDescriptor = false; } var getDescriptor = function (newProps, name) { var descriptor = Object.getOwnPropertyDescriptor(newProps, name); if (descriptor && (descriptor.get || descriptor.set)) { return descriptor; } return null; }, inheritGetterSetter = function (newProps, oldProps, addTo) { addTo = addTo || newProps; var descriptor; for (var name in newProps) { if (descriptor = getDescriptor(newProps, name)) { this._defineProperty(addTo, oldProps, name, descriptor); } else { Construct._overwrite(addTo, oldProps, name, newProps[name]); } } }, simpleInherit = function (newProps, oldProps, addTo) { addTo = addTo || newProps; for (var name in newProps) { Construct._overwrite(addTo, oldProps, name, newProps[name]); } }; assign(Construct, { constructorExtends: true, newInstance: function () { var inst = this.instance(), args; if (inst.setup) { Object.defineProperty(inst, '__inSetup', { configurable: true, enumerable: false, value: true, writable: true }); args = inst.setup.apply(inst, arguments); if (args instanceof Construct.ReturnValue) { return args.value; } inst.__inSetup = false; } if (inst.init) { inst.init.apply(inst, args || arguments); } return inst; }, _inherit: canGetDescriptor ? inheritGetterSetter : simpleInherit, _defineProperty: function (what, oldProps, propName, descriptor) { Object.defineProperty(what, propName, descriptor); }, _overwrite: function (what, oldProps, propName, val) { Object.defineProperty(what, propName, { value: val, configurable: true, enumerable: true, writable: true }); }, setup: function (base) { this.defaults = deepAssign(true, {}, base.defaults, this.defaults); }, instance: function () { initializing = 1; var inst = new this(); initializing = 0; return inst; }, extend: function (name, staticProperties, instanceProperties) { var shortName = name, klass = staticProperties, proto = instanceProperties; if (typeof shortName !== 'string') { proto = klass; klass = shortName; shortName = null; } if (!proto) { proto = klass; klass = null; } proto = proto || {}; var _super_class = this, _super = this.prototype, Constructor, prototype; prototype = this.instance(); Construct._inherit(proto, _super, prototype); if (shortName) { } else if (klass && klass.shortName) { shortName = klass.shortName; } else if (this.shortName) { shortName = this.shortName; } var constructorName = shortName ? shortName.replace(constructorNameRegex, '_') : 'Constructor'; if (reservedWords[constructorName]) { constructorName = CanString.capitalize(constructorName); } function init() { if (!initializing) { if (!this || this.constructor !== Constructor && arguments.length && Constructor.constructorExtends) { dev.warn('can/construct/construct.js: extending a Construct without calling extend'); } return (!this || this.constructor !== Constructor) && arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) : Constructor.newInstance.apply(Constructor, arguments); } } Constructor = typeof namedCtor === 'function' ? namedCtor(constructorName, init) : function () { return init.apply(this, arguments); }; for (var propName in _super_class) { if (_super_class.hasOwnProperty(propName)) { Constructor[propName] = _super_class[propName]; } } Construct._inherit(klass, _super_class, Constructor); assign(Constructor, { constructor: Constructor, prototype: prototype }); if (shortName !== undefined) { Constructor.shortName = shortName; } Constructor.prototype.constructor = Constructor; var t = [_super_class].concat(makeArray(arguments)), args = Constructor.setup.apply(Constructor, t); if (Constructor.init) { Constructor.init.apply(Constructor, args || t); } return Constructor; }, ReturnValue: function (value) { this.value = value; } }); Construct.prototype.setup = function () { }; Construct.prototype.init = function () { }; module.exports = namespace.Construct = Construct; }); /*can-cid@1.1.2#can-cid*/ define('can-cid', [ 'require', 'exports', 'module', 'can-namespace' ], function (require, exports, module) { var namespace = require('can-namespace'); var _cid = 0; var domExpando = 'can' + new Date(); var cid = function (object, name) { var propertyName = object.nodeName ? domExpando : '_cid'; if (!object[propertyName]) { _cid++; object[propertyName] = (name || '') + _cid; } return object[propertyName]; }; cid.domExpando = domExpando; cid.get = function (object) { var type = typeof object; var isObject = type !== null && (type === 'object' || type === 'function'); return isObject ? cid(object) : type + ':' + object; }; if (namespace.cid) { throw new Error('You can\'t have two versions of can-cid, check your dependencies'); } else { module.exports = namespace.cid = cid; } }); /*can-dom-data-state@0.2.0#can-dom-data-state*/ define('can-dom-data-state', [ 'require', 'exports', 'module', 'can-namespace', 'can-cid' ], function (require, exports, module) { 'use strict'; var namespace = require('can-namespace'); var CID = require('can-cid'); var data = {}; var isEmptyObject = function (obj) { for (var prop in obj) { return false; } return true; }; var setData = function (name, value) { var id = CID(this); var store = data[id] || (data[id] = {}); if (name !== undefined) { store[name] = value; } return store; }; var deleteNode = function () { var id = CID.get(this); var nodeDeleted = false; if (id && data[id]) { nodeDeleted = true; delete data[id]; } return nodeDeleted; }; var domDataState = { _data: data, getCid: function () { return CID.get(this); }, cid: function () { return CID(this); }, expando: CID.domExpando, get: function (key) { var id = CID.get(this), store = id && data[id]; return key === undefined ? store : store && store[key]; }, set: setData, clean: function (prop) { var id = CID.get(this); var itemData = data[id]; if (itemData && itemData[prop]) { delete itemData[prop]; } if (isEmptyObject(itemData)) { deleteNode.call(this); } }, delete: deleteNode }; if (namespace.domDataState) { throw new Error('You can\'t have two versions of can-dom-data-state, check your dependencies'); } else { module.exports = namespace.domDataState = domDataState; } }); /*can-reflect@1.10.2#reflections/helpers*/ define('can-reflect/reflections/helpers', [ 'require', 'exports', 'module', 'can-symbol' ], function (require, exports, module) { var canSymbol = require('can-symbol'); module.exports = { makeGetFirstSymbolValue: function (symbolNames) { var symbols = symbolNames.map(function (name) { return canSymbol.for(name); }); var length = symbols.length; return function getFirstSymbol(obj) { var index = -1; while (++index < length) { if (obj[symbols[index]] !== undefined) { return obj[symbols[index]]; } } }; }, hasLength: function (list) { var type = typeof list; var length = list && type !== 'boolean' && typeof list !== 'number' && 'length' in list && list.length; return typeof list !== 'function' && (length === 0 || typeof length === 'number' && length > 0 && length - 1 in list); } }; }); /*can-reflect@1.10.2#reflections/type/type*/ define('can-reflect/reflections/type/type', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect/reflections/helpers' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var helpers = require('can-reflect/reflections/helpers'); var plainFunctionPrototypePropertyNames = Object.getOwnPropertyNames(function () { }.prototype); var plainFunctionPrototypeProto = Object.getPrototypeOf(function () { }.prototype); function isConstructorLike(func) { var value = func[canSymbol.for('can.new')]; if (value !== undefined) { return value; } if (typeof func !== 'function') { return false; } var prototype = func.prototype; if (!prototype) { return false; } if (plainFunctionPrototypeProto !== Object.getPrototypeOf(prototype)) { return true; } var propertyNames = Object.getOwnPropertyNames(prototype); if (propertyNames.length === plainFunctionPrototypePropertyNames.length) { for (var i = 0, len = propertyNames.length; i < len; i++) { if (propertyNames[i] !== plainFunctionPrototypePropertyNames[i]) { return true; } } return false; } else { return true; } } var getNewOrApply = helpers.makeGetFirstSymbolValue([ 'can.new', 'can.apply' ]); function isFunctionLike(obj) { var result, symbolValue = obj[canSymbol.for('can.isFunctionLike')]; if (symbolValue !== undefined) { return symbolValue; } result = getNewOrApply(obj); if (result !== undefined) { return !!result; } return typeof obj === 'function'; } function isPrimitive(obj) { var type = typeof obj; if (obj == null || type !== 'function' && type !== 'object') { return true; } else { return false; } } function isBuiltIn(obj) { if (isPrimitive(obj) || Array.isArray(obj) || isPlainObject(obj) || Object.prototype.toString.call(obj) !== '[object Object]' && Object.prototype.toString.call(obj).indexOf('[object ') !== -1) { return true; } else { return false; } } function isValueLike(obj) { var symbolValue; if (isPrimitive(obj)) { return true; } symbolValue = obj[canSymbol.for('can.isValueLike')]; if (typeof symbolValue !== 'undefined') { return symbolValue; } var value = obj[canSymbol.for('can.getValue')]; if (value !== undefined) { return !!value; } } function isMapLike(obj) { if (isPrimitive(obj)) { return false; } var isMapLike = obj[canSymbol.for('can.isMapLike')]; if (typeof isMapLike !== 'undefined') { return !!isMapLike; } var value = obj[canSymbol.for('can.getKeyValue')]; if (value !== undefined) { return !!value; } return true; } var onValueSymbol = canSymbol.for('can.onValue'), onKeyValueSymbol = canSymbol.for('can.onKeyValue'), onPatchesSymbol = canSymbol.for('can.onPatches'); function isObservableLike(obj) { if (isPrimitive(obj)) { return false; } return Boolean(obj[onValueSymbol] || obj[onKeyValueSymbol] || obj[onPatchesSymbol]); } function isListLike(list) { var symbolValue, type = typeof list; if (type === 'string') { return true; } if (isPrimitive(list)) { return false; } symbolValue = list[canSymbol.for('can.isListLike')]; if (typeof symbolValue !== 'undefined') { return symbolValue; } var value = list[canSymbol.iterator]; if (value !== undefined) { return !!value; } if (Array.isArray(list)) { return true; } return helpers.hasLength(list); } var supportsSymbols = typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'; var isSymbolLike; if (supportsSymbols) { isSymbolLike = function (symbol) { return typeof symbol === 'symbol'; }; } else { var symbolStart = '@@symbol'; isSymbolLike = function (symbol) { if (typeof symbol === 'object' && !Array.isArray(symbol)) { return symbol.toString().substr(0, symbolStart.length) === symbolStart; } else { return false; } }; } var coreHasOwn = Object.prototype.hasOwnProperty; var funcToString = Function.prototype.toString; var objectCtorString = funcToString.call(Object); function isPlainObject(obj) { if (!obj || typeof obj !== 'object') { return false; } var proto = Object.getPrototypeOf(obj); if (proto === Object.prototype || proto === null) { return true; } var Constructor = coreHasOwn.call(proto, 'constructor') && proto.constructor; return typeof Constructor === 'function' && Constructor instanceof Constructor && funcToString.call(Constructor) === objectCtorString; } module.exports = { isConstructorLike: isConstructorLike, isFunctionLike: isFunctionLike, isListLike: isListLike, isMapLike: isMapLike, isObservableLike: isObservableLike, isPrimitive: isPrimitive, isBuiltIn: isBuiltIn, isValueLike: isValueLike, isSymbolLike: isSymbolLike, isMoreListLikeThanMapLike: function (obj) { if (Array.isArray(obj)) { return true; } if (obj instanceof Array) { return true; } var value = obj[canSymbol.for('can.isMoreListLikeThanMapLike')]; if (value !== undefined) { return value; } var isListLike = this.isListLike(obj), isMapLike = this.isMapLike(obj); if (isListLike && !isMapLike) { return true; } else if (!isListLike && isMapLike) { return false; } }, isIteratorLike: function (obj) { return obj && typeof obj === 'object' && typeof obj.next === 'function' && obj.next.length === 0; }, isPromise: function (obj) { return obj instanceof Promise || Object.prototype.toString.call(obj) === '[object Promise]'; }, isPlainObject: isPlainObject }; }); /*can-reflect@1.10.2#reflections/call/call*/ define('can-reflect/reflections/call/call', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect/reflections/type/type' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var typeReflections = require('can-reflect/reflections/type/type'); module.exports = { call: function (func, context) { var args = [].slice.call(arguments, 2); var apply = func[canSymbol.for('can.apply')]; if (apply) { return apply.call(func, context, args); } else { return func.apply(context, args); } }, apply: function (func, context, args) { var apply = func[canSymbol.for('can.apply')]; if (apply) { return apply.call(func, context, args); } else { return func.apply(context, args); } }, 'new': function (func) { var args = [].slice.call(arguments, 1); var makeNew = func[canSymbol.for('can.new')]; if (makeNew) { return makeNew.apply(func, args); } else { var context = Object.create(func.prototype); var ret = func.apply(context, args); if (typeReflections.isPrimitive(ret)) { return context; } else { return ret; } } } }; }); /*can-reflect@1.10.2#reflections/get-set/get-set*/ define('can-reflect/reflections/get-set/get-set', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect/reflections/type/type' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var typeReflections = require('can-reflect/reflections/type/type'); var setKeyValueSymbol = canSymbol.for('can.setKeyValue'), getKeyValueSymbol = canSymbol.for('can.getKeyValue'), getValueSymbol = canSymbol.for('can.getValue'), setValueSymbol = canSymbol.for('can.setValue'); var reflections = { setKeyValue: function (obj, key, value) { if (typeReflections.isSymbolLike(key)) { if (typeof key === 'symbol') { obj[key] = value; } else { Object.defineProperty(obj, key, { enumerable: false, configurable: true, value: value, writable: true }); } return; } var setKeyValue = obj[setKeyValueSymbol]; if (setKeyValue !== undefined) { return setKeyValue.call(obj, key, value); } else { obj[key] = value; } }, getKeyValue: function (obj, key) { var getKeyValue = obj[getKeyValueSymbol]; if (getKeyValue) { return getKeyValue.call(obj, key); } return obj[key]; }, deleteKeyValue: function (obj, key) { var deleteKeyValue = obj[canSymbol.for('can.deleteKeyValue')]; if (deleteKeyValue) { return deleteKeyValue.call(obj, key); } delete obj[key]; }, getValue: function (value) { if (typeReflections.isPrimitive(value)) { return value; } var getValue = value[getValueSymbol]; if (getValue) { return getValue.call(value); } return value; }, setValue: function (item, value) { var setValue = item && item[setValueSymbol]; if (setValue) { return setValue.call(item, value); } else { throw new Error('can-reflect.setValue - Can not set value.'); } }, splice: function (obj, index, removing, adding) { var howMany; if (typeof removing !== 'number') { var updateValues = obj[canSymbol.for('can.updateValues')]; if (updateValues) { return updateValues.call(obj, index, removing, adding); } howMany = removing.length; } else { howMany = removing; } var splice = obj[canSymbol.for('can.splice')]; if (splice) { return splice.call(obj, index, howMany, adding); } return [].splice.apply(obj, [ index, howMany ].concat(adding)); }, addValues: function (obj, adding, index) { var add = obj[canSymbol.for('can.addValues')]; if (add) { return add.call(obj, adding, index); } if (Array.isArray(obj) && index === undefined) { return obj.push.apply(obj, adding); } return reflections.splice(obj, index, [], adding); }, removeValues: function (obj, removing, index) { var removeValues = obj[canSymbol.for('can.removeValues')]; if (removeValues) { return removeValues.call(obj, removing, index); } if (Array.isArray(obj) && index === undefined) { removing.forEach(function (item) { var index = obj.indexOf(item); if (index >= 0) { obj.splice(index, 1); } }); return; } return reflections.splice(obj, index, removing, []); } }; reflections.get = reflections.getKeyValue; reflections.set = reflections.setKeyValue; reflections['delete'] = reflections.deleteKeyValue; module.exports = reflections; }); /*can-reflect@1.10.2#reflections/observe/observe*/ define('can-reflect/reflections/observe/observe', [ 'require', 'exports', 'module', 'can-symbol' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var slice = [].slice; function makeFallback(symbolName, fallbackName) { return function (obj, event, handler, queueName) { var method = obj[canSymbol.for(symbolName)]; if (method !== undefined) { return method.call(obj, event, handler, queueName); } return this[fallbackName].apply(this, arguments); }; } function makeErrorIfMissing(symbolName, errorMessage) { return function (obj) { var method = obj[canSymbol.for(symbolName)]; if (method !== undefined) { var args = slice.call(arguments, 1); return method.apply(obj, args); } throw new Error(errorMessage); }; } module.exports = { onKeyValue: makeFallback('can.onKeyValue', 'onEvent'), offKeyValue: makeFallback('can.offKeyValue', 'offEvent'), onKeys: makeErrorIfMissing('can.onKeys', 'can-reflect: can not observe an onKeys event'), onKeysAdded: makeErrorIfMissing('can.onKeysAdded', 'can-reflect: can not observe an onKeysAdded event'), onKeysRemoved: makeErrorIfMissing('can.onKeysRemoved', 'can-reflect: can not unobserve an onKeysRemoved event'), getKeyDependencies: makeErrorIfMissing('can.getKeyDependencies', 'can-reflect: can not determine dependencies'), getWhatIChange: makeErrorIfMissing('can.getWhatIChange', 'can-reflect: can not determine dependencies'), getChangesDependencyRecord: function getChangesDependencyRecord(handler) { var fn = handler[canSymbol.for('can.getChangesDependencyRecord')]; if (typeof fn === 'function') { return fn(); } }, keyHasDependencies: makeErrorIfMissing('can.keyHasDependencies', 'can-reflect: can not determine if this has key dependencies'), onValue: makeErrorIfMissing('can.onValue', 'can-reflect: can not observe value change'), offValue: makeErrorIfMissing('can.offValue', 'can-reflect: can not unobserve value change'), getValueDependencies: makeErrorIfMissing('can.getValueDependencies', 'can-reflect: can not determine dependencies'), valueHasDependencies: makeErrorIfMissing('can.valueHasDependencies', 'can-reflect: can not determine if value has dependencies'), onPatches: makeErrorIfMissing('can.onPatches', 'can-reflect: can not observe patches on object'), offPatches: makeErrorIfMissing('can.offPatches', 'can-reflect: can not unobserve patches on object'), onInstanceBoundChange: makeErrorIfMissing('can.onInstanceBoundChange', 'can-reflect: can not observe bound state change in instances.'), offInstanceBoundChange: makeErrorIfMissing('can.offInstanceBoundChange', 'can-reflect: can not unobserve bound state change'), isBound: makeErrorIfMissing('can.isBound', 'can-reflect: cannot determine if object is bound'), onEvent: function (obj, eventName, callback, queue) { if (obj) { var onEvent = obj[canSymbol.for('can.onEvent')]; if (onEvent !== undefined) { return onEvent.call(obj, eventName, callback, queue); } else if (obj.addEventListener) { obj.addEventListener(eventName, callback, queue); } } }, offEvent: function (obj, eventName, callback, queue) { if (obj) { var offEvent = obj[canSymbol.for('can.offEvent')]; if (offEvent !== undefined) { return offEvent.call(obj, eventName, callback, queue); } else if (obj.removeEventListener) { obj.removeEventListener(eventName, callback, queue); } } }, setPriority: function (obj, priority) { if (obj) { var setPriority = obj[canSymbol.for('can.setPriority')]; if (setPriority !== undefined) { setPriority.call(obj, priority); return true; } } return false; }, getPriority: function (obj) { if (obj) { var getPriority = obj[canSymbol.for('can.getPriority')]; if (getPriority !== undefined) { return getPriority.call(obj); } } return undefined; } }; }); /*can-reflect@1.10.2#reflections/shape/shape*/ define('can-reflect/reflections/shape/shape', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect/reflections/get-set/get-set', 'can-reflect/reflections/type/type', 'can-reflect/reflections/helpers' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var getSetReflections = require('can-reflect/reflections/get-set/get-set'); var typeReflections = require('can-reflect/reflections/type/type'); var helpers = require('can-reflect/reflections/helpers'); var shapeReflections; var shiftFirstArgumentToThis = function (func) { return function () { var args = [this]; args.push.apply(args, arguments); return func.apply(null, args); }; }; var getKeyValueSymbol = canSymbol.for('can.getKeyValue'); var shiftedGetKeyValue = shiftFirstArgumentToThis(getSetReflections.getKeyValue); var setKeyValueSymbol = canSymbol.for('can.setKeyValue'); var shiftedSetKeyValue = shiftFirstArgumentToThis(getSetReflections.setKeyValue); var sizeSymbol = canSymbol.for('can.size'); var serializeMap = null; var hasUpdateSymbol = helpers.makeGetFirstSymbolValue([ 'can.updateDeep', 'can.assignDeep', 'can.setKeyValue' ]); var shouldUpdateOrAssign = function (obj) { return typeReflections.isPlainObject(obj) || Array.isArray(obj) || !!hasUpdateSymbol(obj); }; function isSerializable(obj) { if (typeReflections.isPrimitive(obj)) { return true; } if (hasUpdateSymbol(obj)) { return false; } return typeReflections.isBuiltIn(obj) && !typeReflections.isPlainObject(obj); } var Object_Keys; try { Object.keys(1); Object_Keys = Object.keys; } catch (e) { Object_Keys = function (obj) { if (typeReflections.isPrimitive(obj)) { return []; } else { return Object.keys(obj); } }; } function makeSerializer(methodName, symbolsToCheck) { return function serializer(value, MapType) { if (isSerializable(value)) { return value; } var firstSerialize; if (MapType && !serializeMap) { serializeMap = { unwrap: new MapType(), serialize: new MapType() }; firstSerialize = true; } var serialized; if (typeReflections.isValueLike(value)) { serialized = this[methodName](getSetReflections.getValue(value)); } else { var isListLike = typeReflections.isIteratorLike(value) || typeReflections.isMoreListLikeThanMapLike(value); serialized = isListLike ? [] : {}; if (serializeMap) { if (serializeMap[methodName].has(value)) { return serializeMap[methodName].get(value); } else { serializeMap[methodName].set(value, serialized); } } for (var i = 0, len = symbolsToCheck.length; i < len; i++) { var serializer = value[symbolsToCheck[i]]; if (serializer) { var result = serializer.call(value, serialized); if (firstSerialize) { serializeMap = null; } return result; } } if (typeof obj === 'function') { if (serializeMap) { serializeMap[methodName].set(value, value); } serialized = value; } else if (isListLike) { this.eachIndex(value, function (childValue, index) { serialized[index] = this[methodName](childValue); }, this); } else { this.eachKey(value, function (childValue, prop) { serialized[prop] = this[methodName](childValue); }, this); } } if (firstSerialize) { serializeMap = null; } return serialized; }; } var makeMap; if (typeof Map !== 'undefined') { makeMap = function (keys) { var map = new Map(); shapeReflections.eachIndex(keys, function (key) { map.set(key, true); }); return map; }; } else { makeMap = function (keys) { var map = {}; keys.forEach(function (key) { map[key] = true; }); return { get: function (key) { return map[key]; }, set: function (key, value) { map[key] = value; }, keys: function () { return keys; } }; }; } var fastHasOwnKey = function (obj) { var hasOwnKey = obj[canSymbol.for('can.hasOwnKey')]; if (hasOwnKey) { return hasOwnKey.bind(obj); } else { var map = makeMap(shapeReflections.getOwnEnumerableKeys(obj)); return function (key) { return map.get(key); }; } }; function addPatch(patches, patch) { var lastPatch = patches[patches.length - 1]; if (lastPatch) { if (lastPatch.deleteCount === lastPatch.insert.length && patch.index - lastPatch.index === lastPatch.deleteCount) { lastPatch.insert.push.apply(lastPatch.insert, patch.insert); lastPatch.deleteCount += patch.deleteCount; return; } } patches.push(patch); } function updateDeepList(target, source, isAssign) { var sourceArray = this.toArray(source); var patches = [], lastIndex = -1; this.eachIndex(target, function (curVal, index) { lastIndex = index; if (index >= sourceArray.length) { if (!isAssign) { addPatch(patches, { index: index, deleteCount: sourceArray.length - index + 1, insert: [] }); } return false; } var newVal = sourceArray[index]; if (typeReflections.isPrimitive(curVal) || typeReflections.isPrimitive(newVal) || shouldUpdateOrAssign(curVal) === false) { addPatch(patches, { index: index, deleteCount: 1, insert: [newVal] }); } else { this.updateDeep(curVal, newVal); } }, this); if (sourceArray.length > lastIndex) { addPatch(patches, { index: lastIndex + 1, deleteCount: 0, insert: sourceArray.slice(lastIndex + 1) }); } for (var i = 0, patchLen = patches.length; i < patchLen; i++) { var patch = patches[i]; getSetReflections.splice(target, patch.index, patch.deleteCount, patch.insert); } return target; } shapeReflections = { each: function (obj, callback, context) { if (typeReflections.isIteratorLike(obj) || typeReflections.isMoreListLikeThanMapLike(obj)) { return this.eachIndex(obj, callback, context); } else { return this.eachKey(obj, callback, context); } }, eachIndex: function (list, callback, context) { if (Array.isArray(list)) { return this.eachListLike(list, callback, context); } else { var iter, iterator = list[canSymbol.iterator]; if (typeReflections.isIteratorLike(list)) { iter = list; } else if (iterator) { iter = iterator.call(list); } if (iter) { var res, index = 0; while (!(res = iter.next()).done) { if (callback.call(context || list, res.value, index++, list) === false) { break; } } } else { this.eachListLike(list, callback, context); } } return list; }, eachListLike: function (list, callback, context) { var index = -1; var length = list.length; if (length === undefined) { var size = list[sizeSymbol]; if (size) { length = size.call(list); } else { throw new Error('can-reflect: unable to iterate.'); } } while (++index < length) { var item = list[index]; if (callback.call(context || item, item, index, list) === false) { break; } } return list; }, toArray: function (obj) { var arr = []; this.each(obj, function (value) { arr.push(value); }); return arr; }, eachKey: function (obj, callback, context) { if (obj) { var enumerableKeys = this.getOwnEnumerableKeys(obj); var getKeyValue = obj[getKeyValueSymbol] || shiftedGetKeyValue; return this.eachIndex(enumerableKeys, function (key) { var value = getKeyValue.call(obj, key); return callback.call(context || obj, value, key, obj); }); } return obj; }, 'hasOwnKey': function (obj, key) { var hasOwnKey = obj[canSymbol.for('can.hasOwnKey')]; if (hasOwnKey) { return hasOwnKey.call(obj, key); } var getOwnKeys = obj[canSymbol.for('can.getOwnKeys')]; if (getOwnKeys) { var found = false; this.eachIndex(getOwnKeys.call(obj), function (objKey) { if (objKey === key) { found = true; return false; } }); return found; } return obj.hasOwnProperty(key); }, getOwnEnumerableKeys: function (obj) { var getOwnEnumerableKeys = obj[canSymbol.for('can.getOwnEnumerableKeys')]; if (getOwnEnumerableKeys) { return getOwnEnumerableKeys.call(obj); } if (obj[canSymbol.for('can.getOwnKeys')] && obj[canSymbol.for('can.getOwnKeyDescriptor')]) { var keys = []; this.eachIndex(this.getOwnKeys(obj), function (key) { var descriptor = this.getOwnKeyDescriptor(obj, key); if (descriptor.enumerable) { keys.push(key); } }, this); return keys; } else { return Object_Keys(obj); } }, getOwnKeys: function (obj) { var getOwnKeys = obj[canSymbol.for('can.getOwnKeys')]; if (getOwnKeys) { return getOwnKeys.call(obj); } else { return Object.getOwnPropertyNames(obj); } }, getOwnKeyDescriptor: function (obj, key) { var getOwnKeyDescriptor = obj[canSymbol.for('can.getOwnKeyDescriptor')]; if (getOwnKeyDescriptor) { return getOwnKeyDescriptor.call(obj, key); } else { return Object.getOwnPropertyDescriptor(obj, key); } }, unwrap: makeSerializer('unwrap', [canSymbol.for('can.unwrap')]), serialize: makeSerializer('serialize', [ canSymbol.for('can.serialize'), canSymbol.for('can.unwrap') ]), assignMap: function (target, source) { var hasOwnKey = fastHasOwnKey(target); var getKeyValue = target[getKeyValueSymbol] || shiftedGetKeyValue; var setKeyValue = target[setKeyValueSymbol] || shiftedSetKeyValue; this.eachKey(source, function (value, key) { if (!hasOwnKey(key) || getKeyValue.call(target, key) !== value) { setKeyValue.call(target, key, value); } }); return target; }, assignList: function (target, source) { var inserting = this.toArray(source); getSetReflections.splice(target, 0, inserting, inserting); return target; }, assign: function (target, source) { if (typeReflections.isIteratorLike(source) || typeReflections.isMoreListLikeThanMapLike(source)) { this.assignList(target, source); } else { this.assignMap(target, source); } return target; }, assignDeepMap: function (target, source) { var hasOwnKey = fastHasOwnKey(target); var getKeyValue = target[getKeyValueSymbol] || shiftedGetKeyValue; var setKeyValue = target[setKeyValueSymbol] || shiftedSetKeyValue; this.eachKey(source, function (newVal, key) { if (!hasOwnKey(key)) { getSetReflections.setKeyValue(target, key, newVal); } else { var curVal = getKeyValue.call(target, key); if (newVal === curVal) { } else if (typeReflections.isPrimitive(curVal) || typeReflections.isPrimitive(newVal) || shouldUpdateOrAssign(curVal) === false) { setKeyValue.call(target, key, newVal); } else { this.assignDeep(curVal, newVal); } } }, this); return target; }, assignDeepList: function (target, source) { return updateDeepList.call(this, target, source, true); }, assignDeep: function (target, source) { var assignDeep = target[canSymbol.for('can.assignDeep')]; if (assignDeep) { assignDeep.call(target, source); } else if (typeReflections.isMoreListLikeThanMapLike(source)) { this.assignDeepList(target, source); } else { this.assignDeepMap(target, source); } return target; }, updateMap: function (target, source) { var sourceKeyMap = makeMap(this.getOwnEnumerableKeys(source)); var sourceGetKeyValue = source[getKeyValueSymbol] || shiftedGetKeyValue; var targetSetKeyValue = target[setKeyValueSymbol] || shiftedSetKeyValue; this.eachKey(target, function (curVal, key) { if (!sourceKeyMap.get(key)) { getSetReflections.deleteKeyValue(target, key); return; } sourceKeyMap.set(key, false); var newVal = sourceGetKeyValue.call(source, key); if (newVal !== curVal) { targetSetKeyValue.call(target, key, newVal); } }, this); this.eachIndex(sourceKeyMap.keys(), function (key) { if (sourceKeyMap.get(key)) { targetSetKeyValue.call(target, key, sourceGetKeyValue.call(source, key)); } }); return target; }, updateList: function (target, source) { var inserting = this.toArray(source); getSetReflections.splice(target, 0, target, inserting); return target; }, update: function (target, source) { if (typeReflections.isIteratorLike(source) || typeReflections.isMoreListLikeThanMapLike(source)) { this.updateList(target, source); } else { this.updateMap(target, source); } return target; }, updateDeepMap: function (target, source) { var sourceKeyMap = makeMap(this.getOwnEnumerableKeys(source)); var sourceGetKeyValue = source[getKeyValueSymbol] || shiftedGetKeyValue; var targetSetKeyValue = target[setKeyValueSymbol] || shiftedSetKeyValue; this.eachKey(target, function (curVal, key) { if (!sourceKeyMap.get(key)) { getSetReflections.deleteKeyValue(target, key); return; } sourceKeyMap.set(key, false); var newVal = sourceGetKeyValue.call(source, key); if (typeReflections.isPrimitive(curVal) || typeReflections.isPrimitive(newVal) || shouldUpdateOrAssign(curVal) === false) { targetSetKeyValue.call(target, key, newVal); } else { this.updateDeep(curVal, newVal); } }, this); this.eachIndex(sourceKeyMap.keys(), function (key) { if (sourceKeyMap.get(key)) { targetSetKeyValue.call(target, key, sourceGetKeyValue.call(source, key)); } }); return target; }, updateDeepList: function (target, source) { return updateDeepList.call(this, target, source); }, updateDeep: function (target, source) { var updateDeep = target[canSymbol.for('can.updateDeep')]; if (updateDeep) { updateDeep.call(target, source); } else if (typeReflections.isMoreListLikeThanMapLike(source)) { this.updateDeepList(target, source); } else { this.updateDeepMap(target, source); } return target; }, 'in': function () { }, getAllEnumerableKeys: function () { }, getAllKeys: function () { }, assignSymbols: function (target, source) { this.eachKey(source, function (value, key) { var symbol = typeReflections.isSymbolLike(canSymbol[key]) ? canSymbol[key] : canSymbol.for(key); getSetReflections.setKeyValue(target, symbol, value); }); return target; }, isSerializable: isSerializable, size: function (obj) { var size = obj[sizeSymbol]; var count = 0; if (size) { return size.call(obj); } else if (helpers.hasLength(obj)) { return obj.length; } else if (typeReflections.isListLike(obj)) { this.each(obj, function () { count++; }); return count; } else if (obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { count++; } } return count; } else { return undefined; } }, defineInstanceKey: function (cls, key, properties) { var defineInstanceKey = cls[canSymbol.for('can.defineInstanceKey')]; if (defineInstanceKey) { return defineInstanceKey.call(cls, key, properties); } var proto = cls.prototype; defineInstanceKey = proto[canSymbol.for('can.defineInstanceKey')]; if (defineInstanceKey) { defineInstanceKey.call(proto, key, properties); } else { Object.defineProperty(proto, key, shapeReflections.assign({ configurable: true, enumerable: !typeReflections.isSymbolLike(key), writable: true }, properties)); } } }; shapeReflections.keys = shapeReflections.getOwnEnumerableKeys; module.exports = shapeReflections; }); /*can-reflect@1.10.2#reflections/get-name/get-name*/ define('can-reflect/reflections/get-name/get-name', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect/reflections/type/type' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var typeReflections = require('can-reflect/reflections/type/type'); var getNameSymbol = canSymbol.for('can.getName'); function setName(obj, nameGetter) { if (typeof nameGetter !== 'function') { var value = nameGetter; nameGetter = function () { return value; }; } Object.defineProperty(obj, getNameSymbol, { value: nameGetter }); } function getName(obj) { var nameGetter = obj[getNameSymbol]; if (nameGetter) { return nameGetter.call(obj); } if (typeof obj === 'function') { return obj.name; } if (obj.constructor && obj !== obj.constructor) { var parent = getName(obj.constructor); if (parent) { if (typeReflections.isValueLike(obj)) { return parent + '<>'; } if (typeReflections.isMoreListLikeThanMapLike(obj)) { return parent + '[]'; } if (typeReflections.isMapLike(obj)) { return parent + '{}'; } } } return undefined; } module.exports = { setName: setName, getName: getName }; }); /*can-reflect@1.10.2#types/map*/ define('can-reflect/types/map', [ 'require', 'exports', 'module', 'can-reflect/reflections/shape/shape', 'can-symbol' ], function (require, exports, module) { var shape = require('can-reflect/reflections/shape/shape'); var CanSymbol = require('can-symbol'); function keysPolyfill() { var keys = []; var currentIndex = 0; this.forEach(function (val, key) { keys.push(key); }); return { next: function () { return { value: keys[currentIndex], done: currentIndex++ === keys.length }; } }; } if (typeof Map !== 'undefined') { shape.assignSymbols(Map.prototype, { 'can.getOwnEnumerableKeys': Map.prototype.keys, 'can.setKeyValue': Map.prototype.set, 'can.getKeyValue': Map.prototype.get, 'can.deleteKeyValue': Map.prototype['delete'], 'can.hasOwnKey': Map.prototype.has }); if (typeof Map.prototype.keys !== 'function') { Map.prototype.keys = Map.prototype[CanSymbol.for('can.getOwnEnumerableKeys')] = keysPolyfill; } } if (typeof WeakMap !== 'undefined') { shape.assignSymbols(WeakMap.prototype, { 'can.getOwnEnumerableKeys': function () { throw new Error('can-reflect: WeakMaps do not have enumerable keys.'); }, 'can.setKeyValue': WeakMap.prototype.set, 'can.getKeyValue': WeakMap.prototype.get, 'can.deleteKeyValue': WeakMap.prototype['delete'], 'can.hasOwnKey': WeakMap.prototype.has }); } }); /*can-reflect@1.10.2#types/set*/ define('can-reflect/types/set', [ 'require', 'exports', 'module', 'can-reflect/reflections/shape/shape', 'can-symbol' ], function (require, exports, module) { var shape = require('can-reflect/reflections/shape/shape'); var CanSymbol = require('can-symbol'); if (typeof Set !== 'undefined') { shape.assignSymbols(Set.prototype, { 'can.isMoreListLikeThanMapLike': true, 'can.updateValues': function (index, removing, adding) { if (removing !== adding) { shape.each(removing, function (value) { this.delete(value); }, this); } shape.each(adding, function (value) { this.add(value); }, this); }, 'can.size': function () { return this.size; } }); if (typeof Set.prototype[CanSymbol.iterator] !== 'function') { Set.prototype[CanSymbol.iterator] = function () { var arr = []; var currentIndex = 0; this.forEach(function (val) { arr.push(val); }); return { next: function () { return { value: arr[currentIndex], done: currentIndex++ === arr.length }; } }; }; } } if (typeof WeakSet !== 'undefined') { shape.assignSymbols(WeakSet.prototype, { 'can.isListLike': true, 'can.isMoreListLikeThanMapLike': true, 'can.updateValues': function (index, removing, adding) { if (removing !== adding) { shape.each(removing, function (value) { this.delete(value); }, this); } shape.each(adding, function (value) { this.add(value); }, this); }, 'can.size': function () { throw new Error('can-reflect: WeakSets do not have enumerable keys.'); } }); } }); /*can-reflect@1.10.2#can-reflect*/ define('can-reflect', [ 'require', 'exports', 'module', 'can-reflect/reflections/call/call', 'can-reflect/reflections/get-set/get-set', 'can-reflect/reflections/observe/observe', 'can-reflect/reflections/shape/shape', 'can-reflect/reflections/type/type', 'can-reflect/reflections/get-name/get-name', 'can-namespace', 'can-reflect/types/map', 'can-reflect/types/set' ], function (require, exports, module) { var functionReflections = require('can-reflect/reflections/call/call'); var getSet = require('can-reflect/reflections/get-set/get-set'); var observe = require('can-reflect/reflections/observe/observe'); var shape = require('can-reflect/reflections/shape/shape'); var type = require('can-reflect/reflections/type/type'); var getName = require('can-reflect/reflections/get-name/get-name'); var namespace = require('can-namespace'); var reflect = {}; [ functionReflections, getSet, observe, shape, type, getName ].forEach(function (reflections) { for (var prop in reflections) { reflect[prop] = reflections[prop]; if (typeof reflections[prop] === 'function') { var propDescriptor = Object.getOwnPropertyDescriptor(reflections[prop], 'name'); if (!propDescriptor || propDescriptor.writable && propDescriptor.configurable) { Object.defineProperty(reflections[prop], 'name', { value: 'canReflect.' + prop }); } } } }); require('can-reflect/types/map'); require('can-reflect/types/set'); module.exports = namespace.Reflect = reflect; }); /*can-globals@0.3.0#can-globals-proto*/ define('can-globals/can-globals-proto', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var canReflect = require('can-reflect'); function dispatch(key) { var handlers = this.eventHandlers[key]; if (handlers) { var handlersCopy = handlers.slice(); var value = this.getKeyValue(key); for (var i = 0; i < handlersCopy.length; i++) { handlersCopy[i](value); } } } function Globals() { this.eventHandlers = {}; this.properties = {}; } Globals.prototype.define = function (key, value, enableCache) { if (enableCache === undefined) { enableCache = true; } if (!this.properties[key]) { this.properties[key] = { default: value, value: value, enableCache: enableCache }; } return this; }; Globals.prototype.getKeyValue = function (key) { var property = this.properties[key]; if (property) { if (typeof property.value === 'function') { if (property.cachedValue) { return property.cachedValue; } if (property.enableCache) { property.cachedValue = property.value(); return property.cachedValue; } else { return property.value(); } } return property.value; } }; Globals.prototype.makeExport = function (key) { return function (value) { if (arguments.length === 0) { return this.getKeyValue(key); } if (typeof value === 'undefined' || value === null) { this.deleteKeyValue(key); } else { if (typeof value === 'function') { this.setKeyValue(key, function () { return value; }); } else { this.setKeyValue(key, value); } return value; } }.bind(this); }; Globals.prototype.offKeyValue = function (key, handler) { if (this.properties[key]) { var handlers = this.eventHandlers[key]; if (handlers) { var i = handlers.indexOf(handler); handlers.splice(i, 1); } } return this; }; Globals.prototype.onKeyValue = function (key, handler) { if (this.properties[key]) { if (!this.eventHandlers[key]) { this.eventHandlers[key] = []; } this.eventHandlers[key].push(handler); } return this; }; Globals.prototype.deleteKeyValue = function (key) { var property = this.properties[key]; if (property !== undefined) { property.value = property.default; property.cachedValue = undefined; dispatch.call(this, key); } return this; }; Globals.prototype.setKeyValue = function (key, value) { if (!this.properties[key]) { return this.define(key, value); } var property = this.properties[key]; property.value = value; property.cachedValue = undefined; dispatch.call(this, key); return this; }; Globals.prototype.reset = function () { for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { this.properties[key].value = this.properties[key].default; this.properties[key].cachedValue = undefined; dispatch.call(this, key); } } return this; }; canReflect.assignSymbols(Globals.prototype, { 'can.getKeyValue': Globals.prototype.getKeyValue, 'can.setKeyValue': Globals.prototype.setKeyValue, 'can.deleteKeyValue': Globals.prototype.deleteKeyValue, 'can.onKeyValue': Globals.prototype.onKeyValue, 'can.offKeyValue': Globals.prototype.offKeyValue }); module.exports = Globals; }(function () { return this; }(), require, exports, module)); }); /*can-globals@0.3.0#can-globals-instance*/ define('can-globals/can-globals-instance', [ 'require', 'exports', 'module', 'can-namespace', 'can-globals/can-globals-proto' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var namespace = require('can-namespace'); var Globals = require('can-globals/can-globals-proto'); var globals = new Globals(); if (namespace.globals) { throw new Error('You can\'t have two versions of can-globals, check your dependencies'); } else { module.exports = namespace.globals = globals; } }(function () { return this; }(), require, exports, module)); }); /*can-globals@0.3.0#global/global*/ define('can-globals/global/global', [ 'require', 'exports', 'module', 'can-globals/can-globals-instance' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var globals = require('can-globals/can-globals-instance'); globals.define('global', function () { return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope ? self : typeof process === 'object' && {}.toString.call(process) === '[object process]' ? global : window; }); module.exports = globals.makeExport('global'); }(function () { return this; }(), require, exports, module)); }); /*can-globals@0.3.0#document/document*/ define('can-globals/document/document', [ 'require', 'exports', 'module', 'can-globals/global/global', 'can-globals/can-globals-instance' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; require('can-globals/global/global'); var globals = require('can-globals/can-globals-instance'); globals.define('document', function () { return globals.getKeyValue('global').document; }); module.exports = globals.makeExport('document'); }(function () { return this; }(), require, exports, module)); }); /*can-globals@0.3.0#mutation-observer/mutation-observer*/ define('can-globals/mutation-observer/mutation-observer', [ 'require', 'exports', 'module', 'can-globals/global/global', 'can-globals/can-globals-instance' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; require('can-globals/global/global'); var globals = require('can-globals/can-globals-instance'); globals.define('MutationObserver', function () { var GLOBAL = globals.getKeyValue('global'); return GLOBAL.MutationObserver || GLOBAL.WebKitMutationObserver || GLOBAL.MozMutationObserver; }); module.exports = globals.makeExport('MutationObserver'); }(function () { return this; }(), require, exports, module)); }); /*can-cid@1.1.2#helpers*/ define('can-cid/helpers', function (require, exports, module) { module.exports = { each: function (obj, cb, context) { for (var prop in obj) { cb.call(context, obj[prop], prop); } return obj; } }; }); /*can-cid@1.1.2#set/set*/ define('can-cid/set/set', [ 'require', 'exports', 'module', 'can-cid', 'can-cid/helpers' ], function (require, exports, module) { 'use strict'; var getCID = require('can-cid').get; var helpers = require('can-cid/helpers'); var CIDSet; if (typeof Set !== 'undefined') { CIDSet = Set; } else { var CIDSet = function () { this.values = {}; }; CIDSet.prototype.add = function (value) { this.values[getCID(value)] = value; }; CIDSet.prototype['delete'] = function (key) { var has = getCID(key) in this.values; if (has) { delete this.values[getCID(key)]; } return has; }; CIDSet.prototype.forEach = function (cb, thisArg) { helpers.each(this.values, cb, thisArg); }; CIDSet.prototype.has = function (value) { return getCID(value) in this.values; }; CIDSet.prototype.clear = function () { return this.values = {}; }; Object.defineProperty(CIDSet.prototype, 'size', { get: function () { var size = 0; helpers.each(this.values, function () { size++; }); return size; } }); } module.exports = CIDSet; }); /*can-util@3.10.18#dom/mutation-observer/document/document*/ define('can-util/dom/mutation-observer/document/document', [ 'require', 'exports', 'module', 'can-globals/document/document', 'can-dom-data-state', 'can-globals/mutation-observer/mutation-observer', 'can-util/js/each/each', 'can-cid/set/set', 'can-util/js/make-array/make-array', 'can-util/js/string/string' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getDocument = require('can-globals/document/document'); var domDataState = require('can-dom-data-state'); var getMutationObserver = require('can-globals/mutation-observer/mutation-observer'); var each = require('can-util/js/each/each'); var CIDStore = require('can-cid/set/set'); var makeArray = require('can-util/js/make-array/make-array'); var string = require('can-util/js/string/string'); var dispatchIfListening = function (mutatedNode, nodes, dispatched) { if (dispatched.has(mutatedNode)) { return true; } dispatched.add(mutatedNode); if (nodes.name === 'removedNodes') { var documentElement = getDocument().documentElement; if (documentElement.contains(mutatedNode)) { return; } } nodes.handlers.forEach(function (handler) { handler(mutatedNode); }); nodes.afterHandlers.forEach(function (handler) { handler(mutatedNode); }); }; var mutationObserverDocument = { add: function (handler) { var MO = getMutationObserver(); if (MO) { var documentElement = getDocument().documentElement; var globalObserverData = domDataState.get.call(documentElement, 'globalObserverData'); if (!globalObserverData) { var observer = new MO(function (mutations) { globalObserverData.handlers.forEach(function (handler) { handler(mutations); }); }); observer.observe(documentElement, { childList: true, subtree: true }); globalObserverData = { observer: observer, handlers: [] }; domDataState.set.call(documentElement, 'globalObserverData', globalObserverData); } globalObserverData.handlers.push(handler); } }, remove: function (handler) { var documentElement = getDocument().documentElement; var globalObserverData = domDataState.get.call(documentElement, 'globalObserverData'); if (globalObserverData) { var index = globalObserverData.handlers.indexOf(handler); if (index >= 0) { globalObserverData.handlers.splice(index, 1); } if (globalObserverData.handlers.length === 0) { globalObserverData.observer.disconnect(); domDataState.clean.call(documentElement, 'globalObserverData'); } } } }; var makeMutationMethods = function (name) { var mutationName = name.toLowerCase() + 'Nodes'; var getMutationData = function () { var documentElement = getDocument().documentElement; var mutationData = domDataState.get.call(documentElement, mutationName + 'MutationData'); if (!mutationData) { mutationData = { name: mutationName, handlers: [], afterHandlers: [], hander: null }; if (getMutationObserver()) { domDataState.set.call(documentElement, mutationName + 'MutationData', mutationData); } } return mutationData; }; var setup = function () { var mutationData = getMutationData(); if (mutationData.handlers.length === 0 || mutationData.afterHandlers.length === 0) { mutationData.handler = function (mutations) { var dispatched = new CIDStore(); mutations.forEach(function (mutation) { each(mutation[mutationName], function (mutatedNode) { var children = mutatedNode.getElementsByTagName && makeArray(mutatedNode.getElementsByTagName('*')); var alreadyChecked = dispatchIfListening(mutatedNode, mutationData, dispatched); if (children && !alreadyChecked) { for (var j = 0, child; (child = children[j]) !== undefined; j++) { dispatchIfListening(child, mutationData, dispatched); } } }); }); }; this.add(mutationData.handler); } return mutationData; }; var teardown = function () { var documentElement = getDocument().documentElement; var mutationData = getMutationData(); if (mutationData.handlers.length === 0 && mutationData.afterHandlers.length === 0) { this.remove(mutationData.handler); domDataState.clean.call(documentElement, mutationName + 'MutationData'); } }; var createOnOffHandlers = function (name, handlerList) { mutationObserverDocument['on' + name] = function (handler) { var mutationData = setup.call(this); mutationData[handlerList].push(handler); }; mutationObserverDocument['off' + name] = function (handler) { var mutationData = getMutationData(); var index = mutationData[handlerList].indexOf(handler); if (index >= 0) { mutationData[handlerList].splice(index, 1); } teardown.call(this); }; }; var createHandlers = function (name) { createOnOffHandlers(name, 'handlers'); createOnOffHandlers('After' + name, 'afterHandlers'); }; createHandlers(string.capitalize(mutationName)); }; makeMutationMethods('added'); makeMutationMethods('removed'); module.exports = mutationObserverDocument; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/data/data*/ define('can-util/dom/data/data', [ 'require', 'exports', 'module', 'can-dom-data-state', 'can-util/dom/mutation-observer/document/document' ], function (require, exports, module) { 'use strict'; var domDataState = require('can-dom-data-state'); var mutationDocument = require('can-util/dom/mutation-observer/document/document'); var elementSetCount = 0; var deleteNode = function () { elementSetCount -= 1; return domDataState.delete.call(this); }; var cleanupDomData = function (node) { if (domDataState.get.call(node) !== undefined) { deleteNode.call(node); } if (elementSetCount === 0) { mutationDocument.offAfterRemovedNodes(cleanupDomData); } }; module.exports = { getCid: domDataState.getCid, cid: domDataState.cid, expando: domDataState.expando, clean: domDataState.clean, get: domDataState.get, set: function (name, value) { if (elementSetCount === 0) { mutationDocument.onAfterRemovedNodes(cleanupDomData); } elementSetCount += domDataState.get.call(this) ? 0 : 1; domDataState.set.call(this, name, value); }, delete: deleteNode, _getElementSetCount: function () { return elementSetCount; } }; }); /*can-util@3.10.18#dom/class-name/class-name*/ define('can-util/dom/class-name/class-name', function (require, exports, module) { 'use strict'; var has = function (className) { if (this.classList) { return this.classList.contains(className); } else { return !!this.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')); } }; module.exports = { has: has, add: function (className) { if (this.classList) { this.classList.add(className); } else if (!has.call(this, className)) { this.className += ' ' + className; } }, remove: function (className) { if (this.classList) { this.classList.remove(className); } else if (has.call(this, className)) { var reg = new RegExp('(\\s|^)' + className + '(\\s|$)'); this.className = this.className.replace(reg, ' '); } } }; }); /*can-globals@0.3.0#is-node/is-node*/ define('can-globals/is-node/is-node', [ 'require', 'exports', 'module', 'can-globals/can-globals-instance' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var globals = require('can-globals/can-globals-instance'); globals.define('isNode', function () { return typeof process === 'object' && {}.toString.call(process) === '[object process]'; }); module.exports = globals.makeExport('isNode'); }(function () { return this; }(), require, exports, module)); }); /*can-globals@0.3.0#is-browser-window/is-browser-window*/ define('can-globals/is-browser-window/is-browser-window', [ 'require', 'exports', 'module', 'can-globals/can-globals-instance', 'can-globals/is-node/is-node' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var globals = require('can-globals/can-globals-instance'); require('can-globals/is-node/is-node'); globals.define('isBrowserWindow', function () { var isNode = globals.getKeyValue('isNode'); return typeof window !== 'undefined' && typeof document !== 'undefined' && isNode === false; }); module.exports = globals.makeExport('isBrowserWindow'); }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/events/events*/ define('can-util/dom/events/events', [ 'require', 'exports', 'module', 'can-globals/document/document', 'can-globals/is-browser-window/is-browser-window', 'can-util/js/is-plain-object/is-plain-object', 'can-log/dev/dev' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getDocument = require('can-globals/document/document'); var isBrowserWindow = require('can-globals/is-browser-window/is-browser-window'); var isPlainObject = require('can-util/js/is-plain-object/is-plain-object'); var fixSyntheticEventsOnDisabled = false; var dev = require('can-log/dev/dev'); function isDispatchingOnDisabled(element, ev) { var isInsertedOrRemoved = isPlainObject(ev) ? ev.type === 'inserted' || ev.type === 'removed' : ev === 'inserted' || ev === 'removed'; var isDisabled = !!element.disabled; return isInsertedOrRemoved && isDisabled; } module.exports = { addEventListener: function () { this.addEventListener.apply(this, arguments); }, removeEventListener: function () { this.removeEventListener.apply(this, arguments); }, canAddEventListener: function () { return this.nodeName && (this.nodeType === 1 || this.nodeType === 9) || this === window; }, dispatch: function (event, args, bubbles) { var ret; var dispatchingOnDisabled = fixSyntheticEventsOnDisabled && isDispatchingOnDisabled(this, event); var doc = this.ownerDocument || getDocument(); var ev = doc.createEvent('HTMLEvents'); var isString = typeof event === 'string'; ev.initEvent(isString ? event : event.type, bubbles === undefined ? true : bubbles, false); if (!isString) { for (var prop in event) { if (ev[prop] === undefined) { ev[prop] = event[prop]; } } } if (this.disabled === true && ev.type !== 'fix_synthetic_events_on_disabled_test') { dev.warn('can-util/dom/events::dispatch: Dispatching a synthetic event on a disabled is ' + 'problematic in FireFox and Internet Explorer. We recommend avoiding this if at ' + 'all possible. see https://github.com/canjs/can-util/issues/294'); } ev.args = args; if (dispatchingOnDisabled) { this.disabled = false; } ret = this.dispatchEvent(ev); if (dispatchingOnDisabled) { this.disabled = true; } return ret; } }; (function () { if (!isBrowserWindow()) { return; } var testEventName = 'fix_synthetic_events_on_disabled_test'; var input = document.createElement('input'); input.disabled = true; var timer = setTimeout(function () { fixSyntheticEventsOnDisabled = true; }, 50); var onTest = function onTest() { clearTimeout(timer); module.exports.removeEventListener.call(input, testEventName, onTest); }; module.exports.addEventListener.call(input, testEventName, onTest); try { module.exports.dispatch.call(input, testEventName, [], false); } catch (e) { onTest(); fixSyntheticEventsOnDisabled = true; } }()); }(function () { return this; }(), require, exports, module)); }); /*can-observation-recorder@0.1.3#can-observation-recorder*/ define('can-observation-recorder', [ 'require', 'exports', 'module', 'can-namespace' ], function (require, exports, module) { var namespace = require('can-namespace'); var stack = []; var ObservationRecorder = { stack: stack, start: function () { stack.push({ keyDependencies: new Map(), valueDependencies: new Set(), traps: null, ignore: 0 }); }, stop: function () { return stack.pop(); }, add: function (obj, event) { var top = stack[stack.length - 1]; if (top && top.ignore === 0) { if (top.traps) { top.traps.push([ obj, event ]); } else { if (event === undefined) { top.valueDependencies.add(obj); } else { var eventSet = top.keyDependencies.get(obj); if (!eventSet) { eventSet = new Set(); top.keyDependencies.set(obj, eventSet); } eventSet.add(event); } } } }, addMany: function (observes) { var top = stack[stack.length - 1]; if (top) { if (top.traps) { top.traps.push.apply(top.traps, observes); } else { for (var i = 0, len = observes.length; i < len; i++) { this.add(observes[i][0], observes[i][1]); } } } }, ignore: function (fn) { return function () { if (stack.length) { var top = stack[stack.length - 1]; top.ignore++; var res = fn.apply(this, arguments); top.ignore--; return res; } else { return fn.apply(this, arguments); } }; }, isRecording: function () { var len = stack.length; var last = len && stack[len - 1]; return last && last.ignore === 0 && last; }, makeDependenciesRecord: function () { return { traps: null, keyDependencies: new Map(), valueDependencies: new Set(), ignore: 0 }; }, makeDependenciesRecorder: function () { return ObservationRecorder.makeDependenciesRecord(); }, trap: function () { if (stack.length) { var top = stack[stack.length - 1]; var oldTraps = top.traps; var traps = top.traps = []; return function () { top.traps = oldTraps; return traps; }; } else { return function () { return []; }; } }, trapsCount: function () { if (stack.length) { var top = stack[stack.length - 1]; return top.traps.length; } else { return 0; } } }; if (namespace.ObservationRecorder) { throw new Error('You can\'t have two versions of can-observation-recorder, check your dependencies'); } else { module.exports = namespace.ObservationRecorder = ObservationRecorder; } }); /*can-util@3.10.18#js/is-promise-like/is-promise-like*/ define('can-util/js/is-promise-like/is-promise-like', function (require, exports, module) { 'use strict'; module.exports = function (obj) { return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; }; }); /*can-queues@0.3.1#queue-state*/ define('can-queues/queue-state', function (require, exports, module) { module.exports = { lastTask: null }; }); /*can-queues@0.3.1#queue*/ define('can-queues/queue', [ 'require', 'exports', 'module', 'can-queues/queue-state', 'can-log/dev/dev', 'can-assign' ], function (require, exports, module) { var queueState = require('can-queues/queue-state'); var canDev = require('can-log/dev/dev'); var assign = require('can-assign'); function noOperation() { } var Queue = function (name, callbacks) { this.callbacks = assign({ onFirstTask: noOperation, onComplete: function () { queueState.lastTask = null; } }, callbacks || {}); this.name = name; this.index = 0; this.tasks = []; this._log = false; }; Queue.prototype.constructor = Queue; Queue.noop = noOperation; Queue.prototype.enqueue = function (fn, context, args, meta) { var len = this.tasks.push({ fn: fn, context: context, args: args, meta: meta || {} }); this._logEnqueue(this.tasks[len - 1]); if (len === 1) { this.callbacks.onFirstTask(this); } }; Queue.prototype.flush = function () { while (this.index < this.tasks.length) { var task = this.tasks[this.index++]; this._logFlush(task); task.fn.apply(task.context, task.args); } this.index = 0; this.tasks = []; this.callbacks.onComplete(this); }; Queue.prototype.log = function () { this._log = arguments.length ? arguments[0] : true; }; Queue.prototype._logEnqueue = function (task) { task.meta.parentTask = queueState.lastTask; task.meta.stack = this; if (this._log === true || this._log === 'enqueue') { var log = task.meta.log ? task.meta.log.concat(task) : [ task.fn.name, task ]; canDev.log.apply(canDev, [this.name + ' enqueuing:'].concat(log)); } }; Queue.prototype._logFlush = function (task) { if (this._log === true || this._log === 'flush') { var log = task.meta.log ? task.meta.log.concat(task) : [ task.fn.name, task ]; canDev.log.apply(canDev, [this.name + ' running :'].concat(log)); } queueState.lastTask = task; }; module.exports = Queue; }); /*can-queues@0.3.1#priority-queue*/ define('can-queues/priority-queue', [ 'require', 'exports', 'module', 'can-queues/queue' ], function (require, exports, module) { var Queue = require('can-queues/queue'); var PriorityQueue = function () { Queue.apply(this, arguments); this.taskMap = new Map(); this.taskContainersByPriority = []; this.curPriorityIndex = Infinity; this.curPriorityMax = 0; this.isFlushing = false; this.tasksRemaining = 0; }; PriorityQueue.prototype = Object.create(Queue.prototype); PriorityQueue.prototype.constructor = PriorityQueue; PriorityQueue.prototype.enqueue = function (fn, context, args, meta) { if (!this.taskMap.has(fn)) { this.tasksRemaining++; var isFirst = this.taskContainersByPriority.length === 0; var task = { fn: fn, context: context, args: args, meta: meta || {} }; var taskContainer = this.getTaskContainerAndUpdateRange(task); taskContainer.tasks.push(task); this.taskMap.set(fn, task); this._logEnqueue(task); if (isFirst) { this.callbacks.onFirstTask(this); } } }; PriorityQueue.prototype.getTaskContainerAndUpdateRange = function (task) { var priority = task.meta.priority || 0; if (priority < this.curPriorityIndex) { this.curPriorityIndex = priority; } if (priority > this.curPriorityMax) { this.curPriorityMax = priority; } var tcByPriority = this.taskContainersByPriority; var taskContainer = tcByPriority[priority]; if (!taskContainer) { taskContainer = tcByPriority[priority] = { tasks: [], index: 0 }; } return taskContainer; }; PriorityQueue.prototype.flush = function () { if (this.isFlushing) { return; } this.isFlushing = true; while (true) { if (this.curPriorityIndex <= this.curPriorityMax) { var taskContainer = this.taskContainersByPriority[this.curPriorityIndex]; if (taskContainer && taskContainer.tasks.length > taskContainer.index) { var task = taskContainer.tasks[taskContainer.index++]; this._logFlush(task); this.tasksRemaining--; this.taskMap['delete'](task.fn); task.fn.apply(task.context, task.args); } else { this.curPriorityIndex++; } } else { this.taskMap = new Map(); this.curPriorityIndex = Infinity; this.curPriorityMax = 0; this.taskContainersByPriority = []; this.isFlushing = false; this.callbacks.onComplete(this); return; } } }; PriorityQueue.prototype.isEnqueued = function (fn) { return this.taskMap.has(fn); }; PriorityQueue.prototype.flushQueuedTask = function (fn) { var task = this.taskMap.get(fn); if (task) { var priority = task.meta.priority || 0; var taskContainer = this.taskContainersByPriority[priority]; var index = taskContainer.tasks.indexOf(task, taskContainer.index); if (index >= 0) { taskContainer.tasks.splice(index, 1); this._logFlush(task); this.tasksRemaining--; this.taskMap['delete'](task.fn); task.fn.apply(task.context, task.args); } } }; PriorityQueue.prototype.tasksRemainingCount = function () { return this.tasksRemaining; }; module.exports = PriorityQueue; }); /*can-queues@0.3.1#completion-queue*/ define('can-queues/completion-queue', [ 'require', 'exports', 'module', 'can-queues/queue' ], function (require, exports, module) { var Queue = require('can-queues/queue'); var CompletionQueue = function () { Queue.apply(this, arguments); this.flushCount = 0; }; CompletionQueue.prototype = Object.create(Queue.prototype); CompletionQueue.prototype.constructor = CompletionQueue; CompletionQueue.prototype.flush = function () { if (this.flushCount === 0) { this.flushCount++; while (this.index < this.tasks.length) { var task = this.tasks[this.index++]; this._logFlush(task); task.fn.apply(task.context, task.args); } this.index = 0; this.tasks = []; this.flushCount--; this.callbacks.onComplete(this); } }; module.exports = CompletionQueue; }); /*can-queues@0.3.1#can-queues*/ define('can-queues', [ 'require', 'exports', 'module', 'can-util/js/dev/dev', 'can-queues/queue', 'can-queues/priority-queue', 'can-queues/queue-state', 'can-queues/completion-queue', 'can-namespace' ], function (require, exports, module) { var canDev = require('can-util/js/dev/dev'); var Queue = require('can-queues/queue'); var PriorityQueue = require('can-queues/priority-queue'); var queueState = require('can-queues/queue-state'); var CompletionQueue = require('can-queues/completion-queue'); var ns = require('can-namespace'); var batchStartCounter = 0; var addedTask = false; var isFlushing = false; var batchNum = 0; var batchData; var queueNames = [ 'notify', 'derive', 'domUI', 'mutate' ]; var NOTIFY_QUEUE, DERIVE_QUEUE, DOM_UI_QUEUE, MUTATE_QUEUE; NOTIFY_QUEUE = new Queue('NOTIFY', { onComplete: function () { DERIVE_QUEUE.flush(); }, onFirstTask: function () { if (!batchStartCounter) { NOTIFY_QUEUE.flush(); } else { addedTask = true; } } }); DERIVE_QUEUE = new PriorityQueue('DERIVE', { onComplete: function () { DOM_UI_QUEUE.flush(); }, onFirstTask: function () { addedTask = true; } }); DOM_UI_QUEUE = new CompletionQueue('DOM_UI', { onComplete: function () { MUTATE_QUEUE.flush(); }, onFirstTask: function () { addedTask = true; } }); MUTATE_QUEUE = new Queue('MUTATE', { onComplete: function () { queueState.lastTask = null; isFlushing = false; }, onFirstTask: function () { addedTask = true; } }); var queues = { Queue: Queue, PriorityQueue: PriorityQueue, CompletionQueue: CompletionQueue, notifyQueue: NOTIFY_QUEUE, deriveQueue: DERIVE_QUEUE, domUIQueue: DOM_UI_QUEUE, mutateQueue: MUTATE_QUEUE, batch: { start: function () { batchStartCounter++; if (batchStartCounter === 1) { batchNum++; batchData = { number: batchNum }; } }, stop: function () { batchStartCounter--; if (batchStartCounter === 0) { if (addedTask) { addedTask = false; isFlushing = true; NOTIFY_QUEUE.flush(); } } }, isCollecting: function () { return batchStartCounter > 0; }, number: function () { return batchNum; }, data: function () { return batchData; } }, enqueueByQueue: function enqueueByQueue(fnByQueue, context, args, makeMeta, reasonLog) { if (fnByQueue) { queues.batch.start(); queueNames.forEach(function (queueName) { var name = queueName + 'Queue'; var QUEUE = queues[name]; var tasks = fnByQueue[queueName]; if (tasks !== undefined) { tasks.forEach(function (fn) { var meta = makeMeta != null ? makeMeta(fn, context, args) : {}; meta.reasonLog = reasonLog; QUEUE.enqueue(fn, context, args, meta); }); } }); queues.batch.stop(); } }, stack: function () { var current = queueState.lastTask; var stack = []; while (current) { stack.unshift(current); current = current.meta.parentTask; } return stack; }, logStack: function () { var stack = this.stack(); stack.forEach(function (task, i) { var meta = task.meta; if (i === 0 && meta && meta.reasonLog) { canDev.log.apply(canDev, meta.reasonLog); } var log = meta && meta.log ? meta.log : [ task.fn.name, task ]; canDev.log.apply(canDev, [task.meta.stack.name + ' ran task:'].concat(log)); }); }, taskCount: function () { console.warn('THIS IS NOT USED RIGHT?'); return NOTIFY_QUEUE.tasks.length + DERIVE_QUEUE.tasks.length + DOM_UI_QUEUE.tasks.length + MUTATE_QUEUE.tasks.length; }, flush: function () { NOTIFY_QUEUE.flush(); }, log: function () { NOTIFY_QUEUE.log.apply(NOTIFY_QUEUE, arguments); DERIVE_QUEUE.log.apply(DERIVE_QUEUE, arguments); DOM_UI_QUEUE.log.apply(DOM_UI_QUEUE, arguments); MUTATE_QUEUE.log.apply(MUTATE_QUEUE, arguments); } }; if (ns.queues) { throw new Error('You can\'t have two versions of can-queues, check your dependencies'); } else { module.exports = ns.queues = queues; } }); /*can-key-tree@0.1.2#can-key-tree*/ define('can-key-tree', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var reflect = require('can-reflect'); function isBuiltInPrototype(obj) { if (obj === Object.prototype) { return true; } var protoString = Object.prototype.toString.call(obj); var isNotObjObj = protoString !== '[object Object]'; var isObjSomething = protoString.indexOf('[object ') !== -1; return isNotObjObj && isObjSomething; } function getDeepSize(root, level) { if (level === 0) { return reflect.size(root); } else if (reflect.size(root) === 0) { return 0; } else { var count = 0; reflect.each(root, function (value) { count += getDeepSize(value, level - 1); }); return count; } } function getDeep(node, items, depth, maxDepth) { if (!node) { return; } if (maxDepth === depth) { if (reflect.isMoreListLikeThanMapLike(node)) { reflect.addValues(items, reflect.toArray(node)); } else { throw new Error('can-key-tree: Map-type leaf containers are not supported yet.'); } } else { reflect.each(node, function (value) { getDeep(value, items, depth + 1, maxDepth); }); } } function clearDeep(node, depth, maxDepth) { if (maxDepth === depth) { if (reflect.isMoreListLikeThanMapLike(node)) { reflect.removeValues(node, reflect.toArray(node)); } else { throw new Error('can-key-tree: Map-type leaf containers are not supported yet.'); } } else { reflect.each(node, function (value, key) { clearDeep(value, depth + 1, maxDepth); reflect.deleteKeyValue(node, key); }); } } var KeyTree = function (treeStructure, callbacks) { this.callbacks = callbacks || {}; this.treeStructure = treeStructure; var FirstConstructor = treeStructure[0]; if (reflect.isConstructorLike(FirstConstructor)) { this.root = new FirstConstructor(); } else { this.root = FirstConstructor; } }; reflect.assign(KeyTree.prototype, { add: function (keys) { if (keys.length > this.treeStructure.length) { throw new Error('can-key-tree: Can not add path deeper than tree.'); } var place = this.root; var rootWasEmpty = reflect.size(this.root) === 0; for (var i = 0; i < keys.length - 1; i++) { var key = keys[i]; var childNode = reflect.getKeyValue(place, key); if (!childNode) { var Constructor = this.treeStructure[i + 1]; if (isBuiltInPrototype(Constructor.prototype)) { childNode = new Constructor(); } else { childNode = new Constructor(key); } reflect.setKeyValue(place, key, childNode); } place = childNode; } if (reflect.isMoreListLikeThanMapLike(place)) { reflect.addValues(place, [keys[keys.length - 1]]); } else { throw new Error('can-key-tree: Map types are not supported yet.'); } if (rootWasEmpty && this.callbacks.onFirst) { this.callbacks.onFirst.call(this); } return this; }, getNode: function (keys) { var node = this.root; for (var i = 0; i < keys.length; i++) { var key = keys[i]; node = reflect.getKeyValue(node, key); if (!node) { return; } } return node; }, get: function (keys) { var node = this.getNode(keys); if (this.treeStructure.length === keys.length) { return node; } else { var Type = this.treeStructure[this.treeStructure.length - 1]; var items = new Type(); getDeep(node, items, keys.length, this.treeStructure.length - 1); return items; } }, delete: function (keys) { var parentNode = this.root, path = [this.root], lastKey = keys[keys.length - 1]; for (var i = 0; i < keys.length - 1; i++) { var key = keys[i]; var childNode = reflect.getKeyValue(parentNode, key); if (childNode === undefined) { return false; } else { path.push(childNode); } parentNode = childNode; } if (!keys.length) { clearDeep(parentNode, 0, this.treeStructure.length - 1); } else if (keys.length === this.treeStructure.length) { if (reflect.isMoreListLikeThanMapLike(parentNode)) { reflect.removeValues(parentNode, [lastKey]); } else { throw new Error('can-key-tree: Map types are not supported yet.'); } } else { var nodeToRemove = reflect.getKeyValue(parentNode, lastKey); if (nodeToRemove !== undefined) { clearDeep(nodeToRemove, keys.length, this.treeStructure.length - 1); reflect.deleteKeyValue(parentNode, lastKey); } else { return false; } } for (i = path.length - 2; i >= 0; i--) { if (reflect.size(parentNode) === 0) { parentNode = path[i]; reflect.deleteKeyValue(parentNode, keys[i]); } else { break; } } if (this.callbacks.onEmpty && reflect.size(this.root) === 0) { this.callbacks.onEmpty.call(this); } return true; }, size: function () { return getDeepSize(this.root, this.treeStructure.length - 1); } }); module.exports = KeyTree; }); /*can-reflect-promise@2.0.0-pre.5#can-reflect-promise*/ define('can-reflect-promise', [ 'require', 'exports', 'module', 'can-reflect', 'can-symbol', 'can-observation-recorder', 'can-queues', 'can-key-tree', 'can-util/js/dev/dev' ], function (require, exports, module) { var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var ObservationRecorder = require('can-observation-recorder'); var queues = require('can-queues'); var KeyTree = require('can-key-tree'); var dev = require('can-util/js/dev/dev'); var getKeyValueSymbol = canSymbol.for('can.getKeyValue'), observeDataSymbol = canSymbol.for('can.meta'); var promiseDataPrototype = { isPending: true, state: 'pending', isResolved: false, isRejected: false, value: undefined, reason: undefined }; function setVirtualProp(promise, property, value) { var observeData = promise[observeDataSymbol]; var old = observeData[property]; observeData[property] = value; queues.enqueueByQueue(observeData.handlers.getNode([property]), promise, [ value, old ], function () { return {}; }, [ 'Promise', promise, 'resolved with value', value, 'and changed virtual property: ' + property ]); } function initPromise(promise) { var observeData = promise[observeDataSymbol]; if (!observeData) { Object.defineProperty(promise, observeDataSymbol, { enumerable: false, configurable: false, writable: false, value: Object.create(promiseDataPrototype) }); observeData = promise[observeDataSymbol]; observeData.handlers = new KeyTree([ Object, Object, Array ]); } promise.then(function (value) { queues.batch.start(); setVirtualProp(promise, 'isPending', false); setVirtualProp(promise, 'isResolved', true); setVirtualProp(promise, 'value', value); setVirtualProp(promise, 'state', 'resolved'); queues.batch.stop(); }, function (reason) { queues.batch.start(); setVirtualProp(promise, 'isPending', false); setVirtualProp(promise, 'isRejected', true); setVirtualProp(promise, 'reason', reason); setVirtualProp(promise, 'state', 'rejected'); queues.batch.stop(); dev.error('Failed promise:', reason); }); } function setupPromise(value) { var oldPromiseFn; var proto = 'getPrototypeOf' in Object ? Object.getPrototypeOf(value) : value.__proto__; if (value[getKeyValueSymbol] && value[observeDataSymbol]) { return; } if (proto === null || proto === Object.prototype) { proto = value; if (typeof proto.promise === 'function') { oldPromiseFn = proto.promise; proto.promise = function () { var result = oldPromiseFn.call(proto); setupPromise(result); return result; }; } } canReflect.assignSymbols(proto, { 'can.getKeyValue': function (key) { if (!this[observeDataSymbol]) { initPromise(this); } ObservationRecorder.add(this, key); switch (key) { case 'state': case 'isPending': case 'isResolved': case 'isRejected': case 'value': case 'reason': return this[observeDataSymbol][key]; default: return this[key]; } }, 'can.getValue': function () { return this[getKeyValueSymbol]('value'); }, 'can.isValueLike': false, 'can.onKeyValue': function (key, handler, queue) { if (!this[observeDataSymbol]) { initPromise(this); } this[observeDataSymbol].handlers.add([ key, queue || 'mutate', handler ]); }, 'can.offKeyValue': function (key, handler, queue) { if (!this[observeDataSymbol]) { initPromise(this); } this[observeDataSymbol].handlers.delete([ key, queue || 'mutate', handler ]); } }); } module.exports = setupPromise; }); /*can-stache-key@1.0.0-pre.15#can-stache-key*/ define('can-stache-key', [ 'require', 'exports', 'module', 'can-observation-recorder', 'can-log/dev/dev', 'can-util/js/each/each', 'can-symbol', 'can-reflect', 'can-util/js/is-promise-like/is-promise-like', 'can-reflect-promise' ], function (require, exports, module) { var ObservationRecorder = require('can-observation-recorder'); var dev = require('can-log/dev/dev'); var each = require('can-util/js/each/each'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var isPromiseLike = require('can-util/js/is-promise-like/is-promise-like'); var canReflectPromise = require('can-reflect-promise'); var getValueSymbol = canSymbol.for('can.getValue'); var setValueSymbol = canSymbol.for('can.setValue'); var isValueLikeSymbol = canSymbol.for('can.isValueLike'); var peek = ObservationRecorder.ignore(canReflect.getKeyValue.bind(canReflect)); var observeReader; var bindName = Function.prototype.bind; bindName = function (source) { var fn = Function.prototype.bind.call(this, source); Object.defineProperty(fn, 'name', { value: canReflect.getName(source) + '.' + canReflect.getName(this) }); return fn; }; var isAt = function (index, reads) { var prevRead = reads[index - 1]; return prevRead && prevRead.at; }; var readValue = function (value, index, reads, options, state, prev) { var usedValueReader; do { usedValueReader = false; for (var i = 0, len = observeReader.valueReaders.length; i < len; i++) { if (observeReader.valueReaders[i].test(value, index, reads, options)) { value = observeReader.valueReaders[i].read(value, index, reads, options, state, prev); } } } while (usedValueReader); return value; }; var specialRead = { index: true, key: true, event: true, element: true, viewModel: true }; var checkForObservableAndNotify = function (options, state, getObserves, value, index) { if (options.foundObservable && !state.foundObservable) { if (ObservationRecorder.trapsCount()) { ObservationRecorder.addMany(getObserves()); options.foundObservable(value, index); state.foundObservable = true; } } }; observeReader = { read: function (parent, reads, options) { options = options || {}; var state = { foundObservable: false }; var getObserves; if (options.foundObservable) { getObserves = ObservationRecorder.trap(); } var cur = readValue(parent, 0, reads, options, state), type, prev, readLength = reads.length, i = 0, last; checkForObservableAndNotify(options, state, getObserves, parent, 0); while (i < readLength) { prev = cur; for (var r = 0, readersLength = observeReader.propertyReaders.length; r < readersLength; r++) { var reader = observeReader.propertyReaders[r]; if (reader.test(cur)) { cur = reader.read(cur, reads[i], i, options, state); break; } } checkForObservableAndNotify(options, state, getObserves, prev, i); last = cur; i = i + 1; cur = readValue(cur, i, reads, options, state, prev); checkForObservableAndNotify(options, state, getObserves, prev, i - 1); type = typeof cur; if (i < reads.length && (cur === null || cur === undefined)) { if (options.earlyExit) { options.earlyExit(prev, i - 1, cur); } return { value: undefined, parent: prev }; } } if (cur === undefined) { if (options.earlyExit) { options.earlyExit(prev, i - 1); } } return { value: cur, parent: prev }; }, get: function (parent, reads, options) { return observeReader.read(parent, observeReader.reads(reads), options || {}).value; }, valueReadersMap: {}, valueReaders: [ { name: 'function', test: function (value) { return value && canReflect.isFunctionLike(value) && !canReflect.isConstructorLike(value); }, read: function (value, i, reads, options, state, prev) { if (options.callMethodsOnObservables && canReflect.isObservableLike(prev) && canReflect.isMapLike(prev)) { dev.warn('can-stache-key: read() called with `callMethodsOnObservables: true`.'); return value.apply(prev, options.args || []); } return options.proxyMethods !== false ? bindName.call(value, prev) : value; } }, { name: 'isValueLike', test: function (value, i, reads, options) { return value && value[getValueSymbol] && value[isValueLikeSymbol] !== false && (options.foundAt || !isAt(i, reads)); }, read: function (value, i, reads, options) { if (options.readCompute === false && i === reads.length) { return value; } return canReflect.getValue(value); }, write: function (base, newVal) { if (base[setValueSymbol]) { base[setValueSymbol](newVal); } else if (base.set) { base.set(newVal); } else { base(newVal); } } } ], propertyReadersMap: {}, propertyReaders: [ { name: 'map', test: function (value) { if (isPromiseLike(value) || typeof value === 'object' && value && typeof value.then === 'function') { canReflectPromise(value); } return canReflect.isObservableLike(value) && canReflect.isMapLike(value); }, read: function (value, prop) { var res = canReflect.getKeyValue(value, prop.key); if (res !== undefined) { return res; } else { return value[prop.key]; } }, write: canReflect.setKeyValue }, { name: 'object', test: function () { return true; }, read: function (value, prop, i, options) { if (value == null) { return undefined; } else { if (typeof value === 'object') { if (prop.key in value) { return value[prop.key]; } else if (prop.at && specialRead[prop.key] && '@' + prop.key in value) { options.foundAt = true; dev.warn('Use %' + prop.key + ' in place of @' + prop.key + '.'); return value['@' + prop.key]; } } else { return value[prop.key]; } } }, write: function (base, prop, newVal) { var propValue = base[prop]; if (canReflect.isMapLike(propValue) && newVal && typeof newVal === 'object') { dev.warn('can-stache-key: Merging data into "' + prop + '" because its parent is non-observable'); canReflect.update(propValue, newVal); } else if (canReflect.isValueLike(propValue) && canReflect.isObservableLike(propValue)) { canReflect.setValue(propValue, newVal); } else { base[prop] = newVal; } } } ], reads: function (keyArg) { var key = '' + keyArg; var keys = []; var last = 0; var at = false; if (key.charAt(0) === '@') { last = 1; at = true; } var keyToAdd = ''; for (var i = last; i < key.length; i++) { var character = key.charAt(i); if (character === '.' || character === '@') { if (key.charAt(i - 1) !== '\\') { keys.push({ key: keyToAdd, at: at }); at = character === '@'; keyToAdd = ''; } else { keyToAdd = keyToAdd.substr(0, keyToAdd.length - 1) + '.'; } } else { keyToAdd += character; } } keys.push({ key: keyToAdd, at: at }); return keys; }, write: function (parent, key, value, options) { var keys = typeof key === 'string' ? observeReader.reads(key) : key; var last; options = options || {}; if (keys.length > 1) { last = keys.pop(); parent = observeReader.read(parent, keys, options).value; keys.push(last); } else { last = keys[0]; } var keyValue = peek(parent, last.key); if (observeReader.valueReadersMap.isValueLike.test(keyValue, keys.length - 1, keys, options)) { observeReader.valueReadersMap.isValueLike.write(keyValue, value, options); } else { if (observeReader.valueReadersMap.isValueLike.test(parent, keys.length - 1, keys, options)) { parent = parent[getValueSymbol](); } if (observeReader.propertyReadersMap.map.test(parent)) { observeReader.propertyReadersMap.map.write(parent, last.key, value, options); } else if (observeReader.propertyReadersMap.object.test(parent)) { observeReader.propertyReadersMap.object.write(parent, last.key, value, options); if (options.observation) { options.observation.update(); } } } } }; each(observeReader.propertyReaders, function (reader) { observeReader.propertyReadersMap[reader.name] = reader; }); each(observeReader.valueReaders, function (reader) { observeReader.valueReadersMap[reader.name] = reader; }); observeReader.set = observeReader.write; module.exports = observeReader; }); /*can-event-queue@0.13.1#value/merge-dependency-records*/ define('can-event-queue/value/merge-dependency-records', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var canReflect = require('can-reflect'); var mergeValueDependencies = function mergeValueDependencies(obj, source) { var sourceValueDeps = source.valueDependencies; if (sourceValueDeps) { var destValueDeps = obj.valueDependencies; if (!destValueDeps) { destValueDeps = new Set(); obj.valueDependencies = destValueDeps; } canReflect.eachIndex(sourceValueDeps, function (dep) { destValueDeps.add(dep); }); } }; var mergeKeyDependencies = function mergeKeyDependencies(obj, source) { var sourcekeyDeps = source.keyDependencies; if (sourcekeyDeps) { var destKeyDeps = obj.keyDependencies; if (!destKeyDeps) { destKeyDeps = new Map(); obj.keyDependencies = destKeyDeps; } canReflect.eachKey(sourcekeyDeps, function (keys, obj) { var entry = destKeyDeps.get(obj); if (!entry) { entry = new Set(); destKeyDeps.set(obj, entry); } canReflect.eachIndex(keys, function (key) { entry.add(key); }); }); } }; module.exports = function mergeDependencyRecords(object, source) { mergeKeyDependencies(object, source); mergeValueDependencies(object, source); return object; }; }); /*can-define-lazy-value@1.0.1#define-lazy-value*/ define('can-define-lazy-value', function (require, exports, module) { module.exports = function defineLazyValue(obj, prop, initializer, writable) { Object.defineProperty(obj, prop, { configurable: true, get: function () { Object.defineProperty(this, prop, { value: undefined, writable: true }); var value = initializer.call(this, obj, prop); Object.defineProperty(this, prop, { value: value, writable: !!writable }); return value; }, set: function (value) { Object.defineProperty(this, prop, { value: value, writable: !!writable }); return value; } }); }; }); /*can-event-queue@0.13.1#value/value*/ define('can-event-queue/value/value', [ 'require', 'exports', 'module', 'can-queues', 'can-key-tree', 'can-reflect', 'can-event-queue/value/merge-dependency-records', 'can-define-lazy-value' ], function (require, exports, module) { var queues = require('can-queues'); var KeyTree = require('can-key-tree'); var canReflect = require('can-reflect'); var mergeDependencyRecords = require('can-event-queue/value/merge-dependency-records'); var defineLazyValue = require('can-define-lazy-value'); var properties = { on: function (handler, queue) { this.handlers.add([ queue || 'mutate', handler ]); }, off: function (handler, queueName) { if (handler === undefined) { if (queueName === undefined) { this.handlers.delete([]); } else { this.handlers.delete([queueName]); } } else { this.handlers.delete([ queueName || 'mutate', handler ]); } } }; var symbols = { 'can.onValue': properties.on, 'can.offValue': properties.off, 'can.dispatch': function (value, old) { queues.enqueueByQueue(this.handlers.getNode([]), this, [ value, old ], null, [ canReflect.getName(this), 'changed to', value, 'from', old ]); if (typeof this._log === 'function') { this._log(old, value); } }, 'can.getWhatIChange': function getWhatIChange() { var whatIChange = {}; var notifyHandlers = this.handlers.get(['notify']); var mutateHandlers = [].concat(this.handlers.get(['mutate']), this.handlers.get(['domUI'])); if (notifyHandlers.length) { notifyHandlers.forEach(function (handler) { var changes = canReflect.getChangesDependencyRecord(handler); if (changes) { var record = whatIChange.derive; if (!record) { record = whatIChange.derive = {}; } mergeDependencyRecords(record, changes); } }); } if (mutateHandlers.length) { mutateHandlers.forEach(function (handler) { var changes = canReflect.getChangesDependencyRecord(handler); if (changes) { var record = whatIChange.mutate; if (!record) { record = whatIChange.mutate = {}; } mergeDependencyRecords(record, changes); } }); } return Object.keys(whatIChange).length ? whatIChange : undefined; } }; function defineLazyHandlers() { return new KeyTree([ Object, Array ], { onFirst: this.onBound !== undefined && this.onBound.bind(this), onEmpty: this.onUnbound !== undefined && this.onUnbound.bind(this) }); } var mixinValueEventBindings = function (obj) { canReflect.assign(obj, properties); canReflect.assignSymbols(obj, symbols); defineLazyValue(obj, 'handlers', defineLazyHandlers, true); return obj; }; mixinValueEventBindings.addHandlers = function (obj, callbacks) { console.warn('can-event-queue/value: Avoid using addHandlers. Add onBound and onUnbound methods instead.'); obj.handlers = new KeyTree([ Object, Array ], callbacks); return obj; }; module.exports = mixinValueEventBindings; }); /*can-observation@4.0.0-pre.24#recorder-dependency-helpers*/ define('can-observation/recorder-dependency-helpers', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var canReflect = require('can-reflect'); function addNewKeyDependenciesIfNotInOld(event) { if (this.oldEventSet === undefined || this.oldEventSet['delete'](event) === false) { canReflect.onKeyValue(this.observable, event, this.onDependencyChange, 'notify'); } } function addObservablesNewKeyDependenciesIfNotInOld(eventSet, observable) { eventSet.forEach(addNewKeyDependenciesIfNotInOld, { onDependencyChange: this.onDependencyChange, observable: observable, oldEventSet: this.oldDependencies.keyDependencies.get(observable) }); } function removeKeyDependencies(event) { canReflect.offKeyValue(this.observable, event, this.onDependencyChange, 'notify'); } function removeObservablesKeyDependencies(oldEventSet, observable) { oldEventSet.forEach(removeKeyDependencies, { onDependencyChange: this.onDependencyChange, observable: observable }); } function addValueDependencies(observable) { if (this.oldDependencies.valueDependencies.delete(observable) === false) { canReflect.onValue(observable, this.onDependencyChange, 'notify'); } } function removeValueDependencies(observable) { canReflect.offValue(observable, this.onDependencyChange, 'notify'); } module.exports = { updateObservations: function (observationData) { observationData.newDependencies.keyDependencies.forEach(addObservablesNewKeyDependenciesIfNotInOld, observationData); observationData.oldDependencies.keyDependencies.forEach(removeObservablesKeyDependencies, observationData); observationData.newDependencies.valueDependencies.forEach(addValueDependencies, observationData); observationData.oldDependencies.valueDependencies.forEach(removeValueDependencies, observationData); }, stopObserving: function (observationReciever, onDependencyChange) { observationReciever.keyDependencies.forEach(removeObservablesKeyDependencies, { onDependencyChange: onDependencyChange }); observationReciever.valueDependencies.forEach(removeValueDependencies, { onDependencyChange: onDependencyChange }); } }; }); /*can-observation@4.0.0-pre.24#temporarily-bind*/ define('can-observation/temporarily-bind', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var canReflect = require('can-reflect'); var temporarilyBoundNoOperation = function () { }; var observables; var unbindTemporarilyBoundValue = function () { for (var i = 0, len = observables.length; i < len; i++) { canReflect.offValue(observables[i], temporarilyBoundNoOperation); } observables = null; }; function temporarilyBind(compute) { var computeInstance = compute.computeInstance || compute; canReflect.onValue(computeInstance, temporarilyBoundNoOperation); if (!observables) { observables = []; setTimeout(unbindTemporarilyBoundValue, 10); } observables.push(computeInstance); } module.exports = temporarilyBind; }); /*can-observation@4.0.0-pre.24#can-observation*/ define('can-observation', [ 'require', 'exports', 'module', 'can-namespace', 'can-reflect', 'can-queues', 'can-observation-recorder', 'can-symbol', 'can-log/dev/dev', 'can-event-queue/value/value', 'can-observation/recorder-dependency-helpers', 'can-observation/temporarily-bind' ], function (require, exports, module) { (function (global, require, exports, module) { var namespace = require('can-namespace'); var canReflect = require('can-reflect'); var queues = require('can-queues'); var ObservationRecorder = require('can-observation-recorder'); var canSymbol = require('can-symbol'); var dev = require('can-log/dev/dev'); var valueEventBindings = require('can-event-queue/value/value'); var recorderHelpers = require('can-observation/recorder-dependency-helpers'); var temporarilyBind = require('can-observation/temporarily-bind'); var dispatchSymbol = canSymbol.for('can.dispatch'); var getChangesSymbol = canSymbol.for('can.getChangesDependencyRecord'); var getValueDependenciesSymbol = canSymbol.for('can.getValueDependencies'); function Observation(func, context, options) { this.func = func; this.context = context; this.options = options || { priority: 0, isObservable: true }; this.bound = false; this.newDependencies = ObservationRecorder.makeDependenciesRecord(); this.oldDependencies = null; var self = this; this.onDependencyChange = function (newVal) { self.dependencyChange(this, newVal); }; this.update = this.update.bind(this); this.onDependencyChange[getChangesSymbol] = function getChanges() { return { valueDependencies: new Set([self]) }; }; Object.defineProperty(this.onDependencyChange, 'name', { value: canReflect.getName(this) + '.onDependencyChange' }); Object.defineProperty(this.update, 'name', { value: canReflect.getName(this) + '.update' }); } valueEventBindings(Observation.prototype); canReflect.assign(Observation.prototype, { onBound: function () { this.bound = true; this.oldDependencies = this.newDependencies; ObservationRecorder.start(); this.value = this.func.call(this.context); this.newDependencies = ObservationRecorder.stop(); recorderHelpers.updateObservations(this); }, dependencyChange: function (context, args) { if (this.bound === true) { queues.deriveQueue.enqueue(this.update, this, [], { priority: this.options.priority, log: [canReflect.getName(this.update)] }, [ canReflect.getName(context), 'changed' ]); } }, update: function () { if (this.bound === true) { var oldValue = this.value; this.oldValue = null; this.onBound(); if (oldValue !== this.value) { this[dispatchSymbol](this.value, oldValue); } } }, onUnbound: function () { this.bound = false; recorderHelpers.stopObserving(this.newDependencies, this.onDependencyChange); this.newDependencies = ObservationRecorder.makeDependenciesRecorder(); }, get: function () { if (this.options.isObservable && ObservationRecorder.isRecording()) { ObservationRecorder.add(this); if (!this.bound) { Observation.temporarilyBind(this); } } if (this.bound === true) { if (queues.deriveQueue.tasksRemainingCount() > 0) { Observation.updateChildrenAndSelf(this); } return this.value; } else { return this.func.call(this.context); } }, hasDependencies: function () { var newDependencies = this.newDependencies; return this.bound ? newDependencies.valueDependencies.size + newDependencies.keyDependencies.size > 0 : undefined; }, log: function () { var quoteString = function quoteString(x) { return typeof x === 'string' ? JSON.stringify(x) : x; }; this._log = function (previous, current) { dev.log(canReflect.getName(this), '\n is ', quoteString(current), '\n was ', quoteString(previous)); }; } }); canReflect.assignSymbols(Observation.prototype, { 'can.getValue': Observation.prototype.get, 'can.isValueLike': true, 'can.isMapLike': false, 'can.isListLike': false, 'can.valueHasDependencies': Observation.prototype.hasDependencies, 'can.getValueDependencies': function () { if (this.bound === true) { var deps = this.newDependencies, result = {}; if (deps.keyDependencies.size) { result.keyDependencies = deps.keyDependencies; } if (deps.valueDependencies.size) { result.valueDependencies = deps.valueDependencies; } return result; } return undefined; }, 'can.getPriority': function () { return this.options.priority; }, 'can.setPriority': function (priority) { this.options.priority = priority; }, 'can.getName': function () { return canReflect.getName(this.constructor) + '<' + canReflect.getName(this.func) + '>'; } }); Observation.updateChildrenAndSelf = function (observation) { if (observation.update !== undefined && queues.deriveQueue.isEnqueued(observation.update) === true) { queues.deriveQueue.flushQueuedTask(observation.update); return true; } if (observation[getValueDependenciesSymbol]) { var childHasChanged = false; var valueDependencies = observation[getValueDependenciesSymbol]().valueDependencies || []; valueDependencies.forEach(function (observable) { if (Observation.updateChildrenAndSelf(observable) === true) { childHasChanged = true; } }); return childHasChanged; } else { return false; } }; var alias = { addAll: 'addMany' }; [ 'add', 'addAll', 'ignore', 'trap', 'trapsCount', 'isRecording' ].forEach(function (methodName) { Observation[methodName] = function () { var name = alias[methodName] ? alias[methodName] : methodName; console.warn('can-observation: Call ' + name + '() on can-observation-recorder.'); return ObservationRecorder[name].apply(this, arguments); }; }); Observation.prototype.start = function () { console.warn('can-observation: Use .on and .off to bind.'); return this.onBound(); }; Observation.prototype.stop = function () { console.warn('can-observation: Use .on and .off to bind.'); return this.onUnbound(); }; Observation.temporarilyBind = temporarilyBind; module.exports = namespace.Observation = Observation; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/dispatch/dispatch*/ define('can-util/dom/dispatch/dispatch', [ 'require', 'exports', 'module', 'can-util/dom/events/events' ], function (require, exports, module) { 'use strict'; var domEvents = require('can-util/dom/events/events'); module.exports = function () { return domEvents.dispatch.apply(this, arguments); }; }); /*can-util@3.10.18#dom/matches/matches*/ define('can-util/dom/matches/matches', function (require, exports, module) { 'use strict'; var matchesMethod = function (element) { return element.matches || element.webkitMatchesSelector || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || element.oMatchesSelector; }; module.exports = function () { var method = matchesMethod(this); return method ? method.apply(this, arguments) : false; }; }); /*can-util@3.10.18#js/is-empty-object/is-empty-object*/ define('can-util/js/is-empty-object/is-empty-object', function (require, exports, module) { 'use strict'; module.exports = function (obj) { for (var prop in obj) { return false; } return true; }; }); /*can-util@3.10.18#dom/events/delegate/delegate*/ define('can-util/dom/events/delegate/delegate', [ 'require', 'exports', 'module', 'can-util/dom/events/events', 'can-util/dom/data/data', 'can-util/dom/matches/matches', 'can-util/js/each/each', 'can-util/js/is-empty-object/is-empty-object', 'can-cid' ], function (require, exports, module) { 'use strict'; var domEvents = require('can-util/dom/events/events'); var domData = require('can-util/dom/data/data'); var domMatches = require('can-util/dom/matches/matches'); var each = require('can-util/js/each/each'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var canCid = require('can-cid'); var dataName = 'delegateEvents'; var useCapture = function (eventType) { return eventType === 'focus' || eventType === 'blur'; }; var handleEvent = function (overrideEventType, ev) { var events = domData.get.call(this, dataName); var eventTypeEvents = events[overrideEventType || ev.type]; var matches = []; if (eventTypeEvents) { var selectorDelegates = []; each(eventTypeEvents, function (delegates) { selectorDelegates.push(delegates); }); var cur = ev.target; do { selectorDelegates.forEach(function (delegates) { if (domMatches.call(cur, delegates[0].selector)) { matches.push({ target: cur, delegates: delegates }); } }); cur = cur.parentNode; } while (cur && cur !== ev.currentTarget); } var oldStopProp = ev.stopPropagation; ev.stopPropagation = function () { oldStopProp.apply(this, arguments); this.cancelBubble = true; }; for (var i = 0; i < matches.length; i++) { var match = matches[i]; var delegates = match.delegates; for (var d = 0, dLen = delegates.length; d < dLen; d++) { if (delegates[d].handler.call(match.target, ev) === false) { return false; } if (ev.cancelBubble) { return; } } } }; domEvents.addDelegateListener = function (eventType, selector, handler) { var events = domData.get.call(this, dataName), eventTypeEvents; if (!events) { domData.set.call(this, dataName, events = {}); } if (!(eventTypeEvents = events[eventType])) { eventTypeEvents = events[eventType] = {}; var delegateHandler = handleEvent.bind(this, eventType); domData.set.call(this, canCid(handler), delegateHandler); domEvents.addEventListener.call(this, eventType, delegateHandler, useCapture(eventType)); } if (!eventTypeEvents[selector]) { eventTypeEvents[selector] = []; } eventTypeEvents[selector].push({ handler: handler, selector: selector }); }; domEvents.removeDelegateListener = function (eventType, selector, handler) { var events = domData.get.call(this, dataName); if (events && events[eventType] && events[eventType][selector]) { var eventTypeEvents = events[eventType], delegates = eventTypeEvents[selector], i = 0; while (i < delegates.length) { if (delegates[i].handler === handler) { delegates.splice(i, 1); } else { i++; } } if (delegates.length === 0) { delete eventTypeEvents[selector]; if (isEmptyObject(eventTypeEvents)) { var delegateHandler = domData.get.call(this, canCid(handler)); domEvents.removeEventListener.call(this, eventType, delegateHandler, useCapture(eventType)); delete events[eventType]; if (isEmptyObject(events)) { domData.clean.call(this, dataName); } } } } }; }); /*can-control@4.0.0-pre.4#can-control*/ define('can-control', [ 'require', 'exports', 'module', 'can-construct', 'can-namespace', 'can-util/js/string/string', 'can-util/js/assign/assign', 'can-util/js/is-function/is-function', 'can-util/js/each/each', 'can-util/js/dev/dev', 'can-util/js/get/get', 'can-util/dom/data/data', 'can-util/dom/class-name/class-name', 'can-util/dom/events/events', 'can-stache-key', 'can-reflect', 'can-observation', 'can-symbol', 'can-util/dom/dispatch/dispatch', 'can-util/dom/events/delegate/delegate' ], function (require, exports, module) { var Construct = require('can-construct'); var namespace = require('can-namespace'); var string = require('can-util/js/string/string'); var assign = require('can-util/js/assign/assign'); var isFunction = require('can-util/js/is-function/is-function'); var each = require('can-util/js/each/each'); var dev = require('can-util/js/dev/dev'); var get = require('can-util/js/get/get'); var domData = require('can-util/dom/data/data'); var className = require('can-util/dom/class-name/class-name'); var domEvents = require('can-util/dom/events/events'); var observeReader = require('can-stache-key'); var canReflect = require('can-reflect'); var Observation = require('can-observation'); var canSymbol = require('can-symbol'); var processors; require('can-util/dom/dispatch/dispatch'); require('can-util/dom/events/delegate/delegate'); var onKeyValueSymbol = canSymbol.for('can.onKeyValue'), offKeyValueSymbol = canSymbol.for('can.offKeyValue'), onEventSymbol = canSymbol.for('can.onEvent'), offEventSymbol = canSymbol.for('can.offEvent'), onValueSymbol = canSymbol.for('can.onValue'), offValueSymbol = canSymbol.for('can.offValue'); var canEvent = { on: function (eventName, handler, queue) { var listenWithDOM = domEvents.canAddEventListener.call(this); if (listenWithDOM) { var method = typeof handler === 'string' ? 'addDelegateListener' : 'addEventListener'; domEvents[method].call(this, eventName, handler, queue); } else { if (this[onKeyValueSymbol]) { canReflect.onKeyValue(this, eventName, handler, queue); } else if (this[onEventSymbol]) { this[onEventSymbol](eventName, handler, queue); } else if ('addEventListener' in this) { this.addEventListener(eventName, handler, queue); } else { if (!eventName && this[onValueSymbol]) { canReflect.onValue(this, handler); } else { throw new Error('can-control: Unable to bind ' + eventName); } } } }, off: function (eventName, handler, queue) { var listenWithDOM = domEvents.canAddEventListener.call(this); if (listenWithDOM) { var method = typeof handler === 'string' ? 'removeDelegateListener' : 'removeEventListener'; domEvents[method].call(this, eventName, handler, queue); } else { if (this[offKeyValueSymbol]) { canReflect.offKeyValue(this, eventName, handler, queue); } else if (this[offEventSymbol]) { this[offEventSymbol](eventName, handler, queue); } else if ('removeEventListener' in this) { this.removeEventListener(eventName, handler, queue); } else { if (!eventName && this[offValueSymbol]) { canReflect.offValue(this, handler); } else { throw new Error('can-control: Unable to unbind ' + eventName); } } } } }; var bind = function (el, ev, callback, queue) { canEvent.on.call(el, ev, callback, queue); return function () { canEvent.off.call(el, ev, callback, queue); }; }, slice = [].slice, paramReplacer = /\{([^\}]+)\}/g, delegate = function (el, selector, ev, callback) { canEvent.on.call(el, ev, selector, callback); return function () { canEvent.off.call(el, ev, selector, callback); }; }, binder = function (el, ev, callback, selector) { return selector ? delegate(el, selector.trim(), ev, callback) : bind(el, ev, callback); }, basicProcessor; var Control = Construct.extend('Control', { setup: function () { Construct.setup.apply(this, arguments); if (Control) { var control = this, funcName; control.actions = {}; for (funcName in control.prototype) { if (control._isAction(funcName)) { control.actions[funcName] = control._action(funcName); } } } }, _shifter: function (context, name) { var method = typeof name === 'string' ? context[name] : name; if (!isFunction(method)) { method = context[method]; } var Control = this; function controlMethod() { var wrapped = Control.wrapElement(this); context.called = name; return method.apply(context, [wrapped].concat(slice.call(arguments, 0))); } Object.defineProperty(controlMethod, 'name', { value: canReflect.getName(this) + '[' + name + ']' }); return controlMethod; }, _isAction: function (methodName) { var val = this.prototype[methodName], type = typeof val; return methodName !== 'constructor' && (type === 'function' || type === 'string' && isFunction(this.prototype[val])) && !!(Control.isSpecial(methodName) || processors[methodName] || /[^\w]/.test(methodName)); }, _action: function (methodName, options, controlInstance) { var readyCompute, unableToBind; paramReplacer.lastIndex = 0; if (options || !paramReplacer.test(methodName)) { var controlActionData = function () { var delegate; var name = methodName.replace(paramReplacer, function (matched, key) { var value, parent; if (this._isDelegate(options, key)) { delegate = this._getDelegate(options, key); return ''; } key = this._removeDelegateFromKey(key); parent = this._lookup(options)[0]; value = observeReader.read(parent, observeReader.reads(key), { readCompute: false }).value; if (value === undefined && typeof window !== 'undefined') { value = get(window, key); } if (!parent || !(canReflect.isObservableLike(parent) && canReflect.isMapLike(parent)) && !value) { unableToBind = true; return null; } if (typeof value === 'string') { return value; } else { delegate = value; return ''; } }.bind(this)); name = name.trim(); var parts = name.split(/\s+/g), event = parts.pop(); return { processor: this.processors[event] || basicProcessor, parts: [ name, parts.join(' '), event ], delegate: delegate || undefined }; }; Object.defineProperty(controlActionData, 'name', { value: canReflect.getName(controlInstance || this.prototype) + '[' + methodName + '].actionData' }); readyCompute = new Observation(controlActionData, this); if (controlInstance) { var handler = function (actionData) { controlInstance._bindings.control[methodName](controlInstance.element); controlInstance._bindings.control[methodName] = actionData.processor(actionData.delegate || controlInstance.element, actionData.parts[2], actionData.parts[1], methodName, controlInstance); }; Object.defineProperty(handler, 'name', { value: canReflect.getName(controlInstance) + '[' + methodName + '].handler' }); canReflect.onValue(readyCompute, handler, 'mutate'); if (unableToBind) { dev.log('can-control: No property found for handling ' + methodName); } controlInstance._bindings.readyComputes[methodName] = { compute: readyCompute, handler: handler }; } return readyCompute.get(); } }, _lookup: function (options) { return [ options, window ]; }, _removeDelegateFromKey: function (key) { return key; }, _isDelegate: function (options, key) { return key === 'element'; }, _getDelegate: function (options, key) { return undefined; }, processors: {}, defaults: {}, convertElement: function (element) { element = typeof element === 'string' ? document.querySelector(element) : element; return this.wrapElement(element); }, wrapElement: function (el) { return el; }, unwrapElement: function (el) { return el; }, isSpecial: function (eventName) { return eventName === 'inserted' || eventName === 'removed'; } }, { setup: function (element, options) { var cls = this.constructor, pluginname = cls.pluginName || cls.shortName, arr; if (!element) { throw new Error('Creating an instance of a named control without passing an element'); } this.element = cls.convertElement(element); if (pluginname && pluginname !== 'Control') { className.add.call(this.element, pluginname); } arr = domData.get.call(this.element, 'controls'); if (!arr) { arr = []; domData.set.call(this.element, 'controls', arr); } arr.push(this); if (canReflect.isObservableLike(options) && canReflect.isMapLike(options)) { for (var prop in cls.defaults) { if (!options.hasOwnProperty(prop)) { observeReader.set(options, prop, cls.defaults[prop]); } } this.options = options; } else { this.options = assign(assign({}, cls.defaults), options); } this.on(); return [ this.element, this.options ]; }, on: function (el, selector, eventName, func) { if (!el) { this.off(); var cls = this.constructor, bindings = this._bindings, actions = cls.actions, element = this.constructor.unwrapElement(this.element), destroyCB = Control._shifter(this, 'destroy'), funcName, ready; for (funcName in actions) { if (actions.hasOwnProperty(funcName)) { ready = actions[funcName] || cls._action(funcName, this.options, this); if (ready) { bindings.control[funcName] = ready.processor(ready.delegate || element, ready.parts[2], ready.parts[1], funcName, this); } } } domEvents.addEventListener.call(element, 'removed', destroyCB); bindings.user.push(function (el) { domEvents.removeEventListener.call(el, 'removed', destroyCB); }); return bindings.user.length; } if (typeof el === 'string') { func = eventName; eventName = selector; selector = el; el = this.element; } if (func === undefined) { func = eventName; eventName = selector; selector = null; } if (typeof func === 'string') { func = Control._shifter(this, func); } this._bindings.user.push(binder(el, eventName, func, selector)); return this._bindings.user.length; }, off: function () { var el = this.constructor.unwrapElement(this.element), bindings = this._bindings; if (bindings) { each(bindings.user || [], function (value) { value(el); }); each(bindings.control || {}, function (value) { value(el); }); each(bindings.readyComputes || {}, function (value) { canReflect.offValue(value.compute, value.handler, 'mutate'); }); } this._bindings = { user: [], control: {}, readyComputes: {} }; }, destroy: function () { if (this.element === null) { dev.warn('can-control: Control already destroyed'); return; } var Class = this.constructor, pluginName = Class.pluginName || Class.shortName && string.underscore(Class.shortName), controls; this.off(); if (pluginName && pluginName !== 'can_control') { className.remove.call(this.element, pluginName); } controls = domData.get.call(this.element, 'controls'); if (controls) { controls.splice(controls.indexOf(this), 1); } this.element = null; } }); processors = Control.processors; basicProcessor = function (el, event, selector, methodName, control) { return binder(el, event, Control._shifter(control, methodName), selector); }; each([ 'beforeremove', 'change', 'click', 'contextmenu', 'dblclick', 'keydown', 'keyup', 'keypress', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'reset', 'resize', 'scroll', 'select', 'submit', 'focusin', 'focusout', 'mouseenter', 'mouseleave', 'touchstart', 'touchmove', 'touchcancel', 'touchend', 'touchleave', 'inserted', 'removed', 'dragstart', 'dragenter', 'dragover', 'dragleave', 'drag', 'drop', 'dragend' ], function (v) { processors[v] = basicProcessor; }); module.exports = namespace.Control = Control; }); /*can-component@4.0.0-pre.14#control/control*/ define('can-component/control/control', [ 'require', 'exports', 'module', 'can-control', 'can-util/js/each/each', 'can-reflect' ], function (require, exports, module) { var Control = require('can-control'); var canEach = require('can-util/js/each/each'); var canReflect = require('can-reflect'); var paramReplacer = /\{([^\}]+)\}/g; var ComponentControl = Control.extend({ _lookup: function (options) { return [ options.scope, options, window ]; }, _removeDelegateFromKey: function (key) { return key.replace(/^(scope|^viewModel)\./, ''); }, _isDelegate: function (options, key) { return key === 'scope' || key === 'viewModel'; }, _getDelegate: function (options, key) { return options[key]; }, _action: function (methodName, options, controlInstance) { var hasObjectLookup; paramReplacer.lastIndex = 0; hasObjectLookup = paramReplacer.test(methodName); if (!controlInstance && hasObjectLookup) { return; } else { return Control._action.apply(this, arguments); } } }, { setup: function (el, options) { this.scope = options.scope; this.viewModel = options.viewModel; return Control.prototype.setup.call(this, el, options); }, off: function () { if (this._bindings) { canEach(this._bindings.readyComputes || {}, function (value) { canReflect.offValue(value.compute, value.handler); }); } Control.prototype.off.apply(this, arguments); this._bindings.readyComputes = {}; }, destroy: function () { Control.prototype.destroy.apply(this, arguments); if (typeof this.options.destroy === 'function') { this.options.destroy.apply(this, arguments); } } }); module.exports = ComponentControl; }); /*can-stache@4.0.0-pre.26#expressions/arg*/ define('can-stache/expressions/arg', function (require, exports, module) { var Arg = function (expression, modifiers) { this.expr = expression; this.modifiers = modifiers || {}; this.isCompute = false; }; Arg.prototype.value = function () { return this.expr.value.apply(this.expr, arguments); }; Arg.prototype.sourceText = function () { return (this.modifiers.compute ? '~' : '') + this.expr.sourceText(); }; module.exports = Arg; }); /*can-stache@4.0.0-pre.26#expressions/literal*/ define('can-stache/expressions/literal', function (require, exports, module) { var Literal = function (value) { this._value = value; }; Literal.prototype.value = function () { return this._value; }; Literal.prototype.sourceText = function () { return JSON.stringify(this._value); }; module.exports = Literal; }); /*can-util@3.10.18#js/single-reference/single-reference*/ define('can-util/js/single-reference/single-reference', [ 'require', 'exports', 'module', 'can-cid' ], function (require, exports, module) { (function (global, require, exports, module) { var CID = require('can-cid'); var singleReference; function getKeyName(key, extraKey) { var keyName = extraKey ? CID(key) + ':' + extraKey : CID(key); return keyName || key; } singleReference = { set: function (obj, key, value, extraKey) { obj[getKeyName(key, extraKey)] = value; }, getAndDelete: function (obj, key, extraKey) { var keyName = getKeyName(key, extraKey); var value = obj[keyName]; delete obj[keyName]; return value; } }; module.exports = singleReference; }(function () { return this; }(), require, exports, module)); }); /*can-view-scope@4.0.0-pre.36#make-compute-like*/ define('can-view-scope/make-compute-like', [ 'require', 'exports', 'module', 'can-util/js/single-reference/single-reference', 'can-reflect' ], function (require, exports, module) { var singleReference = require('can-util/js/single-reference/single-reference'); var canReflect = require('can-reflect'); var Compute = function (newVal) { if (arguments.length) { return canReflect.setValue(this, newVal); } else { return canReflect.getValue(this); } }; module.exports = function (observable) { var compute = Compute.bind(observable); compute.on = compute.bind = compute.addEventListener = function (event, handler) { var translationHandler = function (newVal, oldVal) { handler.call(compute, { type: 'change' }, newVal, oldVal); }; singleReference.set(handler, this, translationHandler); observable.on(translationHandler); }; compute.off = compute.unbind = compute.removeEventListener = function (event, handler) { observable.off(singleReference.getAndDelete(handler, this)); }; canReflect.assignSymbols(compute, { 'can.getValue': function () { return canReflect.getValue(observable); }, 'can.setValue': function (newVal) { return canReflect.setValue(observable, newVal); }, 'can.onValue': function (handler, queue) { return canReflect.onValue(observable, handler, queue); }, 'can.offValue': function (handler, queue) { return canReflect.offValue(observable, handler, queue); }, 'can.valueHasDependencies': function () { return canReflect.valueHasDependencies(observable); }, 'can.getPriority': function () { return canReflect.getPriority(observable); }, 'can.setPriority': function (newPriority) { canReflect.setPriority(observable, newPriority); }, 'can.isValueLike': true, 'can.isFunctionLike': false }); compute.isComputed = true; return compute; }; }); /*can-simple-observable@2.0.0-pre.24#log*/ define('can-simple-observable/log', [ 'require', 'exports', 'module', 'can-log/dev/dev', 'can-reflect' ], function (require, exports, module) { var dev = require('can-log/dev/dev'); var canReflect = require('can-reflect'); function quoteString(x) { return typeof x === 'string' ? JSON.stringify(x) : x; } module.exports = function log() { this._log = function (previous, current) { dev.log(canReflect.getName(this), '\n is ', quoteString(current), '\n was ', quoteString(previous)); }; }; }); /*can-simple-observable@2.0.0-pre.24#can-simple-observable*/ define('can-simple-observable', [ 'require', 'exports', 'module', 'can-simple-observable/log', 'can-namespace', 'can-symbol', 'can-reflect', 'can-observation-recorder', 'can-event-queue/value/value' ], function (require, exports, module) { var log = require('can-simple-observable/log'); var ns = require('can-namespace'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var ObservationRecorder = require('can-observation-recorder'); var valueEventBindings = require('can-event-queue/value/value'); var dispatchSymbol = canSymbol.for('can.dispatch'); function SimpleObservable(initialValue) { this.value = initialValue; } valueEventBindings(SimpleObservable.prototype); Object.assign(SimpleObservable.prototype, { log: log, get: function () { ObservationRecorder.add(this); return this.value; }, set: function (value) { var old = this.value; this.value = value; this[dispatchSymbol](value, old); } }); canReflect.assignSymbols(SimpleObservable.prototype, { 'can.getValue': SimpleObservable.prototype.get, 'can.setValue': SimpleObservable.prototype.set, 'can.isMapLike': false, 'can.valueHasDependencies': function () { return true; }, 'can.getName': function () { var value = this.value; if (typeof value !== 'object' || value === null) { value = JSON.stringify(value); } else { value = ''; } return canReflect.getName(this.constructor) + '<' + value + '>'; } }); module.exports = ns.SimpleObservable = SimpleObservable; }); /*can-simple-observable@2.0.0-pre.24#settable/settable*/ define('can-simple-observable/settable/settable', [ 'require', 'exports', 'module', 'can-reflect', 'can-observation-recorder', 'can-simple-observable', 'can-observation', 'can-queues', 'can-simple-observable/log', 'can-event-queue/value/value' ], function (require, exports, module) { var canReflect = require('can-reflect'); var ObservationRecorder = require('can-observation-recorder'); var SimpleObservable = require('can-simple-observable'); var Observation = require('can-observation'); var queues = require('can-queues'); var log = require('can-simple-observable/log'); var valueEventBindings = require('can-event-queue/value/value'); var peek = ObservationRecorder.ignore(canReflect.getValue.bind(canReflect)); function SettableObservable(fn, context, initialValue) { this.lastSetValue = new SimpleObservable(initialValue); function observe() { return fn.call(context, this.lastSetValue.get()); } this.handler = this.handler.bind(this); canReflect.assignSymbols(this, { 'can.getName': function () { return canReflect.getName(this.constructor) + '<' + canReflect.getName(fn) + '>'; } }); Object.defineProperty(this.handler, 'name', { value: canReflect.getName(this) + '.handler' }); Object.defineProperty(observe, 'name', { value: canReflect.getName(fn) + '::' + canReflect.getName(this.constructor) }); this.observation = new Observation(observe, this); } valueEventBindings(SettableObservable.prototype); Object.assign(SettableObservable.prototype, { log: log, constructor: SettableObservable, handler: function (newVal) { var old = this.value; this.value = newVal; if (typeof this._log === 'function') { this._log(old, newVal); } queues.enqueueByQueue(this.handlers.getNode([]), this, [ newVal, old ], function () { return {}; }); }, onBound: function () { this.bound = true; canReflect.onValue(this.observation, this.handler, 'notify'); this.value = peek(this.observation); }, onUnbound: function () { this.bound = false; canReflect.offValue(this.observation, this.handler, 'notify'); }, set: function (newVal) { if (newVal !== this.lastSetValue.get()) { this.lastSetValue.set(newVal); } }, get: function () { if (ObservationRecorder.isRecording()) { ObservationRecorder.add(this); if (!this.bound) { Observation.temporarilyBind(this); } } if (this.bound === true) { return this.value; } else { return this.observation.get(); } }, hasDependencies: function () { return canReflect.valueHasDependencies(this.observation); }, getValueDependencies: function () { return canReflect.getValueDependencies(this.observation); } }); canReflect.assignSymbols(SettableObservable.prototype, { 'can.getValue': SettableObservable.prototype.get, 'can.setValue': SettableObservable.prototype.set, 'can.isMapLike': false, 'can.getPriority': function () { return canReflect.getPriority(this.observation); }, 'can.setPriority': function (newPriority) { canReflect.setPriority(this.observation, newPriority); }, 'can.valueHasDependencies': SettableObservable.prototype.hasDependencies, 'can.getValueDependencies': SettableObservable.prototype.getValueDependencies }); module.exports = SettableObservable; }); /*can-simple-observable@2.0.0-pre.24#setter/setter*/ define('can-simple-observable/setter/setter', [ 'require', 'exports', 'module', 'can-reflect', 'can-observation', 'can-simple-observable/settable/settable', 'can-event-queue/value/value' ], function (require, exports, module) { var canReflect = require('can-reflect'); var Observation = require('can-observation'); var SettableObservable = require('can-simple-observable/settable/settable'); var valueEventBindings = require('can-event-queue/value/value'); function SetterObservable(getter, setter) { this.setter = setter; this.observation = new Observation(getter); this.handler = this.handler.bind(this); canReflect.assignSymbols(this, { 'can.getName': function () { return canReflect.getName(this.constructor) + '<' + canReflect.getName(getter) + '>'; } }); Object.defineProperty(this.handler, 'name', { value: canReflect.getName(this) + '.handler' }); } SetterObservable.prototype = Object.create(SettableObservable.prototype); SetterObservable.prototype.constructor = SetterObservable; SetterObservable.prototype.set = function (newVal) { this.setter(newVal); }; SetterObservable.prototype.hasDependencies = function () { return canReflect.valueHasDependencies(this.observation); }; canReflect.assignSymbols(SetterObservable.prototype, { 'can.setValue': SetterObservable.prototype.set, 'can.valueHasDependencies': SetterObservable.prototype.hasDependencies }); module.exports = SetterObservable; }); /*can-stache@4.0.0-pre.26#src/expression-helpers*/ define('can-stache/src/expression-helpers', [ 'require', 'exports', 'module', 'can-stache/expressions/arg', 'can-stache/expressions/literal', 'can-reflect', 'can-stache-key', 'can-symbol', 'can-observation', 'can-view-scope/make-compute-like', 'can-simple-observable/setter/setter' ], function (require, exports, module) { var Arg = require('can-stache/expressions/arg'); var Literal = require('can-stache/expressions/literal'); var canReflect = require('can-reflect'); var observeReader = require('can-stache-key'); var canSymbol = require('can-symbol'); var Observation = require('can-observation'); var makeComputeLike = require('can-view-scope/make-compute-like'); var SetterObservable = require('can-simple-observable/setter/setter'); function getObservableValue_fromKey(key, scope, readOptions) { var data = scope.computeData(key, readOptions); Observation.temporarilyBind(data); return data; } function computeHasDependencies(compute) { return compute[canSymbol.for('can.valueHasDependencies')] ? canReflect.valueHasDependencies(compute) : compute.computeInstance.hasDependencies; } function getObservableValue_fromDynamicKey_fromObservable(key, root, helperOptions, readOptions) { var getKey = function () { return ('' + canReflect.getValue(key)).replace('.', '\\.'); }; var computeValue = new SetterObservable(function getDynamicKey() { return observeReader.get(canReflect.getValue(root), getKey()); }, function setDynamicKey(newVal) { observeReader.write(canReflect.getValue(root), observeReader.reads(getKey()), newVal); }); Observation.temporarilyBind(computeValue); return computeValue; } function convertToArgExpression(expr) { if (!(expr instanceof Arg) && !(expr instanceof Literal)) { return new Arg(expr); } else { return expr; } } function toComputeOrValue(value) { if (canReflect.isObservableLike(value)) { if (canReflect.isValueLike(value) && canReflect.valueHasDependencies(value) === false) { return canReflect.getValue(value); } if (value.compute) { return value.compute; } else { return makeComputeLike(value); } } return value; } function toCompute(value) { if (value) { if (value.isComputed) { return value; } if (value.compute) { return value.compute; } else { return makeComputeLike(value); } } return value; } module.exports = { getObservableValue_fromKey: getObservableValue_fromKey, computeHasDependencies: computeHasDependencies, getObservableValue_fromDynamicKey_fromObservable: getObservableValue_fromDynamicKey_fromObservable, convertToArgExpression: convertToArgExpression, toComputeOrValue: toComputeOrValue, toCompute: toCompute }; }); /*can-stache@4.0.0-pre.26#expressions/hashes*/ define('can-stache/expressions/hashes', [ 'require', 'exports', 'module', 'can-reflect', 'can-observation', 'can-stache/src/expression-helpers' ], function (require, exports, module) { var canReflect = require('can-reflect'); var Observation = require('can-observation'); var expressionHelpers = require('can-stache/src/expression-helpers'); var Hashes = function (hashes) { this.hashExprs = hashes; }; Hashes.prototype.value = function (scope, helperOptions) { var hash = {}; for (var prop in this.hashExprs) { var val = expressionHelpers.convertToArgExpression(this.hashExprs[prop]), value = val.value.apply(val, arguments); hash[prop] = { call: !val.modifiers || !val.modifiers.compute, value: value }; } return new Observation(function () { var finalHash = {}; for (var prop in hash) { finalHash[prop] = hash[prop].call ? canReflect.getValue(hash[prop].value) : expressionHelpers.toComputeOrValue(hash[prop].value); } return finalHash; }); }; Hashes.prototype.sourceText = function () { var hashes = []; canReflect.eachKey(this.hashExprs, function (expr, prop) { hashes.push(prop + '=' + expr.sourceText()); }); return hashes.join(' '); }; module.exports = Hashes; }); /*can-stache@4.0.0-pre.26#expressions/bracket*/ define('can-stache/expressions/bracket', [ 'require', 'exports', 'module', 'can-symbol', 'can-stache/src/expression-helpers' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var expressionHelpers = require('can-stache/src/expression-helpers'); var Bracket = function (key, root, originalKey) { this.root = root; this.key = key; this[canSymbol.for('can-stache.originalKey')] = originalKey; }; Bracket.prototype.value = function (scope, helpers) { var root = this.root ? this.root.value(scope, helpers) : scope.peek('.'); return expressionHelpers.getObservableValue_fromDynamicKey_fromObservable(this.key.value(scope, helpers), root, scope, helpers, {}); }; Bracket.prototype.sourceText = function () { if (this.rootExpr) { return this.rootExpr.sourceText() + '[' + this.key + ']'; } else { return '[' + this.key + ']'; } }; Bracket.prototype.closingTag = function () { return this[canSymbol.for('can-stache.originalKey')] || ''; }; module.exports = Bracket; }); /*can-event-queue@0.13.1#map/legacy/legacy*/ define('can-event-queue/map/legacy/legacy', [ 'require', 'exports', 'module', 'can-util/js/dev/dev', 'can-util/js/assign/assign', 'can-queues', 'can-reflect', 'can-symbol', 'can-key-tree', 'can-util/dom/events/events' ], function (require, exports, module) { var canDev = require('can-util/js/dev/dev'); var assign = require('can-util/js/assign/assign'); var queues = require('can-queues'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var KeyTree = require('can-key-tree'); var domEvents = require('can-util/dom/events/events'); var metaSymbol = canSymbol.for('can.meta'), dispatchBoundChangeSymbol = canSymbol.for('can.dispatchInstanceBoundChange'), dispatchInstanceOnPatchesSymbol = canSymbol.for('can.dispatchInstanceOnPatches'), onKeyValueSymbol = canSymbol.for('can.onKeyValue'), offKeyValueSymbol = canSymbol.for('can.offKeyValue'), onEventSymbol = canSymbol.for('can.onEvent'), offEventSymbol = canSymbol.for('can.offEvent'), onValueSymbol = canSymbol.for('can.onValue'), offValueSymbol = canSymbol.for('can.offValue'); var legacyMapBindings; var ensureMeta = function ensureMeta(obj) { var meta = obj[metaSymbol]; if (!meta) { meta = {}; canReflect.setKeyValue(obj, metaSymbol, meta); } if (!meta.handlers) { meta.handlers = new KeyTree([ Object, Object, Object, Array ], { onFirst: function () { if (obj._eventSetup) { obj._eventSetup(); } if (obj.constructor[dispatchBoundChangeSymbol]) { obj.constructor[dispatchBoundChangeSymbol](obj, true); } }, onEmpty: function () { if (obj._eventTeardown) { obj._eventTeardown(); } if (obj.constructor[dispatchBoundChangeSymbol]) { obj.constructor[dispatchBoundChangeSymbol](obj, false); } } }); } if (!meta.listenHandlers) { meta.listenHandlers = new KeyTree([ Map, Object, Array ]); } return meta; }; var props = { dispatch: function (event, args) { if (arguments.length > 4) { canDev.warn('Arguments to dispatch should be an array, not multiple arguments.'); args = Array.prototype.slice.call(arguments, 1); } if (args && !Array.isArray(args)) { canDev.warn('Arguments to dispatch should be an array.'); args = [args]; } if (!this.__inSetup) { if (typeof event === 'string') { event = { type: event }; } var meta = ensureMeta(this); if (!event.reasonLog) { event.reasonLog = [ canReflect.getName(this), 'dispatched', '"' + event.type + '"', 'with' ].concat(args); } if (!event.makeMeta) { event.makeMeta = function makeMeta(handler) { return { log: [canReflect.getName(handler)] }; }; } if (typeof meta._log === 'function') { meta._log.call(this, event, args); } var handlers = meta.handlers; var handlersByType = handlers.getNode([event.type]); var dispatchPatches = event.patches && this.constructor[dispatchInstanceOnPatchesSymbol]; var batch = dispatchPatches || handlersByType; if (batch) { queues.batch.start(); } if (handlersByType) { if (handlersByType.onKeyValue) { queues.enqueueByQueue(handlersByType.onKeyValue, this, args, event.makeMeta, event.reasonLog); } if (handlersByType.event) { event.batchNum = queues.batch.number(); var eventAndArgs = [event].concat(args); queues.enqueueByQueue(handlersByType.event, this, eventAndArgs, event.makeMeta, event.reasonLog); } } if (dispatchPatches) { this.constructor[dispatchInstanceOnPatchesSymbol](this, event.patches); } if (batch) { queues.batch.stop(); } } }, addEventListener: function (key, handler, queueName) { ensureMeta(this).handlers.add([ key, 'event', queueName || 'mutate', handler ]); }, removeEventListener: function (key, handler, queueName) { if (key === undefined) { var handlers = ensureMeta(this).handlers; var keyHandlers = handlers.getNode([]); Object.keys(keyHandlers).forEach(function (key) { handlers.delete([ key, 'event' ]); }); } else if (!handler && !queueName) { ensureMeta(this).handlers.delete([ key, 'event' ]); } else if (!handler) { ensureMeta(this).handlers.delete([ key, 'event', queueName || 'mutate' ]); } else { ensureMeta(this).handlers.delete([ key, 'event', queueName || 'mutate', handler ]); } }, one: function (event, handler) { var one = function () { legacyMapBindings.off.call(this, event, one); return handler.apply(this, arguments); }; legacyMapBindings.on.call(this, event, one); return this; }, listenTo: function (other, event, handler) { ensureMeta(this).listenHandlers.add([ other, event, handler ]); legacyMapBindings.on.call(other, event, handler); }, stopListening: function (other, event, handler) { var listenHandlers = ensureMeta(this).listenHandlers; function stopHandler(other, event, handler) { legacyMapBindings.off.call(other, event, handler); } function stopEvent(other, event) { listenHandlers.get([ other, event ]).forEach(function (handler) { stopHandler(other, event, handler); }); } function stopOther(other) { canReflect.eachKey(listenHandlers.getNode([other]), function (handlers, event) { stopEvent(other, event); }); } if (other) { if (event) { if (handler) { stopHandler(other, event, handler); listenHandlers.delete([ other, event, handler ]); } else { stopEvent(other, event); listenHandlers.delete([ other, event ]); } } else { stopOther(other); listenHandlers.delete([other]); } } else { canReflect.eachKey(listenHandlers.getNode([]), function (events, other) { stopOther(other); }); listenHandlers.delete([]); } return this; }, on: function (eventName, handler, queue) { var listenWithDOM = domEvents.canAddEventListener.call(this); if (listenWithDOM) { var method = typeof handler === 'string' ? 'addDelegateListener' : 'addEventListener'; domEvents[method].call(this, eventName, handler, queue); } else { if ('addEventListener' in this) { this.addEventListener(eventName, handler, queue); } else if (this[onKeyValueSymbol]) { canReflect.onKeyValue(this, eventName, handler, queue); } else if (this[onEventSymbol]) { this[onEventSymbol](eventName, handler, queue); } else { if (!eventName && this[onValueSymbol]) { canReflect.onValue(this, handler); } else { throw new Error('can-event-queue: Unable to bind ' + eventName); } } } }, off: function (eventName, handler, queue) { var listenWithDOM = domEvents.canAddEventListener.call(this); if (listenWithDOM) { var method = typeof handler === 'string' ? 'removeDelegateListener' : 'removeEventListener'; domEvents[method].call(this, eventName, handler, queue); } else { if ('removeEventListener' in this) { this.removeEventListener(eventName, handler, queue); } else if (this[offKeyValueSymbol]) { canReflect.offKeyValue(this, eventName, handler, queue); } else if (this[offEventSymbol]) { this[offEventSymbol](eventName, handler, queue); } else { if (!eventName && this[offValueSymbol]) { canReflect.offValue(this, handler); } else { throw new Error('can-event-queue: Unable to unbind ' + eventName); } } } } }; props.bind = props.addEventListener; props.unbind = props.removeEventListener; var symbols = { 'can.onKeyValue': function (key, handler, queueName) { ensureMeta(this).handlers.add([ key, 'onKeyValue', queueName || 'mutate', handler ]); }, 'can.offKeyValue': function (key, handler, queueName) { ensureMeta(this).handlers.delete([ key, 'onKeyValue', queueName || 'mutate', handler ]); }, 'can.isBound': function () { return ensureMeta(this).handlers.size() > 0; } }; legacyMapBindings = function (obj) { assign(obj, props); return canReflect.assignSymbols(obj, symbols); }; function defineNonEnumerable(obj, prop, value) { Object.defineProperty(obj, prop, { enumerable: false, value: value }); } assign(legacyMapBindings, props); defineNonEnumerable(legacyMapBindings, 'start', function () { console.warn('use can-queues.batch.start()'); queues.batch.start(); }); defineNonEnumerable(legacyMapBindings, 'stop', function () { console.warn('use can-queues.batch.stop()'); queues.batch.stop(); }); defineNonEnumerable(legacyMapBindings, 'flush', function () { console.warn('use can-queues.flush()'); queues.flush(); }); defineNonEnumerable(legacyMapBindings, 'afterPreviousEvents', function (handler) { console.warn('don\'t use afterPreviousEvents'); queues.mutateQueue.enqueue(function afterPreviousEvents() { queues.mutateQueue.enqueue(handler); }); queues.flush(); }); defineNonEnumerable(legacyMapBindings, 'after', function (handler) { console.warn('don\'t use after'); queues.mutateQueue.enqueue(handler); queues.flush(); }); module.exports = legacyMapBindings; }); /*can-simple-map@4.0.0-pre.13#can-simple-map*/ define('can-simple-map', [ 'require', 'exports', 'module', 'can-construct', 'can-event-queue/map/legacy/legacy', 'can-queues', 'can-util/js/each/each', 'can-observation-recorder', 'can-reflect', 'can-log/dev/dev', 'can-symbol' ], function (require, exports, module) { var Construct = require('can-construct'); var eventQueue = require('can-event-queue/map/legacy/legacy'); var queues = require('can-queues'); var each = require('can-util/js/each/each'); var ObservationRecorder = require('can-observation-recorder'); var canReflect = require('can-reflect'); var dev = require('can-log/dev/dev'); var canSymbol = require('can-symbol'); var ensureMeta = function ensureMeta(obj) { var metaSymbol = canSymbol.for('can.meta'); var meta = obj[metaSymbol]; if (!meta) { meta = {}; canReflect.setKeyValue(obj, metaSymbol, meta); } return meta; }; var SimpleMap = Construct.extend('SimpleMap', { setup: function (initialData) { this._data = {}; if (initialData && typeof initialData === 'object') { this.attr(initialData); } }, attr: function (prop, value) { var self = this; if (arguments.length === 0) { ObservationRecorder.add(this, '__keys'); var data = {}; each(this._data, function (value, prop) { ObservationRecorder.add(this, prop); data[prop] = value; }, this); return data; } else if (arguments.length > 1) { var had = this._data.hasOwnProperty(prop); var old = this._data[prop]; this._data[prop] = value; if (old !== value) { queues.batch.start(); if (!had) { this.dispatch('__keys', []); } if (typeof this._log === 'function') { this._log(prop, value, old); } this.dispatch({ type: prop, reasonLog: [ canReflect.getName(this) + '\'s', prop, 'changed to', value, 'from', old ] }, [ value, old ]); queues.batch.stop(); } } else if (typeof prop === 'object') { queues.batch.start(); canReflect.eachKey(prop, function (value, key) { self.attr(key, value); }); queues.batch.stop(); } else { if (prop !== 'constructor') { ObservationRecorder.add(this, prop); return this._data[prop]; } return this.constructor; } }, serialize: function () { return canReflect.serialize(this, Map); }, get: function () { return this.attr.apply(this, arguments); }, set: function () { return this.attr.apply(this, arguments); }, log: function (key) { var quoteString = function quoteString(x) { return typeof x === 'string' ? JSON.stringify(x) : x; }; var meta = ensureMeta(this); meta.allowedLogKeysSet = meta.allowedLogKeysSet || new Set(); if (key) { meta.allowedLogKeysSet.add(key); } this._log = function (prop, current, previous, log) { if (key && !meta.allowedLogKeysSet.has(prop)) { return; } dev.log(canReflect.getName(this), '\n key ', quoteString(prop), '\n is ', quoteString(current), '\n was ', quoteString(previous)); }; } }); eventQueue(SimpleMap.prototype); canReflect.assignSymbols(SimpleMap.prototype, { 'can.isMapLike': true, 'can.isListLike': false, 'can.isValueLike': false, 'can.getKeyValue': SimpleMap.prototype.get, 'can.setKeyValue': SimpleMap.prototype.set, 'can.deleteKeyValue': function (prop) { if (this._data.hasOwnProperty(prop)) { var old = this._data[prop]; delete this._data[prop]; queues.batch.start(); this.dispatch('__keys', []); if (typeof this._log === 'function') { this._log(prop, undefined, old); } this.dispatch({ type: prop, reasonLog: [ canReflect.getName(this) + '\'s', prop, 'deleted', old ] }, [ undefined, old ]); queues.batch.stop(); } }, 'can.getOwnEnumerableKeys': function () { ObservationRecorder.add(this, '__keys'); return Object.keys(this._data); }, 'can.assignDeep': function (source) { queues.batch.start(); canReflect.assignMap(this, source); queues.batch.stop(); }, 'can.updateDeep': function (source) { queues.batch.start(); canReflect.updateMap(this, source); queues.batch.stop(); }, 'can.keyHasDependencies': function (key) { return false; }, 'can.getKeyDependencies': function (key) { return undefined; }, 'can.getName': function () { return canReflect.getName(this.constructor) + '{}'; } }); module.exports = SimpleMap; }); /*can-view-scope@4.0.0-pre.36#template-context*/ define('can-view-scope/template-context', [ 'require', 'exports', 'module', 'can-simple-map' ], function (require, exports, module) { var SimpleMap = require('can-simple-map'); var TemplateContext = function () { this.vars = new SimpleMap({}); this.helpers = new SimpleMap({}); this.partials = new SimpleMap({}); this.tags = new SimpleMap({}); }; module.exports = TemplateContext; }); /*can-reflect-dependencies@0.0.3#src/add-mutated-by*/ define('can-reflect-dependencies/src/add-mutated-by', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var canReflect = require('can-reflect'); var makeDependencyRecord = function makeDependencyRecord() { return { keyDependencies: new Map(), valueDependencies: new Set() }; }; var makeRootRecord = function makeRootRecord() { return { mutateDependenciesForKey: new Map(), mutateDependenciesForValue: makeDependencyRecord() }; }; module.exports = function (mutatedByMap) { return function addMutatedBy(mutated, key, mutator) { var gotKey = arguments.length === 3; if (arguments.length === 2) { mutator = key; key = undefined; } if (!mutator.keyDependencies && !mutator.valueDependencies) { mutator = { valueDependencies: new Set([mutator]) }; } var root = mutatedByMap.get(mutated); if (!root) { root = makeRootRecord(); mutatedByMap.set(mutated, root); } if (gotKey) { root.mutateDependenciesForKey.set(key, makeDependencyRecord()); } var dependencyRecord = gotKey ? root.mutateDependenciesForKey.get(key) : root.mutateDependenciesForValue; if (mutator.valueDependencies) { canReflect.addValues(dependencyRecord.valueDependencies, mutator.valueDependencies); } if (mutator.keyDependencies) { canReflect.each(mutator.keyDependencies, function (keysSet, obj) { var entry = dependencyRecord.keyDependencies.get(obj); if (!entry) { entry = new Set(); dependencyRecord.keyDependencies.set(obj, entry); } canReflect.addValues(entry, keysSet); }); } }; }; }); /*can-reflect-dependencies@0.0.3#src/delete-mutated-by*/ define('can-reflect-dependencies/src/delete-mutated-by', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var canReflect = require('can-reflect'); module.exports = function (mutatedByMap) { return function deleteMutatedBy(mutated, key, mutator) { var gotKey = arguments.length === 3; var root = mutatedByMap.get(mutated); if (arguments.length === 2) { mutator = key; key = undefined; } if (!mutator.keyDependencies && !mutator.valueDependencies) { mutator = { valueDependencies: new Set([mutator]) }; } var dependencyRecord = gotKey ? root.mutateDependenciesForKey.get(key) : root.mutateDependenciesForValue; if (mutator.valueDependencies) { canReflect.removeValues(dependencyRecord.valueDependencies, mutator.valueDependencies); } if (mutator.keyDependencies) { canReflect.each(mutator.keyDependencies, function (keysSet, obj) { var entry = dependencyRecord.keyDependencies.get(obj); if (entry) { canReflect.removeValues(entry, keysSet); if (!entry.size) { dependencyRecord.keyDependencies.delete(obj); } } }); } }; }; }); /*can-reflect-dependencies@0.0.3#src/is-function*/ define('can-reflect-dependencies/src/is-function', function (require, exports, module) { module.exports = function isFunction(value) { return typeof value === 'function'; }; }); /*can-reflect-dependencies@0.0.3#src/get-dependency-data-of*/ define('can-reflect-dependencies/src/get-dependency-data-of', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect', 'can-reflect-dependencies/src/is-function' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var isFunction = require('can-reflect-dependencies/src/is-function'); var getWhatIChangeSymbol = canSymbol.for('can.getWhatIChange'); var getKeyDependenciesSymbol = canSymbol.for('can.getKeyDependencies'); var getValueDependenciesSymbol = canSymbol.for('can.getValueDependencies'); var getKeyDependencies = function getKeyDependencies(obj, key) { if (isFunction(obj[getKeyDependenciesSymbol])) { return canReflect.getKeyDependencies(obj, key); } }; var getValueDependencies = function getValueDependencies(obj) { if (isFunction(obj[getValueDependenciesSymbol])) { return canReflect.getValueDependencies(obj); } }; var getMutatedKeyDependencies = function getMutatedKeyDependencies(mutatedByMap, obj, key) { var root = mutatedByMap.get(obj); var dependencyRecord; if (root && root.mutateDependenciesForKey.has(key)) { dependencyRecord = root.mutateDependenciesForKey.get(key); } return dependencyRecord; }; var getMutatedValueDependencies = function getMutatedValueDependencies(mutatedByMap, obj) { var result; var root = mutatedByMap.get(obj); if (root) { var dependencyRecord = root.mutateDependenciesForValue; if (dependencyRecord.keyDependencies.size) { result = result || {}; result.keyDependencies = dependencyRecord.keyDependencies; } if (dependencyRecord.valueDependencies.size) { result = result || {}; result.valueDependencies = dependencyRecord.valueDependencies; } } return result; }; var getWhatIChange = function getWhatIChange(obj, key) { if (isFunction(obj[getWhatIChangeSymbol])) { var gotKey = arguments.length === 2; return gotKey ? canReflect.getWhatIChange(obj, key) : canReflect.getWhatIChange(obj); } }; var isEmptyRecord = function isEmptyRecord(record) { return record == null || !Object.keys(record).length || record.keyDependencies && !record.keyDependencies.size && (record.valueDependencies && !record.valueDependencies.size); }; var getWhatChangesMe = function getWhatChangesMe(mutatedByMap, obj, key) { var gotKey = arguments.length === 3; var mutate = gotKey ? getMutatedKeyDependencies(mutatedByMap, obj, key) : getMutatedValueDependencies(mutatedByMap, obj); var derive = gotKey ? getKeyDependencies(obj, key) : getValueDependencies(obj); if (!isEmptyRecord(mutate) || !isEmptyRecord(derive)) { return Object.assign({}, mutate ? { mutate: mutate } : null, derive ? { derive: derive } : null); } }; module.exports = function (mutatedByMap) { return function getDependencyDataOf(obj, key) { var gotKey = arguments.length === 2; var whatChangesMe = gotKey ? getWhatChangesMe(mutatedByMap, obj, key) : getWhatChangesMe(mutatedByMap, obj); var whatIChange = gotKey ? getWhatIChange(obj, key) : getWhatIChange(obj); if (whatChangesMe || whatIChange) { return Object.assign({}, whatIChange ? { whatIChange: whatIChange } : null, whatChangesMe ? { whatChangesMe: whatChangesMe } : null); } }; }; }); /*can-reflect-dependencies@0.0.3#can-reflect-dependencies*/ define('can-reflect-dependencies', [ 'require', 'exports', 'module', 'can-reflect-dependencies/src/add-mutated-by', 'can-reflect-dependencies/src/delete-mutated-by', 'can-reflect-dependencies/src/get-dependency-data-of' ], function (require, exports, module) { var addMutatedBy = require('can-reflect-dependencies/src/add-mutated-by'); var deleteMutatedBy = require('can-reflect-dependencies/src/delete-mutated-by'); var getDependencyDataOf = require('can-reflect-dependencies/src/get-dependency-data-of'); var mutatedByMap = new WeakMap(); module.exports = { addMutatedBy: addMutatedBy(mutatedByMap), deleteMutatedBy: deleteMutatedBy(mutatedByMap), getDependencyDataOf: getDependencyDataOf(mutatedByMap) }; }); /*can-view-scope@4.0.0-pre.36#scope-key-data*/ define('can-view-scope/scope-key-data', [ 'require', 'exports', 'module', 'can-observation', 'can-stache-key', 'can-util/js/assign/assign', 'can-reflect', 'can-symbol', 'can-key-tree', 'can-queues', 'can-observation-recorder', 'can-cid/set/set', 'can-view-scope/make-compute-like', 'can-reflect-dependencies' ], function (require, exports, module) { 'use strict'; var Observation = require('can-observation'); var observeReader = require('can-stache-key'); var assign = require('can-util/js/assign/assign'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var KeyTree = require('can-key-tree'); var queues = require('can-queues'); var ObservationRecorder = require('can-observation-recorder'); var CIDSet = require('can-cid/set/set'); var makeComputeLike = require('can-view-scope/make-compute-like'); var canReflectDeps = require('can-reflect-dependencies'); var peekValue = ObservationRecorder.ignore(canReflect.getValue.bind(canReflect)); var getFastPathRoot = ObservationRecorder.ignore(function (computeData) { if (computeData.reads && computeData.reads.length === 1) { var root = computeData.root; if (root && root[canSymbol.for('can.getValue')]) { root = canReflect.getValue(root); } return root && canReflect.isObservableLike(root) && canReflect.isMapLike(root) && typeof root[computeData.reads[0].key] !== 'function' && root; } return; }); var isEventObject = function (obj) { return obj && typeof obj.batchNum === 'number' && typeof obj.type === 'string'; }; var ScopeKeyData = function (scope, key, options) { this.startingScope = scope; this.key = key; this.options = assign({ observation: this.observation }, options); var observation; this.read = this.read.bind(this); this.dispatch = this.dispatch.bind(this); Object.defineProperty(this.read, 'name', { value: '{{' + this.key + '}}::ScopeKeyData.read' }); Object.defineProperty(this.dispatch, 'name', { value: canReflect.getName(this) + '.dispatch' }); this.handlers = new KeyTree([ Object, Array ], { onFirst: this.setup.bind(this), onEmpty: this.teardown.bind(this) }); observation = this.observation = new Observation(this.read, this); this.fastPath = undefined; this.root = undefined; this.initialValue = undefined; this.reads = undefined; this.setRoot = undefined; var valueDependencies = new CIDSet(); valueDependencies.add(observation); this.dependencies = { valueDependencies: valueDependencies }; }; ScopeKeyData.prototype = { constructor: ScopeKeyData, dispatch: function (newVal) { var old = this.value; this.value = newVal; queues.enqueueByQueue(this.handlers.getNode([]), this, [ newVal, old ], null, [ canReflect.getName(this), 'changed to', newVal, 'from', old ]); }, setup: function () { this.bound = true; canReflect.onValue(this.observation, this.dispatch, 'notify'); var fastPathRoot = getFastPathRoot(this); if (fastPathRoot) { this.toFastPath(fastPathRoot); } this.value = peekValue(this.observation); }, teardown: function () { this.bound = false; canReflect.offValue(this.observation, this.dispatch, 'notify'); this.toSlowPath(); }, set: function (newVal) { var root = this.root || this.setRoot; if (root) { observeReader.write(root, this.reads, newVal, this.options); } else { this.startingScope.set(this.key, newVal, this.options); } }, get: function () { if (ObservationRecorder.isRecording()) { ObservationRecorder.add(this); if (!this.bound) { Observation.temporarilyBind(this); } } if (this.bound === true) { return this.value; } else { return this.observation.get(); } }, on: function (handler, queue) { this.handlers.add([ queue || 'mutate', handler ]); }, off: function (handler, queue) { this.handlers.delete([ queue || 'mutate', handler ]); }, toFastPath: function (fastPathRoot) { var self = this, observation = this.observation; this.fastPath = true; var key = this.reads[0].key; canReflectDeps.addMutatedBy(fastPathRoot, key, { valueDependencies: new Set([self]) }); observation.dependencyChange = function (target, newVal) { if (isEventObject(newVal)) { throw 'no event objects!'; } if (target === fastPathRoot && typeof newVal !== 'function') { this.newVal = newVal; } else { self.toSlowPath(); } return Observation.prototype.dependencyChange.apply(this, arguments); }; observation.onBound = function () { this.value = this.newVal; }; }, toSlowPath: function () { this.observation.dependencyChange = Observation.prototype.dependencyChange; this.observation.onBound = Observation.prototype.onBound; this.fastPath = false; }, read: function () { if (this.root) { return observeReader.read(this.root, this.reads, this.options).value; } var data = this.startingScope.read(this.key, this.options); this.scope = data.scope; this.reads = data.reads; this.root = data.rootObserve; this.setRoot = data.setRoot; return this.initialValue = data.value; }, hasDependencies: function () { return canReflect.valueHasDependencies(this.observation); } }; canReflect.assignSymbols(ScopeKeyData.prototype, { 'can.getValue': ScopeKeyData.prototype.get, 'can.setValue': ScopeKeyData.prototype.set, 'can.onValue': ScopeKeyData.prototype.on, 'can.offValue': ScopeKeyData.prototype.off, 'can.valueHasDependencies': ScopeKeyData.prototype.hasDependencies, 'can.getValueDependencies': function () { var result = this.dependencies; if (this.fastPath) { var key = this.reads[0].key; var fastPathRoot = getFastPathRoot(this); result = { keyDependencies: new Map([[ fastPathRoot, new Set([key]) ]]) }; } return result; }, 'can.getPriority': function () { return canReflect.getPriority(this.observation); }, 'can.setPriority': function (newPriority) { canReflect.setPriority(this.observation, newPriority); }, 'can.getName': function () { return canReflect.getName(this.constructor) + '{{' + this.key + '}}'; } }); Object.defineProperty(ScopeKeyData.prototype, 'compute', { get: function () { var compute = makeComputeLike(this); Object.defineProperty(this, 'compute', { value: compute, writable: false, configurable: false }); return compute; }, configurable: true }); module.exports = ScopeKeyData; }); /*can-view-scope@4.0.0-pre.36#compute_data*/ define('can-view-scope/compute_data', [ 'require', 'exports', 'module', 'can-view-scope/scope-key-data' ], function (require, exports, module) { 'use strict'; var ScopeKeyData = require('can-view-scope/scope-key-data'); module.exports = function (scope, key, options) { return new ScopeKeyData(scope, key, options || { args: [] }); }; }); /*can-view-scope@4.0.0-pre.36#can-view-scope*/ define('can-view-scope', [ 'require', 'exports', 'module', 'can-stache-key', 'can-observation-recorder', 'can-view-scope/template-context', 'can-view-scope/compute_data', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-namespace', 'can-reflect', 'can-log/dev/dev', 'can-define-lazy-value' ], function (require, exports, module) { var observeReader = require('can-stache-key'); var ObservationRecorder = require('can-observation-recorder'); var TemplateContext = require('can-view-scope/template-context'); var makeComputeData = require('can-view-scope/compute_data'); var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var namespace = require('can-namespace'); var canReflect = require('can-reflect'); var canLog = require('can-log/dev/dev'); var defineLazyValue = require('can-define-lazy-value'); function Scope(context, parent, meta) { this._context = context; this._parent = parent; this._meta = meta || {}; this.__cache = {}; } assign(Scope, { read: observeReader.read, Refs: TemplateContext, keyInfo: function (attr) { var info = {}; info.isDotSlash = attr.substr(0, 2) === './'; info.isThisDot = attr.substr(0, 5) === 'this.'; info.isThisAt = attr.substr(0, 5) === 'this@'; info.isInCurrentContext = info.isDotSlash || info.isThisDot || info.isThisAt; info.isInParentContext = attr.substr(0, 3) === '../'; info.isCurrentContext = attr === '.' || attr === 'this'; info.isParentContext = attr === '..'; info.isScope = attr === 'scope'; info.isInScopeVars = attr.substr(0, 11) === 'scope.vars.'; info.isInScope = info.isInScopeVars || attr.substr(0, 6) === 'scope.' || attr.substr(0, 6) === 'scope@'; info.isContextBased = info.isInCurrentContext || info.isInParentContext || info.isCurrentContext || info.isParentContext; return info; } }); assign(Scope.prototype, { add: function (context, meta) { if (context !== this._context) { return new this.constructor(context, this, meta); } else { return this; } }, find: function (attr) { return this.read(attr, { currentScopeOnly: false }); }, read: function (attr, options) { options = options || {}; if (attr === './') { attr = '.'; } var keyInfo = Scope.keyInfo(attr); if (keyInfo.isContextBased && (this._meta.notContext || this._meta.special)) { return this._parent.read(attr, options); } var currentScopeOnly = 'currentScopeOnly' in options ? options.currentScopeOnly : true; if (keyInfo.isInCurrentContext) { currentScopeOnly = true; attr = keyInfo.isDotSlash ? attr.substr(2) : attr.substr(5); } else if ((keyInfo.isInParentContext || keyInfo.isParentContext) && this._parent) { var parent = this._parent; while (parent._meta.notContext || parent._meta.special) { parent = parent._parent; } if (keyInfo.isParentContext) { return observeReader.read(parent._context, [], options); } return parent.read(attr.substr(3) || '.', options); } else if (keyInfo.isCurrentContext) { return observeReader.read(this._context, [], options); } else if (keyInfo.isScope) { return { value: this }; } var keyReads = observeReader.reads(attr), keyRead, key, value; if (keyInfo.isInScope) { keyReads = keyReads.slice(1); keyRead = keyReads[0]; key = keyRead.key; value = this[key]; value = typeof value !== 'undefined' ? value : this.templateContext[key]; if (keyRead.at) { value = value.bind(this); } if (keyReads.length === 1) { return { value: value }; } else if (value) { return observeReader.read(value, keyReads.slice(1)); } else { return this.getTemplateContext()._read(keyReads); } } return this._read(keyReads, options, currentScopeOnly); }, _read: function (keyReads, options, currentScopeOnly) { var currentScope = this, currentContext, undefinedObserves = [], currentObserve, currentReads, setObserveDepth = -1, currentSetReads, currentSetObserve, readOptions = assign({ foundObservable: function (observe, nameIndex) { currentObserve = observe; currentReads = keyReads.slice(nameIndex); }, earlyExit: function (parentValue, nameIndex) { if (nameIndex > setObserveDepth || nameIndex === setObserveDepth && (typeof parentValue === 'object' && keyReads[nameIndex].key in parentValue)) { currentSetObserve = currentObserve; currentSetReads = currentReads; setObserveDepth = nameIndex; } } }, options); var isRecording = ObservationRecorder.isRecording(); while (currentScope) { currentContext = currentScope._context; if ((!options || options.special !== true) && currentScope._meta.special) { currentScope = currentScope._parent; continue; } if (options && options.special && !currentScope._meta.special) { currentScope = currentScope._parent; continue; } if (currentContext !== null && (typeof currentContext === 'object' || typeof currentContext === 'function')) { var getObserves = ObservationRecorder.trap(); var data = observeReader.read(currentContext, keyReads, readOptions); var observes = getObserves(); if (data.value !== undefined) { if (!observes.length && isRecording) { currentObserve = data.parent; currentReads = keyReads.slice(keyReads.length - 1); } else { ObservationRecorder.addMany(observes); } return { scope: currentScope, rootObserve: currentObserve, value: data.value, reads: currentReads }; } else { undefinedObserves.push.apply(undefinedObserves, observes); } } var parentIsNormalContext = currentScope._parent && currentScope._parent._meta && !currentScope._parent._meta.notContext && !currentScope._parent._meta.special; if (currentScopeOnly && parentIsNormalContext) { currentScope = null; } else { currentScope = currentScope._parent; } } ObservationRecorder.addMany(undefinedObserves); return { setRoot: currentSetObserve, reads: currentSetReads, value: undefined }; }, get: function (key, options) { options = assign({ isArgument: true }, options); var res = this.read(key, options); return res.value; }, peek: ObservationRecorder.ignore(function (key, options) { return this.get(key, options); }), peak: ObservationRecorder.ignore(function (key, options) { canLog.warn('peak is deprecated, please use peek instead'); return this.peek(key, options); }), getScope: function (tester) { var scope = this; while (scope) { if (tester(scope)) { return scope; } scope = scope._parent; } }, getContext: function (tester) { var res = this.getScope(tester); return res && res._context; }, getTemplateContext: function () { var lastScope; var templateContext = this.getScope(function (scope) { lastScope = scope; return scope._context instanceof TemplateContext; }); if (!templateContext) { templateContext = new Scope(new TemplateContext()); lastScope._parent = templateContext; } return templateContext; }, getRoot: function () { var cur = this, child = this; while (cur._parent) { child = cur; cur = cur._parent; } if (cur._context instanceof Scope.Refs) { cur = child; } return cur._context; }, getDataForScopeSet: function getDataForScopeSet(key, options) { var keyInfo = Scope.keyInfo(key), parent; if (keyInfo.isCurrentContext) { return { parent: this._context, how: 'setValue' }; } else if (keyInfo.isInParentContext || keyInfo.isParentContext) { parent = this._parent; while (parent._meta.notContext) { parent = parent._parent; } if (keyInfo.isParentContext) { return { parent: parent._context, how: 'setValue' }; } return { how: 'set', parent: parent, passOptions: true, key: key.substr(3) || '.' }; } else if (keyInfo.isInScope) { if (keyInfo.isInScopeVars) { return { parent: this.vars, how: 'set', key: key.substr(11) }; } key = key.substr(6); if (key.indexOf('.') < 0) { return { parent: this.templateContext, how: 'setKeyValue', key: key }; } return { parent: this.getTemplateContext(), how: 'set', key: key }; } var dotIndex = key.lastIndexOf('.'), slashIndex = key.lastIndexOf('/'), contextPath, propName; if (slashIndex > dotIndex) { contextPath = key.substring(0, slashIndex); propName = key.substring(slashIndex + 1, key.length); } else { if (dotIndex !== -1) { contextPath = key.substring(0, dotIndex); propName = key.substring(dotIndex + 1, key.length); } else { contextPath = '.'; propName = key; } } var context = this.read(contextPath, options).value; if (context === undefined) { return { error: 'Attempting to set a value at ' + key + ' where ' + contextPath + ' is undefined.' }; } if (!canReflect.isObservableLike(context) && canReflect.isObservableLike(context[propName])) { if (canReflect.isMapLike(context[propName])) { return { parent: context, key: propName, how: 'updateDeep', warn: 'can-view-scope: Merging data into "' + propName + '" because its parent is non-observable' }; } else if (canReflect.isValueLike(context[propName])) { return { parent: context, key: propName, how: 'setValue' }; } else { return { parent: context, how: 'write', key: propName, passOptions: true }; } } else { return { parent: context, how: 'write', key: propName, passOptions: true }; } }, set: function (key, value, options) { options = options || {}; var data = this.getDataForScopeSet(key, options); var parent = data.parent; if (data.error) { return canLog.error(data.error); } if (data.warn) { canLog.warn(data.warn); } switch (data.how) { case 'set': parent.set(data.key, value, data.passOptions ? options : undefined); break; case 'write': observeReader.write(parent, data.key, value, options); break; case 'setValue': canReflect.setValue('key' in data ? parent[data.key] : parent, value); break; case 'setKeyValue': canReflect.setKeyValue(parent, data.key, value); break; case 'updateDeep': canReflect.updateDeep(parent[data.key], value); break; } }, attr: ObservationRecorder.ignore(function (key, value, options) { canLog.warn('can-view-scope::attr is deprecated, please use peek, get or set'); options = assign({ isArgument: true }, options); if (arguments.length === 2) { return this.set(key, value, options); } else { return this.get(key, options); } }), computeData: function (key, options) { return makeComputeData(this, key, options); }, compute: function (key, options) { return this.computeData(key, options).compute; }, cloneFromRef: function () { var contexts = []; var scope = this, context, parent; while (scope) { context = scope._context; if (context instanceof Scope.Refs) { parent = scope._parent; break; } contexts.unshift(context); scope = scope._parent; } if (parent) { each(contexts, function (context) { parent = parent.add(context); }); return parent; } else { return this; } } }); defineLazyValue(Scope.prototype, 'templateContext', function () { return this.getTemplateContext()._context; }); defineLazyValue(Scope.prototype, 'vars', function () { return this.templateContext.vars; }); defineLazyValue(Scope.prototype, 'root', function () { return this.getRoot(); }); var specialKeywords = [ 'index', 'key', 'element', 'event', 'viewModel', 'arguments' ]; var readFromSpecialContexts = function (key) { return function () { return this._read([{ key: key, at: false }], { special: true }).value; }; }; specialKeywords.forEach(function (key) { Object.defineProperty(Scope.prototype, key, { get: readFromSpecialContexts(key) }); }); namespace.view = namespace.view || {}; module.exports = namespace.view.Scope = Scope; }); /*can-stache@4.0.0-pre.26#src/set-identifier*/ define('can-stache/src/set-identifier', function (require, exports, module) { module.exports = function SetIdentifier(value) { this.value = value; }; }); /*can-stache@4.0.0-pre.26#expressions/call*/ define('can-stache/expressions/call', [ 'require', 'exports', 'module', 'can-view-scope', 'can-stache/expressions/hashes', 'can-stache/src/set-identifier', 'can-observation', 'can-symbol', 'can-simple-observable/setter/setter', 'can-stache/src/expression-helpers', 'can-reflect', 'can-util/js/is-empty-object/is-empty-object', 'can-assign' ], function (require, exports, module) { var Scope = require('can-view-scope'); var Hashes = require('can-stache/expressions/hashes'); var SetIdentifier = require('can-stache/src/set-identifier'); var Observation = require('can-observation'); var canSymbol = require('can-symbol'); var sourceTextSymbol = canSymbol.for('can-stache.sourceText'); var SetterObservable = require('can-simple-observable/setter/setter'); var expressionHelpers = require('can-stache/src/expression-helpers'); var canReflect = require('can-reflect'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var assign = require('can-assign'); var Call = function (methodExpression, argExpressions) { this.methodExpr = methodExpression; this.argExprs = argExpressions.map(expressionHelpers.convertToArgExpression); }; Call.prototype.args = function (scope) { var hashExprs = {}; var args = []; for (var i = 0, len = this.argExprs.length; i < len; i++) { var arg = this.argExprs[i]; if (arg.expr instanceof Hashes) { assign(hashExprs, arg.expr.hashExprs); } var value = arg.value.apply(arg, arguments); args.push({ call: !arg.modifiers || !arg.modifiers.compute, value: value }); } return function (doNotWrapArguments) { var finalArgs = []; if (!isEmptyObject(hashExprs)) { finalArgs.hashExprs = hashExprs; } for (var i = 0, len = args.length; i < len; i++) { if (doNotWrapArguments) { finalArgs[i] = args[i].value; } else { finalArgs[i] = args[i].call ? canReflect.getValue(args[i].value) : expressionHelpers.toCompute(args[i].value); } } return finalArgs; }; }; Call.prototype.value = function (scope, helperOptions) { var method = this.methodExpr.value(scope); var metadata = method.metadata || {}; assign(this, metadata); var getArgs = this.args(scope); var computeFn = function (newVal) { var func = canReflect.getValue(method.fn || method); if (typeof func === 'function') { var args = getArgs(metadata.isLiveBound); if (metadata.isHelper && helperOptions) { if (args.hashExprs && helperOptions.exprData) { helperOptions.exprData.hashExprs = args.hashExprs; } args.push(helperOptions); } if (arguments.length) { args.unshift(new SetIdentifier(newVal)); } return func.apply(null, args); } }; Object.defineProperty(computeFn, 'name', { value: '{{' + this.sourceText() + '}}' }); if (helperOptions && helperOptions.doNotWrapInObservation) { return computeFn(); } else { var computeValue = new SetterObservable(computeFn, computeFn); Observation.temporarilyBind(computeValue); return computeValue; } }; Call.prototype.sourceText = function () { var args = this.argExprs.map(function (arg) { return arg.sourceText(); }); return this.methodExpr.sourceText() + '(' + args.join(',') + ')'; }; Call.prototype.closingTag = function () { if (this.methodExpr[sourceTextSymbol]) { return this.methodExpr[sourceTextSymbol]; } return this.methodExpr.key; }; module.exports = Call; }); /*can-attribute-encoder@0.3.2#can-attribute-encoder*/ define('can-attribute-encoder', [ 'require', 'exports', 'module', 'can-namespace', 'can-log/dev/dev' ], function (require, exports, module) { var namespace = require('can-namespace'); var dev = require('can-log/dev/dev'); function each(items, callback) { for (var i = 0; i < items.length; i++) { callback(items[i], i); } } function makeMap(str) { var obj = {}, items = str.split(','); each(items, function (name) { obj[name] = true; }); return obj; } var caseMattersAttributes = makeMap('allowReorder,attributeName,attributeType,autoReverse,baseFrequency,baseProfile,calcMode,clipPathUnits,contentScriptType,contentStyleType,diffuseConstant,edgeMode,externalResourcesRequired,filterRes,filterUnits,glyphRef,gradientTransform,gradientUnits,kernelMatrix,kernelUnitLength,keyPoints,keySplines,keyTimes,lengthAdjust,limitingConeAngle,markerHeight,markerUnits,markerWidth,maskContentUnits,maskUnits,patternContentUnits,patternTransform,patternUnits,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,repeatCount,repeatDur,requiredExtensions,requiredFeatures,specularConstant,specularExponent,spreadMethod,startOffset,stdDeviation,stitchTiles,surfaceScale,systemLanguage,tableValues,textLength,viewBox,viewTarget,xChannelSelector,yChannelSelector'); function camelCaseToSpinalCase(match, lowerCaseChar, upperCaseChar) { return lowerCaseChar + '-' + upperCaseChar.toLowerCase(); } function startsWith(allOfIt, startsWith) { return allOfIt.indexOf(startsWith) === 0; } function endsWith(allOfIt, endsWith) { return allOfIt.length - allOfIt.indexOf(endsWith) === endsWith.length; } var regexes = { leftParens: /\(/g, rightParens: /\)/g, leftBrace: /\{/g, rightBrace: /\}/g, camelCase: /([a-z])([A-Z])/g, forwardSlash: /\//g, space: /\s/g, uppercase: /[A-Z]/g, uppercaseDelimiterThenChar: /:u:([a-z])/g, caret: /\^/g, dollar: /\$/g, at: /@/g }; var delimiters = { prependUppercase: ':u:', replaceSpace: ':s:', replaceForwardSlash: ':f:', replaceLeftParens: ':lp:', replaceRightParens: ':rp:', replaceLeftBrace: ':lb:', replaceRightBrace: ':rb:', replaceCaret: ':c:', replaceDollar: ':d:', replaceAt: ':at:' }; var encoder = {}; encoder.encode = function (name) { var encoded = name; if (!caseMattersAttributes[encoded] && encoded.match(regexes.camelCase)) { if (startsWith(encoded, 'on:') || endsWith(encoded, ':to') || endsWith(encoded, ':from') || endsWith(encoded, ':bind')) { encoded = encoded.replace(regexes.uppercase, function (char) { return delimiters.prependUppercase + char.toLowerCase(); }); } else { encoded = encoded.replace(regexes.camelCase, camelCaseToSpinalCase); dev.warn('can-attribute-encoder: Found attribute with name: ' + name + '. Converting to: ' + encoded + '.'); } } encoded = encoded.replace(regexes.space, delimiters.replaceSpace).replace(regexes.forwardSlash, delimiters.replaceForwardSlash).replace(regexes.leftParens, delimiters.replaceLeftParens).replace(regexes.rightParens, delimiters.replaceRightParens).replace(regexes.leftBrace, delimiters.replaceLeftBrace).replace(regexes.rightBrace, delimiters.replaceRightBrace).replace(regexes.caret, delimiters.replaceCaret).replace(regexes.dollar, delimiters.replaceDollar).replace(regexes.at, delimiters.replaceAt); return encoded; }; encoder.decode = function (name) { var decoded = name; decoded = decoded.replace(delimiters.replaceLeftParens, '(').replace(delimiters.replaceRightParens, ')').replace(delimiters.replaceLeftBrace, '{').replace(delimiters.replaceRightBrace, '}').replace(delimiters.replaceForwardSlash, '/').replace(delimiters.replaceSpace, ' ').replace(delimiters.replaceCaret, '^').replace(delimiters.replaceDollar, '$').replace(delimiters.replaceAt, '@'); if (!caseMattersAttributes[decoded] && decoded.match(regexes.uppercaseDelimiterThenChar)) { if (startsWith(decoded, 'on:') || endsWith(decoded, ':to') || endsWith(decoded, ':from') || endsWith(decoded, ':bind')) { decoded = decoded.replace(regexes.uppercaseDelimiterThenChar, function (match, char) { return char.toUpperCase(); }); } } return decoded; }; if (namespace.encoder) { throw new Error('You can\'t have two versions of can-attribute-encoder, check your dependencies'); } else { module.exports = namespace.encoder = encoder; } }); /*can-view-parser@4.0.0-pre.0#can-view-parser*/ define('can-view-parser', [ 'require', 'exports', 'module', 'can-namespace', 'can-log/dev/dev', 'can-attribute-encoder' ], function (require, exports, module) { var namespace = require('can-namespace'), dev = require('can-log/dev/dev'), encoder = require('can-attribute-encoder'); function each(items, callback) { for (var i = 0; i < items.length; i++) { callback(items[i], i); } } function makeMap(str) { var obj = {}, items = str.split(','); each(items, function (name) { obj[name] = true; }); return obj; } function handleIntermediate(intermediate, handler) { for (var i = 0, len = intermediate.length; i < len; i++) { var item = intermediate[i]; handler[item.tokenType].apply(handler, item.args); } return intermediate; } function countLines(input) { return input.split('\n').length - 1; } var alphaNumeric = 'A-Za-z0-9', alphaNumericHU = '-:_' + alphaNumeric, magicStart = '{{', endTag = new RegExp('^<\\/([' + alphaNumericHU + ']+)[^>]*>'), magicMatch = new RegExp('\\{\\{(![\\s\\S]*?!|[\\s\\S]*?)\\}\\}\\}?', 'g'), space = /\s/, alphaRegex = new RegExp('[' + alphaNumeric + ']'); var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'); var caseMattersElements = makeMap('altGlyph,altGlyphDef,altGlyphItem,animateColor,animateMotion,animateTransform,clipPath,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,foreignObject,glyphRef,linearGradient,radialGradient,textPath'); var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); var special = makeMap('script'); var tokenTypes = 'start,end,close,attrStart,attrEnd,attrValue,chars,comment,special,done'.split(','); var startOppositesMap = { '{': '}', '(': ')' }; var fn = function () { }; var HTMLParser = function (html, handler, returnIntermediate) { if (typeof html === 'object') { return handleIntermediate(html, handler); } var intermediate = []; handler = handler || {}; if (returnIntermediate) { each(tokenTypes, function (name) { var callback = handler[name] || fn; handler[name] = function () { if (callback.apply(this, arguments) !== false) { var end = arguments.length; if (arguments[end - 1] === undefined) { end = arguments.length - 1; } end = arguments.length; intermediate.push({ tokenType: name, args: [].slice.call(arguments, 0, end) }); } }; }); } function parseStartTag(tag, tagName, rest, unary) { tagName = caseMattersElements[tagName] ? tagName : tagName.toLowerCase(); if (closeSelf[tagName] && stack.last() === tagName) { parseEndTag('', tagName); } unary = empty[tagName] || !!unary; handler.start(tagName, unary, lineNo); if (!unary) { stack.push(tagName); } HTMLParser.parseAttrs(rest, handler, lineNo); lineNo += countLines(tag); handler.end(tagName, unary, lineNo); } function parseEndTag(tag, tagName) { var pos; if (!tagName) { pos = 0; } else { tagName = caseMattersElements[tagName] ? tagName : tagName.toLowerCase(); for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos] === tagName) { break; } } } if (typeof tag === 'undefined') { if (stack.length > 0) { if (handler.filename) { dev.warn(handler.filename + ': expected closing tag </' + stack[pos] + '>'); } else { dev.warn('expected closing tag </' + stack[pos] + '>'); } } } else if (pos < 0 || pos !== stack.length - 1) { if (stack.length > 0) { if (handler.filename) { dev.warn(handler.filename + ':' + lineNo + ': unexpected closing tag ' + tag + ' expected </' + stack[stack.length - 1] + '>'); } else { dev.warn(lineNo + ': unexpected closing tag ' + tag + ' expected </' + stack[stack.length - 1] + '>'); } } else { if (handler.filename) { dev.warn(handler.filename + ':' + lineNo + ': unexpected closing tag ' + tag); } else { dev.warn(lineNo + ': unexpected closing tag ' + tag); } } } if (pos >= 0) { for (var i = stack.length - 1; i >= pos; i--) { if (handler.close) { handler.close(stack[i], lineNo); } } stack.length = pos; } } function parseMustache(mustache, inside) { if (handler.special) { handler.special(inside, lineNo); } } var callChars = function () { if (charsText) { if (handler.chars) { handler.chars(charsText, lineNo); } lineNo += countLines(charsText); } charsText = ''; }; var index, chars, match, lineNo, stack = [], last = html, charsText = ''; lineNo = 1; stack.last = function () { return this[this.length - 1]; }; while (html) { chars = true; if (!stack.last() || !special[stack.last()]) { if (html.indexOf('<!--') === 0) { index = html.indexOf('-->'); if (index >= 0) { callChars(); if (handler.comment) { handler.comment(html.substring(4, index), lineNo); } lineNo += countLines(html.substring(0, index + 3)); html = html.substring(index + 3); chars = false; } } else if (html.indexOf('</') === 0) { match = html.match(endTag); if (match) { callChars(); match[0].replace(endTag, parseEndTag); lineNo += countLines(html.substring(0, match[0].length)); html = html.substring(match[0].length); chars = false; } } else if (html.indexOf('<') === 0) { var res = HTMLParser.searchStartTag(html); if (res) { callChars(); parseStartTag.apply(null, res.match); html = res.html; chars = false; } } else if (html.indexOf(magicStart) === 0) { match = html.match(magicMatch); if (match) { callChars(); match[0].replace(magicMatch, parseMustache); lineNo += countLines(html.substring(0, match[0].length)); html = html.substring(match[0].length); } } if (chars) { index = findBreak(html, magicStart); if (index === 0 && html === last) { charsText += html.charAt(0); html = html.substr(1); index = findBreak(html, magicStart); } var text = index < 0 ? html : html.substring(0, index); html = index < 0 ? '' : html.substring(index); if (text) { charsText += text; } } } else { html = html.replace(new RegExp('([\\s\\S]*?)</' + stack.last() + '[^>]*>'), function (all, text) { text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2'); if (handler.chars) { handler.chars(text, lineNo); } lineNo += countLines(text); return ''; }); parseEndTag('', stack.last()); } if (html === last) { throw new Error('Parse Error: ' + html); } last = html; } callChars(); parseEndTag(); handler.done(lineNo); return intermediate; }; var callAttrStart = function (state, curIndex, handler, rest, lineNo) { var attrName = rest.substring(typeof state.nameStart === 'number' ? state.nameStart : curIndex, curIndex), newAttrName = encoder.encode(attrName); state.attrStart = newAttrName; handler.attrStart(state.attrStart, lineNo); state.inName = false; }; var callAttrEnd = function (state, curIndex, handler, rest, lineNo) { if (state.valueStart !== undefined && state.valueStart < curIndex) { var val = rest.substring(state.valueStart, curIndex); var quotedVal, closedQuote; quotedVal = rest.substring(state.valueStart - 1, curIndex + 1); quotedVal = quotedVal.trim(); closedQuote = quotedVal.charAt(quotedVal.length - 1); if (state.inQuote !== closedQuote) { if (handler.filename) { dev.warn(handler.filename + ':' + lineNo + ': End quote is missing for ' + val); } else { dev.warn(lineNo + ': End quote is missing for ' + val); } } handler.attrValue(val, lineNo); } handler.attrEnd(state.attrStart, lineNo); state.attrStart = undefined; state.valueStart = undefined; state.inValue = false; state.inName = false; state.lookingForEq = false; state.inQuote = false; state.lookingForName = true; }; var findBreak = function (str, magicStart) { var magicLength = magicStart.length; for (var i = 0, len = str.length; i < len; i++) { if (str[i] === '<' || str.substr(i, magicLength) === magicStart) { return i; } } return -1; }; HTMLParser.parseAttrs = function (rest, handler, lineNo) { if (!rest) { return; } var i = 0; var curIndex; var state = { inName: false, nameStart: undefined, inValue: false, valueStart: undefined, inQuote: false, attrStart: undefined, lookingForName: true, lookingForValue: false, lookingForEq: false }; while (i < rest.length) { curIndex = i; var cur = rest.charAt(i); i++; if (magicStart === rest.substr(curIndex, magicStart.length)) { if (state.inValue && curIndex > state.valueStart) { handler.attrValue(rest.substring(state.valueStart, curIndex), lineNo); } else if (state.inName && state.nameStart < curIndex) { callAttrStart(state, curIndex, handler, rest, lineNo); callAttrEnd(state, curIndex, handler, rest, lineNo); } else if (state.lookingForValue) { state.inValue = true; } else if (state.lookingForEq && state.attrStart) { callAttrEnd(state, curIndex, handler, rest, lineNo); } magicMatch.lastIndex = curIndex; var match = magicMatch.exec(rest); if (match) { handler.special(match[1], lineNo); i = curIndex + match[0].length; if (state.inValue) { state.valueStart = curIndex + match[0].length; } } } else if (state.inValue) { if (state.inQuote) { if (cur === state.inQuote) { callAttrEnd(state, curIndex, handler, rest, lineNo); } } else if (space.test(cur)) { callAttrEnd(state, curIndex, handler, rest, lineNo); } } else if (cur === '=' && (state.lookingForEq || state.lookingForName || state.inName)) { if (!state.attrStart) { callAttrStart(state, curIndex, handler, rest, lineNo); } state.lookingForValue = true; state.lookingForEq = false; state.lookingForName = false; } else if (state.inName) { var started = rest[state.nameStart], otherStart, otherOpposite; if (startOppositesMap[started] === cur) { otherStart = started === '{' ? '(' : '{'; otherOpposite = startOppositesMap[otherStart]; if (rest[curIndex + 1] === otherOpposite) { callAttrStart(state, curIndex + 2, handler, rest, lineNo); i++; } else { callAttrStart(state, curIndex + 1, handler, rest, lineNo); } state.lookingForEq = true; } else if (space.test(cur) && started !== '{' && started !== '(') { callAttrStart(state, curIndex, handler, rest, lineNo); state.lookingForEq = true; } } else if (state.lookingForName) { if (!space.test(cur)) { if (state.attrStart) { callAttrEnd(state, curIndex, handler, rest, lineNo); } state.nameStart = curIndex; state.inName = true; } } else if (state.lookingForValue) { if (!space.test(cur)) { state.lookingForValue = false; state.inValue = true; if (cur === '\'' || cur === '"') { state.inQuote = cur; state.valueStart = curIndex + 1; } else { state.valueStart = curIndex; } } else if (i === rest.length) { callAttrEnd(state, curIndex, handler, rest, lineNo); } } } if (state.inName) { callAttrStart(state, curIndex + 1, handler, rest, lineNo); callAttrEnd(state, curIndex + 1, handler, rest, lineNo); } else if (state.lookingForEq || state.lookingForValue || state.inValue) { callAttrEnd(state, curIndex + 1, handler, rest, lineNo); } magicMatch.lastIndex = 0; }; HTMLParser.searchStartTag = function (html) { var closingIndex = html.indexOf('>'); if (closingIndex === -1 || !alphaRegex.test(html[1])) { return null; } var tagName, tagContent, match, rest = '', unary = ''; var startTag = html.substring(0, closingIndex + 1); var isUnary = startTag[startTag.length - 2] === '/'; var spaceIndex = startTag.search(space); if (isUnary) { unary = '/'; tagContent = startTag.substring(1, startTag.length - 2).trim(); } else { tagContent = startTag.substring(1, startTag.length - 1).trim(); } if (spaceIndex === -1) { tagName = tagContent; } else { spaceIndex--; tagName = tagContent.substring(0, spaceIndex); rest = tagContent.substring(spaceIndex); } match = [ startTag, tagName, rest, unary ]; return { match: match, html: html.substring(startTag.length) }; }; module.exports = namespace.HTMLParser = HTMLParser; }); /*can-util@3.10.18#js/set-immediate/set-immediate*/ define('can-util/js/set-immediate/set-immediate', [ 'require', 'exports', 'module', 'can-globals/global/global' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var global = require('can-globals/global/global')(); module.exports = global.setImmediate || function (cb) { return setTimeout(cb, 0); }; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/child-nodes/child-nodes*/ define('can-util/dom/child-nodes/child-nodes', function (require, exports, module) { 'use strict'; function childNodes(node) { var childNodes = node.childNodes; if ('length' in childNodes) { return childNodes; } else { var cur = node.firstChild; var nodes = []; while (cur) { nodes.push(cur); cur = cur.nextSibling; } return nodes; } } module.exports = childNodes; }); /*can-util@3.10.18#dom/contains/contains*/ define('can-util/dom/contains/contains', function (require, exports, module) { 'use strict'; module.exports = function (child) { return this.contains(child); }; }); /*can-util@3.10.18#dom/mutate/mutate*/ define('can-util/dom/mutate/mutate', [ 'require', 'exports', 'module', 'can-util/js/make-array/make-array', 'can-util/js/set-immediate/set-immediate', 'can-cid', 'can-globals/mutation-observer/mutation-observer', 'can-util/dom/child-nodes/child-nodes', 'can-util/dom/contains/contains', 'can-util/dom/dispatch/dispatch', 'can-globals/document/document', 'can-util/dom/data/data' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var makeArray = require('can-util/js/make-array/make-array'); var setImmediate = require('can-util/js/set-immediate/set-immediate'); var CID = require('can-cid'); var getMutationObserver = require('can-globals/mutation-observer/mutation-observer'); var childNodes = require('can-util/dom/child-nodes/child-nodes'); var domContains = require('can-util/dom/contains/contains'); var domDispatch = require('can-util/dom/dispatch/dispatch'); var getDocument = require('can-globals/document/document'); var domData = require('can-util/dom/data/data'); var mutatedElements; var checks = { inserted: function (root, elem) { return domContains.call(root, elem); }, removed: function (root, elem) { return !domContains.call(root, elem); } }; var fireOn = function (elems, root, check, event, dispatched) { if (!elems.length) { return; } var children, cid; for (var i = 0, elem; (elem = elems[i]) !== undefined; i++) { cid = CID(elem); if (elem.getElementsByTagName && check(root, elem) && !dispatched[cid]) { dispatched[cid] = true; children = makeArray(elem.getElementsByTagName('*')); domDispatch.call(elem, event, [], false); if (event === 'removed') { domData.delete.call(elem); } for (var j = 0, child; (child = children[j]) !== undefined; j++) { cid = CID(child); if (!dispatched[cid]) { domDispatch.call(child, event, [], false); if (event === 'removed') { domData.delete.call(child); } dispatched[cid] = true; } } } } }; var fireMutations = function () { var mutations = mutatedElements; mutatedElements = null; var firstElement = mutations[0][1][0]; var doc = getDocument() || firstElement.ownerDocument || firstElement; var root = doc.contains ? doc : doc.documentElement; var dispatched = { inserted: {}, removed: {} }; mutations.forEach(function (mutation) { fireOn(mutation[1], root, checks[mutation[0]], mutation[0], dispatched[mutation[0]]); }); }; var mutated = function (elements, type) { if (!getMutationObserver() && elements.length) { var firstElement = elements[0]; var doc = getDocument() || firstElement.ownerDocument || firstElement; var root = doc.contains ? doc : doc.documentElement; if (checks.inserted(root, firstElement)) { if (!mutatedElements) { mutatedElements = []; setImmediate(fireMutations); } mutatedElements.push([ type, elements ]); } } }; module.exports = { appendChild: function (child) { if (getMutationObserver()) { this.appendChild(child); } else { var children; if (child.nodeType === 11) { children = makeArray(childNodes(child)); } else { children = [child]; } this.appendChild(child); mutated(children, 'inserted'); } }, insertBefore: function (child, ref, document) { if (getMutationObserver()) { this.insertBefore(child, ref); } else { var children; if (child.nodeType === 11) { children = makeArray(childNodes(child)); } else { children = [child]; } this.insertBefore(child, ref); mutated(children, 'inserted'); } }, removeChild: function (child) { if (getMutationObserver()) { this.removeChild(child); } else { mutated([child], 'removed'); this.removeChild(child); } }, replaceChild: function (newChild, oldChild) { if (getMutationObserver()) { this.replaceChild(newChild, oldChild); } else { var children; if (newChild.nodeType === 11) { children = makeArray(childNodes(newChild)); } else { children = [newChild]; } mutated([oldChild], 'removed'); this.replaceChild(newChild, oldChild); mutated(children, 'inserted'); } }, inserted: function (elements) { mutated(elements, 'inserted'); }, removed: function (elements) { mutated(elements, 'removed'); } }; }(function () { return this; }(), require, exports, module)); }); /*can-cid@1.1.2#map/map*/ define('can-cid/map/map', [ 'require', 'exports', 'module', 'can-cid', 'can-cid/helpers' ], function (require, exports, module) { 'use strict'; var getCID = require('can-cid').get; var helpers = require('can-cid/helpers'); var CIDMap; if (typeof Map !== 'undefined') { CIDMap = Map; } else { var CIDMap = function () { this.values = {}; }; CIDMap.prototype.set = function (key, value) { this.values[getCID(key)] = { key: key, value: value }; }; CIDMap.prototype['delete'] = function (key) { var has = getCID(key) in this.values; if (has) { delete this.values[getCID(key)]; } return has; }; CIDMap.prototype.forEach = function (cb, thisArg) { helpers.each(this.values, function (pair) { return cb.call(thisArg || this, pair.value, pair.key, this); }, this); }; CIDMap.prototype.has = function (key) { return getCID(key) in this.values; }; CIDMap.prototype.get = function (key) { var obj = this.values[getCID(key)]; return obj && obj.value; }; CIDMap.prototype.clear = function () { return this.values = {}; }; Object.defineProperty(CIDMap.prototype, 'size', { get: function () { var size = 0; helpers.each(this.values, function () { size++; }); return size; } }); } module.exports = CIDMap; }); /*can-util@3.10.18#js/cid-map/cid-map*/ define('can-util/js/cid-map/cid-map', [ 'require', 'exports', 'module', 'can-cid/map/map' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; module.exports = require('can-cid/map/map'); }(function () { return this; }(), require, exports, module)); }); /*can-view-nodelist@3.1.1#can-view-nodelist*/ define('can-view-nodelist', [ 'require', 'exports', 'module', 'can-util/js/make-array/make-array', 'can-util/js/each/each', 'can-namespace', 'can-util/dom/mutate/mutate', 'can-util/js/cid-map/cid-map' ], function (require, exports, module) { var makeArray = require('can-util/js/make-array/make-array'); var each = require('can-util/js/each/each'); var namespace = require('can-namespace'); var domMutate = require('can-util/dom/mutate/mutate'); var CIDMap = require('can-util/js/cid-map/cid-map'); var nodeMap = new CIDMap(), splice = [].splice, push = [].push, itemsInChildListTree = function (list) { var count = 0; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; if (item.nodeType) { count++; } else { count += itemsInChildListTree(item); } } return count; }, replacementMap = function (replacements) { var map = new CIDMap(); for (var i = 0, len = replacements.length; i < len; i++) { var node = nodeLists.first(replacements[i]); map.set(node, replacements[i]); } return map; }, addUnfoundAsDeepChildren = function (list, rMap) { rMap.forEach(function (replacement) { list.newDeepChildren.push(replacement); }); }; var nodeLists = { update: function (nodeList, newNodes) { var oldNodes = nodeLists.unregisterChildren(nodeList); newNodes = makeArray(newNodes); var oldListLength = nodeList.length; splice.apply(nodeList, [ 0, oldListLength ].concat(newNodes)); if (nodeList.replacements) { nodeLists.nestReplacements(nodeList); nodeList.deepChildren = nodeList.newDeepChildren; nodeList.newDeepChildren = []; } else { nodeLists.nestList(nodeList); } return oldNodes; }, nestReplacements: function (list) { var index = 0, rMap = replacementMap(list.replacements), rCount = list.replacements.length; while (index < list.length && rCount) { var node = list[index], replacement = rMap.get(node); if (replacement) { rMap['delete'](node); list.splice(index, itemsInChildListTree(replacement), replacement); rCount--; } index++; } if (rCount) { addUnfoundAsDeepChildren(list, rMap); } list.replacements = []; }, nestList: function (list) { var index = 0; while (index < list.length) { var node = list[index], childNodeList = nodeMap.get(node); if (childNodeList) { if (childNodeList !== list) { list.splice(index, itemsInChildListTree(childNodeList), childNodeList); } } else { nodeMap.set(node, list); } index++; } }, last: function (nodeList) { var last = nodeList[nodeList.length - 1]; if (last.nodeType) { return last; } else { return nodeLists.last(last); } }, first: function (nodeList) { var first = nodeList[0]; if (first.nodeType) { return first; } else { return nodeLists.first(first); } }, flatten: function (nodeList) { var items = []; for (var i = 0; i < nodeList.length; i++) { var item = nodeList[i]; if (item.nodeType) { items.push(item); } else { items.push.apply(items, nodeLists.flatten(item)); } } return items; }, register: function (nodeList, unregistered, parent, directlyNested) { nodeList.unregistered = unregistered; nodeList.parentList = parent; nodeList.nesting = parent && typeof parent.nesting !== 'undefined' ? parent.nesting + 1 : 0; if (parent) { nodeList.deepChildren = []; nodeList.newDeepChildren = []; nodeList.replacements = []; if (parent !== true) { if (directlyNested) { parent.replacements.push(nodeList); } else { parent.newDeepChildren.push(nodeList); } } } else { nodeLists.nestList(nodeList); } return nodeList; }, unregisterChildren: function (nodeList) { var nodes = []; each(nodeList, function (node) { if (node.nodeType) { if (!nodeList.replacements) { nodeMap['delete'](node); } nodes.push(node); } else { push.apply(nodes, nodeLists.unregister(node, true)); } }); each(nodeList.deepChildren, function (nodeList) { nodeLists.unregister(nodeList, true); }); return nodes; }, unregister: function (nodeList, isChild) { var nodes = nodeLists.unregisterChildren(nodeList, true); if (nodeList.unregistered) { var unregisteredCallback = nodeList.unregistered; nodeList.replacements = nodeList.unregistered = null; if (!isChild) { var deepChildren = nodeList.parentList && nodeList.parentList.deepChildren; if (deepChildren) { var index = deepChildren.indexOf(nodeList); if (index !== -1) { deepChildren.splice(index, 1); } } } unregisteredCallback(); } return nodes; }, after: function (oldElements, newFrag) { var last = oldElements[oldElements.length - 1]; if (last.nextSibling) { domMutate.insertBefore.call(last.parentNode, newFrag, last.nextSibling); } else { domMutate.appendChild.call(last.parentNode, newFrag); } }, replace: function (oldElements, newFrag) { var selectedValue, parentNode = oldElements[0].parentNode; if (parentNode.nodeName.toUpperCase() === 'SELECT' && parentNode.selectedIndex >= 0) { selectedValue = parentNode.value; } if (oldElements.length === 1) { domMutate.replaceChild.call(parentNode, newFrag, oldElements[0]); } else { nodeLists.after(oldElements, newFrag); nodeLists.remove(oldElements); } if (selectedValue !== undefined) { parentNode.value = selectedValue; } }, remove: function (elementsToBeRemoved) { var parent = elementsToBeRemoved[0] && elementsToBeRemoved[0].parentNode; each(elementsToBeRemoved, function (child) { domMutate.removeChild.call(parent, child); }); }, nodeMap: nodeMap }; module.exports = namespace.nodeLists = nodeLists; }); /*can-util@3.10.18#dom/fragment/fragment*/ define('can-util/dom/fragment/fragment', [ 'require', 'exports', 'module', 'can-globals/document/document', 'can-util/dom/child-nodes/child-nodes' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getDocument = require('can-globals/document/document'), childNodes = require('can-util/dom/child-nodes/child-nodes'); var fragmentRE = /^\s*<(\w+)[^>]*>/, toString = {}.toString, fragment = function (html, name, doc) { if (name === undefined) { name = fragmentRE.test(html) && RegExp.$1; } if (html && toString.call(html.replace) === '[object Function]') { html = html.replace(/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, '<$1></$2>'); } var container = doc.createElement('div'), temp = doc.createElement('div'); if (name === 'tbody' || name === 'tfoot' || name === 'thead' || name === 'colgroup') { temp.innerHTML = '<table>' + html + '</table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild; } else if (name === 'col') { temp.innerHTML = '<table><colgroup>' + html + '</colgroup></table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild.firstChild; } else if (name === 'tr') { temp.innerHTML = '<table><tbody>' + html + '</tbody></table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild.firstChild; } else if (name === 'td' || name === 'th') { temp.innerHTML = '<table><tbody><tr>' + html + '</tr></tbody></table>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild.firstChild.firstChild; } else if (name === 'option') { temp.innerHTML = '<select>' + html + '</select>'; container = temp.firstChild.nodeType === 3 ? temp.lastChild : temp.firstChild; } else { container.innerHTML = '' + html; } var tmp = {}, children = childNodes(container); tmp.length = children.length; for (var i = 0; i < children.length; i++) { tmp[i] = children[i]; } return [].slice.call(tmp); }; var buildFragment = function (html, doc) { if (html && html.nodeType === 11) { return html; } if (!doc) { doc = getDocument(); } else if (doc.length) { doc = doc[0]; } var parts = fragment(html, undefined, doc), frag = (doc || document).createDocumentFragment(); for (var i = 0, length = parts.length; i < length; i++) { frag.appendChild(parts[i]); } return frag; }; module.exports = buildFragment; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/frag/frag*/ define('can-util/dom/frag/frag', [ 'require', 'exports', 'module', 'can-globals/document/document', 'can-util/dom/fragment/fragment', 'can-util/js/each/each', 'can-util/dom/child-nodes/child-nodes' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getDocument = require('can-globals/document/document'); var fragment = require('can-util/dom/fragment/fragment'); var each = require('can-util/js/each/each'); var childNodes = require('can-util/dom/child-nodes/child-nodes'); var makeFrag = function (item, doc) { var document = doc || getDocument(); var frag; if (!item || typeof item === 'string') { frag = fragment(item == null ? '' : '' + item, document); if (!frag.childNodes.length) { frag.appendChild(document.createTextNode('')); } return frag; } else if (item.nodeType === 11) { return item; } else if (typeof item.nodeType === 'number') { frag = document.createDocumentFragment(); frag.appendChild(item); return frag; } else if (typeof item.length === 'number') { frag = document.createDocumentFragment(); each(item, function (item) { frag.appendChild(makeFrag(item)); }); if (!childNodes(frag).length) { frag.appendChild(document.createTextNode('')); } return frag; } else { frag = fragment('' + item, document); if (!childNodes(frag).length) { frag.appendChild(document.createTextNode('')); } return frag; } }; module.exports = makeFrag; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/is-of-global-document/is-of-global-document*/ define('can-util/dom/is-of-global-document/is-of-global-document', [ 'require', 'exports', 'module', 'can-globals/document/document' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getDocument = require('can-globals/document/document'); module.exports = function (el) { return (el.ownerDocument || el) === getDocument(); }; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/events/make-mutation-event/make-mutation-event*/ define('can-util/dom/events/make-mutation-event/make-mutation-event', [ 'require', 'exports', 'module', 'can-util/dom/events/events', 'can-util/dom/data/data', 'can-globals/mutation-observer/mutation-observer', 'can-util/dom/dispatch/dispatch', 'can-util/dom/mutation-observer/document/document', 'can-globals/document/document', 'can-cid/map/map', 'can-util/js/string/string', 'can-util/dom/is-of-global-document/is-of-global-document' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var events = require('can-util/dom/events/events'); var domData = require('can-util/dom/data/data'); var getMutationObserver = require('can-globals/mutation-observer/mutation-observer'); var domDispatch = require('can-util/dom/dispatch/dispatch'); var mutationDocument = require('can-util/dom/mutation-observer/document/document'); var getDocument = require('can-globals/document/document'); var CIDMap = require('can-cid/map/map'); var string = require('can-util/js/string/string'); require('can-util/dom/is-of-global-document/is-of-global-document'); module.exports = function (specialEventName, mutationNodesProperty) { var originalAdd = events.addEventListener, originalRemove = events.removeEventListener; events.addEventListener = function (eventName) { if (eventName === specialEventName && getMutationObserver()) { var documentElement = getDocument().documentElement; var specialEventData = domData.get.call(documentElement, specialEventName + 'Data'); if (!specialEventData) { specialEventData = { handler: function (mutatedNode) { if (specialEventData.nodeIdsRespondingToInsert.has(mutatedNode)) { domDispatch.call(mutatedNode, specialEventName, [], false); specialEventData.nodeIdsRespondingToInsert.delete(mutatedNode); } }, nodeIdsRespondingToInsert: new CIDMap() }; mutationDocument['on' + string.capitalize(mutationNodesProperty)](specialEventData.handler); domData.set.call(documentElement, specialEventName + 'Data', specialEventData); } if (this.nodeType !== 11) { var count = specialEventData.nodeIdsRespondingToInsert.get(this) || 0; specialEventData.nodeIdsRespondingToInsert.set(this, count + 1); } } return originalAdd.apply(this, arguments); }; events.removeEventListener = function (eventName) { if (eventName === specialEventName && getMutationObserver()) { var documentElement = getDocument().documentElement; var specialEventData = domData.get.call(documentElement, specialEventName + 'Data'); if (specialEventData) { var newCount = specialEventData.nodeIdsRespondingToInsert.get(this) - 1; if (newCount) { specialEventData.nodeIdsRespondingToInsert.set(this, newCount); } else { specialEventData.nodeIdsRespondingToInsert.delete(this); } if (!specialEventData.nodeIdsRespondingToInsert.size) { mutationDocument['off' + string.capitalize(mutationNodesProperty)](specialEventData.handler); domData.clean.call(documentElement, specialEventName + 'Data'); } } } return originalRemove.apply(this, arguments); }; }; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/events/removed/removed*/ define('can-util/dom/events/removed/removed', [ 'require', 'exports', 'module', 'can-util/dom/events/make-mutation-event/make-mutation-event' ], function (require, exports, module) { 'use strict'; var makeMutationEvent = require('can-util/dom/events/make-mutation-event/make-mutation-event'); makeMutationEvent('removed', 'removedNodes'); }); /*can-view-live@4.0.0-pre.17#lib/core*/ define('can-view-live/lib/core', [ 'require', 'exports', 'module', 'can-view-parser', 'can-util/dom/events/events', 'can-view-nodelist', 'can-util/dom/frag/frag', 'can-util/dom/child-nodes/child-nodes', 'can-reflect', 'can-reflect-dependencies', 'can-util/dom/events/removed/removed' ], function (require, exports, module) { var parser = require('can-view-parser'); var domEvents = require('can-util/dom/events/events'); var nodeLists = require('can-view-nodelist'); var makeFrag = require('can-util/dom/frag/frag'); var childNodes = require('can-util/dom/child-nodes/child-nodes'); var canReflect = require('can-reflect'); var canReflectDeps = require('can-reflect-dependencies'); require('can-util/dom/events/removed/removed'); var live = { setup: function (el, bind, unbind) { var tornDown = false, data, teardown = function () { if (!tornDown) { tornDown = true; unbind(data); domEvents.removeEventListener.call(el, 'removed', teardown); } return true; }; data = { teardownCheck: function (parent) { return parent ? false : teardown(); } }; domEvents.addEventListener.call(el, 'removed', teardown); bind(data); return data; }, listen: function (el, compute, change) { return live.setup(el, function bind() { canReflect.onValue(compute, change, 'notify'); canReflectDeps.addMutatedBy(el, compute); }, function unbind(data) { canReflect.offValue(compute, change, 'notify'); canReflectDeps.deleteMutatedBy(el, compute); if (data.nodeList) { nodeLists.unregister(data.nodeList); } }); }, getAttributeParts: function (newVal) { var attrs = {}, attr; parser.parseAttrs(newVal, { attrStart: function (name) { attrs[name] = ''; attr = name; }, attrValue: function (value) { attrs[attr] += value; }, attrEnd: function () { } }); return attrs; }, isNode: function (obj) { return obj && obj.nodeType; }, addTextNodeIfNoChildren: function (frag) { if (!frag.firstChild) { frag.appendChild(frag.ownerDocument.createTextNode('')); } }, replace: function (nodes, val, teardown) { var oldNodes = nodes.slice(0), frag = makeFrag(val); nodeLists.register(nodes, teardown); nodeLists.update(nodes, childNodes(frag)); nodeLists.replace(oldNodes, frag); return nodes; }, getParentNode: function (el, defaultParentNode) { return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode; }, makeString: function (txt) { return txt == null ? '' : '' + txt; } }; module.exports = live; }); /*can-types@1.1.5#can-types*/ define('can-types', [ 'require', 'exports', 'module', 'can-namespace', 'can-reflect', 'can-symbol', 'can-log/dev/dev' ], function (require, exports, module) { var namespace = require('can-namespace'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var dev = require('can-log/dev/dev'); var types = { isMapLike: function (obj) { dev.warn('can-types.isMapLike(obj) is deprecated, please use `canReflect.isObservableLike(obj) && canReflect.isMapLike(obj)` instead.'); return canReflect.isObservableLike(obj) && canReflect.isMapLike(obj); }, isListLike: function (obj) { dev.warn('can-types.isListLike(obj) is deprecated, please use `canReflect.isObservableLike(obj) && canReflect.isListLike(obj)` instead.'); return canReflect.isObservableLike(obj) && canReflect.isListLike(obj); }, isPromise: function (obj) { dev.warn('can-types.isPromise is deprecated, please use canReflect.isPromise instead.'); return canReflect.isPromise(obj); }, isConstructor: function (func) { dev.warn('can-types.isConstructor is deprecated, please use canReflect.isConstructorLike instead.'); return canReflect.isConstructorLike(func); }, isCallableForValue: function (obj) { dev.warn('can-types.isCallableForValue(obj) is deprecated, please use `canReflect.isFunctionLike(obj) && !canReflect.isConstructorLike(obj)` instead.'); return obj && canReflect.isFunctionLike(obj) && !canReflect.isConstructorLike(obj); }, isCompute: function (obj) { dev.warn('can-types.isCompute is deprecated.'); return obj && obj.isComputed; }, get iterator() { dev.warn('can-types.iterator is deprecated, use `canSymbol.iterator || canSymbol.for("iterator")` instead.'); return canSymbol.iterator || canSymbol.for('iterator'); }, DefaultMap: null, DefaultList: null, queueTask: function (task) { var args = task[2] || []; task[0].apply(task[1], args); }, wrapElement: function (element) { return element; }, unwrapElement: function (element) { return element; } }; if (namespace.types) { throw new Error('You can\'t have two versions of can-types, check your dependencies'); } else { module.exports = namespace.types = types; } }); /*can-util@3.10.18#js/diff/diff*/ define('can-util/js/diff/diff', function (require, exports, module) { 'use strict'; var slice = [].slice; var defaultIdentity = function (a, b) { return a === b; }; function reverseDiff(oldDiffStopIndex, newDiffStopIndex, oldList, newList, identity) { var oldIndex = oldList.length - 1, newIndex = newList.length - 1; while (oldIndex > oldDiffStopIndex && newIndex > newDiffStopIndex) { var oldItem = oldList[oldIndex], newItem = newList[newIndex]; if (identity(oldItem, newItem)) { oldIndex--; newIndex--; continue; } else { return [{ index: newDiffStopIndex, deleteCount: oldIndex - oldDiffStopIndex + 1, insert: slice.call(newList, newDiffStopIndex, newIndex + 1) }]; } } return [{ index: newDiffStopIndex, deleteCount: oldIndex - oldDiffStopIndex + 1, insert: slice.call(newList, newDiffStopIndex, newIndex + 1) }]; } module.exports = exports = function (oldList, newList, identity) { identity = identity || defaultIdentity; var oldIndex = 0, newIndex = 0, oldLength = oldList.length, newLength = newList.length, patches = []; while (oldIndex < oldLength && newIndex < newLength) { var oldItem = oldList[oldIndex], newItem = newList[newIndex]; if (identity(oldItem, newItem)) { oldIndex++; newIndex++; continue; } if (newIndex + 1 < newLength && identity(oldItem, newList[newIndex + 1])) { patches.push({ index: newIndex, deleteCount: 0, insert: [newList[newIndex]] }); oldIndex++; newIndex += 2; continue; } else if (oldIndex + 1 < oldLength && identity(oldList[oldIndex + 1], newItem)) { patches.push({ index: newIndex, deleteCount: 1, insert: [] }); oldIndex += 2; newIndex++; continue; } else { patches.push.apply(patches, reverseDiff(oldIndex, newIndex, oldList, newList, identity)); return patches; } } if (newIndex === newLength && oldIndex === oldLength) { return patches; } patches.push({ index: newIndex, deleteCount: oldLength - oldIndex, insert: slice.call(newList, newIndex) }); return patches; }; }); /*can-util@3.10.18#dom/events/attributes/attributes*/ define('can-util/dom/events/attributes/attributes', [ 'require', 'exports', 'module', 'can-util/dom/events/events', 'can-util/dom/is-of-global-document/is-of-global-document', 'can-util/dom/data/data', 'can-globals/mutation-observer/mutation-observer', 'can-assign', 'can-util/dom/dispatch/dispatch' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var events = require('can-util/dom/events/events'); var isOfGlobalDocument = require('can-util/dom/is-of-global-document/is-of-global-document'); var domData = require('can-util/dom/data/data'); var getMutationObserver = require('can-globals/mutation-observer/mutation-observer'); var assign = require('can-assign'); var domDispatch = require('can-util/dom/dispatch/dispatch'); var originalAdd = events.addEventListener, originalRemove = events.removeEventListener; events.addEventListener = function (eventName) { if (eventName === 'attributes') { var MutationObserver = getMutationObserver(); if (isOfGlobalDocument(this) && MutationObserver) { var existingObserver = domData.get.call(this, 'canAttributesObserver'); if (!existingObserver) { var self = this; var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { var copy = assign({}, mutation); domDispatch.call(self, copy, [], false); }); }); observer.observe(this, { attributes: true, attributeOldValue: true }); domData.set.call(this, 'canAttributesObserver', observer); } } else { domData.set.call(this, 'canHasAttributesBindings', true); } } return originalAdd.apply(this, arguments); }; events.removeEventListener = function (eventName) { if (eventName === 'attributes') { var MutationObserver = getMutationObserver(); var observer; if (isOfGlobalDocument(this) && MutationObserver) { observer = domData.get.call(this, 'canAttributesObserver'); if (observer && observer.disconnect) { observer.disconnect(); domData.clean.call(this, 'canAttributesObserver'); } } else { domData.clean.call(this, 'canHasAttributesBindings'); } } return originalRemove.apply(this, arguments); }; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#dom/events/inserted/inserted*/ define('can-util/dom/events/inserted/inserted', [ 'require', 'exports', 'module', 'can-util/dom/events/make-mutation-event/make-mutation-event' ], function (require, exports, module) { 'use strict'; var makeMutationEvent = require('can-util/dom/events/make-mutation-event/make-mutation-event'); makeMutationEvent('inserted', 'addedNodes'); }); /*can-util@3.10.18#dom/attr/attr*/ define('can-util/dom/attr/attr', [ 'require', 'exports', 'module', 'can-util/js/set-immediate/set-immediate', 'can-globals/document/document', 'can-globals/global/global', 'can-util/dom/is-of-global-document/is-of-global-document', 'can-util/dom/data/data', 'can-util/dom/contains/contains', 'can-util/dom/events/events', 'can-util/dom/dispatch/dispatch', 'can-globals/mutation-observer/mutation-observer', 'can-util/js/each/each', 'can-types', 'can-util/js/diff/diff', 'can-util/dom/events/attributes/attributes', 'can-util/dom/events/inserted/inserted' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var setImmediate = require('can-util/js/set-immediate/set-immediate'); var getDocument = require('can-globals/document/document'); var global = require('can-globals/global/global')(); var isOfGlobalDocument = require('can-util/dom/is-of-global-document/is-of-global-document'); var setData = require('can-util/dom/data/data'); var domContains = require('can-util/dom/contains/contains'); var domEvents = require('can-util/dom/events/events'); var domDispatch = require('can-util/dom/dispatch/dispatch'); var getMutationObserver = require('can-globals/mutation-observer/mutation-observer'); var each = require('can-util/js/each/each'); var types = require('can-types'); var diff = require('can-util/js/diff/diff'); require('can-util/dom/events/attributes/attributes'); require('can-util/dom/events/inserted/inserted'); var namespaces = { 'xlink': 'http://www.w3.org/1999/xlink' }; var formElements = { 'INPUT': true, 'TEXTAREA': true, 'SELECT': true }, toString = function (value) { if (value == null) { return ''; } else { return '' + value; } }, isSVG = function (el) { return el.namespaceURI === 'http://www.w3.org/2000/svg'; }, truthy = function () { return true; }, getSpecialTest = function (special) { return special && special.test || truthy; }, propProp = function (prop, obj) { obj = obj || {}; obj.get = function () { return this[prop]; }; obj.set = function (value) { if (this[prop] !== value) { this[prop] = value; } return value; }; return obj; }, booleanProp = function (prop) { return { isBoolean: true, set: function (value) { if (prop in this) { this[prop] = value !== false; } else { this.setAttribute(prop, ''); } }, remove: function () { this[prop] = false; } }; }, setupMO = function (el, callback) { var attrMO = setData.get.call(el, 'attrMO'); if (!attrMO) { var onMutation = function () { callback.call(el); }; var MO = getMutationObserver(); if (MO) { var observer = new MO(onMutation); observer.observe(el, { childList: true, subtree: true }); setData.set.call(el, 'attrMO', observer); } else { setData.set.call(el, 'attrMO', true); setData.set.call(el, 'canBindingCallback', { onMutation: onMutation }); } } }, _findOptionToSelect = function (parent, value) { var child = parent.firstChild; while (child) { if (child.nodeName === 'OPTION' && value === child.value) { return child; } if (child.nodeName === 'OPTGROUP') { var groupChild = _findOptionToSelect(child, value); if (groupChild) { return groupChild; } } child = child.nextSibling; } }, setChildOptions = function (el, value) { var option; if (value != null) { option = _findOptionToSelect(el, value); } if (option) { option.selected = true; } else { el.selectedIndex = -1; } }, forEachOption = function (parent, fn) { var child = parent.firstChild; while (child) { if (child.nodeName === 'OPTION') { fn(child); } if (child.nodeName === 'OPTGROUP') { forEachOption(child, fn); } child = child.nextSibling; } }, collectSelectedOptions = function (parent) { var selectedValues = []; forEachOption(parent, function (option) { if (option.selected) { selectedValues.push(option.value); } }); return selectedValues; }, markSelectedOptions = function (parent, values) { forEachOption(parent, function (option) { option.selected = values.indexOf(option.value) !== -1; }); }, setChildOptionsOnChange = function (select, aEL) { var handler = setData.get.call(select, 'attrSetChildOptions'); if (handler) { return Function.prototype; } handler = function () { setChildOptions(select, select.value); }; setData.set.call(select, 'attrSetChildOptions', handler); aEL.call(select, 'change', handler); return function (rEL) { setData.clean.call(select, 'attrSetChildOptions'); rEL.call(select, 'change', handler); }; }, attr = { special: { checked: { get: function () { return this.checked; }, set: function (val) { var notFalse = !!val || val === '' || arguments.length === 0; this.checked = notFalse; if (notFalse && this.type === 'radio') { this.defaultChecked = true; } return val; }, remove: function () { this.checked = false; }, test: function () { return this.nodeName === 'INPUT'; } }, 'class': { get: function () { if (isSVG(this)) { return this.getAttribute('class'); } return this.className; }, set: function (val) { val = val || ''; if (isSVG(this)) { this.setAttribute('class', '' + val); } else { this.className = val; } return val; } }, disabled: booleanProp('disabled'), focused: { get: function () { return this === document.activeElement; }, set: function (val) { var cur = attr.get(this, 'focused'); var docEl = this.ownerDocument.documentElement; var element = this; function focusTask() { if (val) { element.focus(); } else { element.blur(); } } if (cur !== val) { if (!domContains.call(docEl, element)) { var initialSetHandler = function () { domEvents.removeEventListener.call(element, 'inserted', initialSetHandler); focusTask(); }; domEvents.addEventListener.call(element, 'inserted', initialSetHandler); } else { types.queueTask([ focusTask, this, [] ]); } } return !!val; }, addEventListener: function (eventName, handler, aEL) { aEL.call(this, 'focus', handler); aEL.call(this, 'blur', handler); return function (rEL) { rEL.call(this, 'focus', handler); rEL.call(this, 'blur', handler); }; }, test: function () { return this.nodeName === 'INPUT'; } }, 'for': propProp('htmlFor'), innertext: propProp('innerText'), innerhtml: propProp('innerHTML'), innerHTML: propProp('innerHTML', { addEventListener: function (eventName, handler, aEL) { var handlers = []; var el = this; each([ 'change', 'blur' ], function (eventName) { var localHandler = function () { handler.apply(this, arguments); }; domEvents.addEventListener.call(el, eventName, localHandler); handlers.push([ eventName, localHandler ]); }); return function (rEL) { each(handlers, function (info) { rEL.call(el, info[0], info[1]); }); }; } }), required: booleanProp('required'), readonly: booleanProp('readOnly'), selected: { get: function () { return this.selected; }, set: function (val) { val = !!val; setData.set.call(this, 'lastSetValue', val); return this.selected = val; }, addEventListener: function (eventName, handler, aEL) { var option = this; var select = this.parentNode; var lastVal = option.selected; var localHandler = function (changeEvent) { var curVal = option.selected; lastVal = setData.get.call(option, 'lastSetValue') || lastVal; if (curVal !== lastVal) { lastVal = curVal; domDispatch.call(option, eventName); } }; var removeChangeHandler = setChildOptionsOnChange(select, aEL); domEvents.addEventListener.call(select, 'change', localHandler); aEL.call(option, eventName, handler); return function (rEL) { removeChangeHandler(rEL); domEvents.removeEventListener.call(select, 'change', localHandler); rEL.call(option, eventName, handler); }; }, test: function () { return this.nodeName === 'OPTION' && this.parentNode && this.parentNode.nodeName === 'SELECT'; } }, src: { set: function (val) { if (val == null || val === '') { this.removeAttribute('src'); return null; } else { this.setAttribute('src', val); return val; } } }, style: { set: function () { var el = global.document && getDocument().createElement('div'); if (el && el.style && 'cssText' in el.style) { return function (val) { return this.style.cssText = val || ''; }; } else { return function (val) { return this.setAttribute('style', val); }; } }() }, textcontent: propProp('textContent'), value: { get: function () { var value = this.value; if (this.nodeName === 'SELECT') { if ('selectedIndex' in this && this.selectedIndex === -1) { value = undefined; } } return value; }, set: function (value) { var nodeName = this.nodeName.toLowerCase(); if (nodeName === 'input') { value = toString(value); } if (this.value !== value || nodeName === 'option') { this.value = value; } if (attr.defaultValue[nodeName]) { this.defaultValue = value; } if (nodeName === 'select') { setData.set.call(this, 'attrValueLastVal', value); setChildOptions(this, value === null ? value : this.value); var docEl = this.ownerDocument.documentElement; if (!domContains.call(docEl, this)) { var select = this; var initialSetHandler = function () { domEvents.removeEventListener.call(select, 'inserted', initialSetHandler); setChildOptions(select, value === null ? value : select.value); }; domEvents.addEventListener.call(this, 'inserted', initialSetHandler); } setupMO(this, function () { var value = setData.get.call(this, 'attrValueLastVal'); attr.set(this, 'value', value); domDispatch.call(this, 'change'); }); } return value; }, test: function () { return formElements[this.nodeName]; } }, values: { get: function () { return collectSelectedOptions(this); }, set: function (values) { values = values || []; markSelectedOptions(this, values); setData.set.call(this, 'stickyValues', attr.get(this, 'values')); setupMO(this, function () { var previousValues = setData.get.call(this, 'stickyValues'); attr.set(this, 'values', previousValues); var currentValues = setData.get.call(this, 'stickyValues'); var changes = diff(previousValues.slice().sort(), currentValues.slice().sort()); if (changes.length) { domDispatch.call(this, 'values'); } }); return values; }, addEventListener: function (eventName, handler, aEL) { var localHandler = function () { domDispatch.call(this, 'values'); }; domEvents.addEventListener.call(this, 'change', localHandler); aEL.call(this, eventName, handler); return function (rEL) { domEvents.removeEventListener.call(this, 'change', localHandler); rEL.call(this, eventName, handler); }; } } }, defaultValue: { input: true, textarea: true }, setAttrOrProp: function (el, attrName, val) { attrName = attrName.toLowerCase(); var special = attr.special[attrName]; if (special && special.isBoolean && !val) { this.remove(el, attrName); } else { this.set(el, attrName, val); } }, set: function (el, attrName, val) { var usingMutationObserver = isOfGlobalDocument(el) && getMutationObserver(); attrName = attrName.toLowerCase(); var oldValue; if (!usingMutationObserver) { oldValue = attr.get(el, attrName); } var newValue; var special = attr.special[attrName]; var setter = special && special.set; var test = getSpecialTest(special); if (typeof setter === 'function' && test.call(el)) { if (arguments.length === 2) { newValue = setter.call(el); } else { newValue = setter.call(el, val); } } else { attr.setAttribute(el, attrName, val); } if (!usingMutationObserver && newValue !== oldValue) { attr.trigger(el, attrName, oldValue); } }, setSelectValue: function (el, value) { attr.set(el, 'value', value); }, setAttribute: function () { var doc = getDocument(); if (doc && document.createAttribute) { try { doc.createAttribute('{}'); } catch (e) { var invalidNodes = {}, attributeDummy = document.createElement('div'); return function (el, attrName, val) { var first = attrName.charAt(0), cachedNode, node, attr; if ((first === '{' || first === '(' || first === '*') && el.setAttributeNode) { cachedNode = invalidNodes[attrName]; if (!cachedNode) { attributeDummy.innerHTML = '<div ' + attrName + '=""></div>'; cachedNode = invalidNodes[attrName] = attributeDummy.childNodes[0].attributes[0]; } node = cachedNode.cloneNode(); node.value = val; el.setAttributeNode(node); } else { attr = attrName.split(':'); if (attr.length !== 1 && namespaces[attr[0]]) { el.setAttributeNS(namespaces[attr[0]], attrName, val); } else { el.setAttribute(attrName, val); } } }; } } return function (el, attrName, val) { el.setAttribute(attrName, val); }; }(), trigger: function (el, attrName, oldValue) { if (setData.get.call(el, 'canHasAttributesBindings')) { attrName = attrName.toLowerCase(); return setImmediate(function () { domDispatch.call(el, { type: 'attributes', attributeName: attrName, target: el, oldValue: oldValue, bubbles: false }, []); }); } }, get: function (el, attrName) { attrName = attrName.toLowerCase(); var special = attr.special[attrName]; var getter = special && special.get; var test = getSpecialTest(special); if (typeof getter === 'function' && test.call(el)) { return getter.call(el); } else { return el.getAttribute(attrName); } }, remove: function (el, attrName) { attrName = attrName.toLowerCase(); var oldValue; if (!getMutationObserver()) { oldValue = attr.get(el, attrName); } var special = attr.special[attrName]; var setter = special && special.set; var remover = special && special.remove; var test = getSpecialTest(special); if (typeof remover === 'function' && test.call(el)) { remover.call(el); } else if (typeof setter === 'function' && test.call(el)) { setter.call(el, undefined); } else { el.removeAttribute(attrName); } if (!getMutationObserver() && oldValue != null) { attr.trigger(el, attrName, oldValue); } }, has: function () { var el = getDocument() && document.createElement('div'); if (el && el.hasAttribute) { return function (el, name) { return el.hasAttribute(name); }; } else { return function (el, name) { return el.getAttribute(name) !== null; }; } }() }; var oldAddEventListener = domEvents.addEventListener; domEvents.addEventListener = function (eventName, handler) { var special = attr.special[eventName]; if (special && special.addEventListener) { var teardown = special.addEventListener.call(this, eventName, handler, oldAddEventListener); var teardowns = setData.get.call(this, 'attrTeardowns'); if (!teardowns) { setData.set.call(this, 'attrTeardowns', teardowns = {}); } if (!teardowns[eventName]) { teardowns[eventName] = []; } teardowns[eventName].push({ teardown: teardown, handler: handler }); return; } return oldAddEventListener.apply(this, arguments); }; var oldRemoveEventListener = domEvents.removeEventListener; domEvents.removeEventListener = function (eventName, handler) { var special = attr.special[eventName]; if (special && special.addEventListener) { var teardowns = setData.get.call(this, 'attrTeardowns'); if (teardowns && teardowns[eventName]) { var eventTeardowns = teardowns[eventName]; for (var i = 0, len = eventTeardowns.length; i < len; i++) { if (eventTeardowns[i].handler === handler) { eventTeardowns[i].teardown.call(this, oldRemoveEventListener); eventTeardowns.splice(i, 1); break; } } if (eventTeardowns.length === 0) { delete teardowns[eventName]; } } return; } return oldRemoveEventListener.apply(this, arguments); }; module.exports = exports = attr; }(function () { return this; }(), require, exports, module)); }); /*can-view-live@4.0.0-pre.17#lib/attr*/ define('can-view-live/lib/attr', [ 'require', 'exports', 'module', 'can-util/dom/attr/attr', 'can-view-live/lib/core', 'can-reflect' ], function (require, exports, module) { var attr = require('can-util/dom/attr/attr'); var live = require('can-view-live/lib/core'); var canReflect = require('can-reflect'); live.attr = function (el, attributeName, compute) { function liveUpdateAttr(newVal) { attr.set(el, attributeName, newVal); } Object.defineProperty(liveUpdateAttr, 'name', { value: 'live.attr update::' + canReflect.getName(compute) }); live.listen(el, compute, liveUpdateAttr); liveUpdateAttr(canReflect.getValue(compute)); }; }); /*can-util@3.10.18#js/global/global*/ define('can-util/js/global/global', [ 'require', 'exports', 'module', 'can-globals/global/global' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; module.exports = require('can-globals/global/global'); }(function () { return this; }(), require, exports, module)); }); /*can-view-callbacks@4.0.0-pre.4#can-view-callbacks*/ define('can-view-callbacks', [ 'require', 'exports', 'module', 'can-observation-recorder', 'can-util/js/dev/dev', 'can-util/js/global/global', 'can-util/dom/mutate/mutate', 'can-namespace' ], function (require, exports, module) { (function (global, require, exports, module) { var ObservationRecorder = require('can-observation-recorder'); var dev = require('can-util/js/dev/dev'); var getGlobal = require('can-util/js/global/global'); var domMutate = require('can-util/dom/mutate/mutate'); var namespace = require('can-namespace'); var requestedAttributes = {}; var attr = function (attributeName, attrHandler) { if (attrHandler) { if (typeof attributeName === 'string') { attributes[attributeName] = attrHandler; if (requestedAttributes[attributeName]) { dev.warn('can-view-callbacks: ' + attributeName + ' custom attribute behavior requested before it was defined. Make sure ' + attributeName + ' is defined before it is needed.'); } } else { regExpAttributes.push({ match: attributeName, handler: attrHandler }); Object.keys(requestedAttributes).forEach(function (requested) { if (attributeName.test(requested)) { dev.warn('can-view-callbacks: ' + requested + ' custom attribute behavior requested before it was defined. Make sure ' + attributeName + ' is defined before it is needed.'); } }); } } else { var cb = attributes[attributeName]; if (!cb) { for (var i = 0, len = regExpAttributes.length; i < len; i++) { var attrMatcher = regExpAttributes[i]; if (attrMatcher.match.test(attributeName)) { return attrMatcher.handler; } } } requestedAttributes[attributeName] = true; return cb; } }; var attributes = {}, regExpAttributes = [], automaticCustomElementCharacters = /[-\:]/; var defaultCallback = function () { }; var tag = function (tagName, tagHandler) { if (tagHandler) { var GLOBAL = getGlobal(); if (typeof tags[tagName.toLowerCase()] !== 'undefined') { dev.warn('Custom tag: ' + tagName.toLowerCase() + ' is already defined'); } if (!automaticCustomElementCharacters.test(tagName) && tagName !== 'content') { dev.warn('Custom tag: ' + tagName.toLowerCase() + ' hyphen missed'); } if (GLOBAL.html5) { GLOBAL.html5.elements += ' ' + tagName; GLOBAL.html5.shivDocument(); } tags[tagName.toLowerCase()] = tagHandler; } else { var cb; if (tagHandler === null) { delete tags[tagName.toLowerCase()]; } else { cb = tags[tagName.toLowerCase()]; } if (!cb && automaticCustomElementCharacters.test(tagName)) { cb = defaultCallback; } return cb; } }; var tags = {}; var callbacks = { _tags: tags, _attributes: attributes, _regExpAttributes: regExpAttributes, defaultCallback: defaultCallback, tag: tag, attr: attr, tagHandler: function (el, tagName, tagData) { var helperTagCallback = tagData.scope.templateContext.tags.get(tagName), tagCallback = helperTagCallback || tags[tagName]; var scope = tagData.scope, res; if (tagCallback) { res = ObservationRecorder.ignore(tagCallback)(el, tagData); } else { res = scope; } if (!tagCallback) { var GLOBAL = getGlobal(); var ceConstructor = GLOBAL.document.createElement(tagName).constructor; if (ceConstructor === GLOBAL.HTMLElement || ceConstructor === GLOBAL.HTMLUnknownElement) { dev.warn('can-view-callbacks: No custom element found for ' + tagName); } } if (res && tagData.subtemplate) { if (scope !== res) { scope = scope.add(res); } var result = tagData.subtemplate(scope, tagData.options); var frag = typeof result === 'string' ? can.view.frag(result) : result; domMutate.appendChild.call(el, frag); } } }; namespace.view = namespace.view || {}; if (namespace.view.callbacks) { throw new Error('You can\'t have two versions of can-view-callbacks, check your dependencies'); } else { module.exports = namespace.view.callbacks = callbacks; } }(function () { return this; }(), require, exports, module)); }); /*can-view-live@4.0.0-pre.17#lib/attrs*/ define('can-view-live/lib/attrs', [ 'require', 'exports', 'module', 'can-view-live/lib/core', 'can-view-callbacks', 'can-util/dom/attr/attr', 'can-util/dom/events/events', 'can-reflect', 'can-reflect-dependencies' ], function (require, exports, module) { var live = require('can-view-live/lib/core'); var viewCallbacks = require('can-view-callbacks'); var attr = require('can-util/dom/attr/attr'); var domEvents = require('can-util/dom/events/events'); var canReflect = require('can-reflect'); var canReflectDeps = require('can-reflect-dependencies'); live.attrs = function (el, compute, scope, options) { if (!canReflect.isObservableLike(compute)) { var attrs = live.getAttributeParts(compute); for (var name in attrs) { attr.set(el, name, attrs[name]); } return; } var oldAttrs = {}; function liveAttrsUpdate(newVal) { var newAttrs = live.getAttributeParts(newVal), name; for (name in newAttrs) { var newValue = newAttrs[name], oldValue = oldAttrs[name]; if (newValue !== oldValue) { attr.set(el, name, newValue); var callback = viewCallbacks.attr(name); if (callback) { callback(el, { attributeName: name, scope: scope, options: options }); } } delete oldAttrs[name]; } for (name in oldAttrs) { attr.remove(el, name); } oldAttrs = newAttrs; } Object.defineProperty(liveAttrsUpdate, 'name', { value: 'live.attrs update::' + canReflect.getName(compute) }); canReflectDeps.addMutatedBy(el, compute); canReflect.onValue(compute, liveAttrsUpdate); var teardownHandler = function () { canReflect.offValue(compute, liveAttrsUpdate); domEvents.removeEventListener.call(el, 'removed', teardownHandler); canReflectDeps.deleteMutatedBy(el, compute); }; domEvents.addEventListener.call(el, 'removed', teardownHandler); liveAttrsUpdate(canReflect.getValue(compute)); }; }); /*can-view-live@4.0.0-pre.17#lib/html*/ define('can-view-live/lib/html', [ 'require', 'exports', 'module', 'can-view-live/lib/core', 'can-view-nodelist', 'can-util/dom/frag/frag', 'can-util/js/make-array/make-array', 'can-util/dom/child-nodes/child-nodes', 'can-reflect' ], function (require, exports, module) { var live = require('can-view-live/lib/core'); var nodeLists = require('can-view-nodelist'); var makeFrag = require('can-util/dom/frag/frag'); var makeArray = require('can-util/js/make-array/make-array'); var childNodes = require('can-util/dom/child-nodes/child-nodes'); var canReflect = require('can-reflect'); live.html = function (el, compute, parentNode, nodeList) { var data, makeAndPut, nodes; parentNode = live.getParentNode(el, parentNode); function liveHTMLUpdateHTML(newVal) { var attached = nodeLists.first(nodes).parentNode; if (attached) { makeAndPut(newVal); } var pn = nodeLists.first(nodes).parentNode; data.teardownCheck(pn); } Object.defineProperty(liveHTMLUpdateHTML, 'name', { value: 'live.html update::' + canReflect.getName(compute) }); data = live.listen(parentNode, compute, liveHTMLUpdateHTML); nodes = nodeList || [el]; makeAndPut = function (val) { var isFunction = typeof val === 'function', frag = makeFrag(isFunction ? '' : val), oldNodes = makeArray(nodes); live.addTextNodeIfNoChildren(frag); oldNodes = nodeLists.update(nodes, childNodes(frag)); if (isFunction) { val(frag.firstChild); } nodeLists.replace(oldNodes, frag); }; data.nodeList = nodes; if (!nodeList) { nodeLists.register(nodes, data.teardownCheck); } else { nodeList.unregistered = data.teardownCheck; } makeAndPut(canReflect.getValue(compute)); }; }); /*can-view-live@4.0.0-pre.17#lib/set-observable*/ define('can-view-live/lib/set-observable', [ 'require', 'exports', 'module', 'can-simple-observable', 'can-reflect' ], function (require, exports, module) { var SimpleObservable = require('can-simple-observable'); var canReflect = require('can-reflect'); function SetObservable(initialValue, setter) { this.setter = setter; SimpleObservable.call(this, initialValue); } SetObservable.prototype = Object.create(SimpleObservable.prototype); SetObservable.prototype.constructor = SetObservable; SetObservable.prototype.set = function (newVal) { this.setter(newVal); }; canReflect.assignSymbols(SetObservable.prototype, { 'can.setValue': SetObservable.prototype.set }); module.exports = SetObservable; }); /*can-view-live@4.0.0-pre.17#lib/patcher*/ define('can-view-live/lib/patcher', [ 'require', 'exports', 'module', 'can-reflect', 'can-key-tree', 'can-symbol', 'can-util/js/diff/diff', 'can-queues', 'can-symbol' ], function (require, exports, module) { var canReflect = require('can-reflect'); var KeyTree = require('can-key-tree'); var canSymbol = require('can-symbol'); var diff = require('can-util/js/diff/diff'); var queues = require('can-queues'); var canSymbol = require('can-symbol'); var onValueSymbol = canSymbol.for('can.onValue'), offValueSymbol = canSymbol.for('can.offValue'); var onPatchesSymbol = canSymbol.for('can.onPatches'); var offPatchesSymbol = canSymbol.for('can.offPatches'); var Patcher = function (observableOrList, priority) { this.handlers = new KeyTree([ Object, Array ], { onFirst: this.setup.bind(this), onEmpty: this.teardown.bind(this) }); this.observableOrList = observableOrList; this.isObservableValue = canReflect.isValueLike(this.observableOrList) || canReflect.isObservableLike(this.observableOrList); if (this.isObservableValue) { this.priority = canReflect.getPriority(observableOrList); } else { this.priority = priority || 0; } this.onList = this.onList.bind(this); this.onPatchesNotify = this.onPatchesNotify.bind(this); this.onPatchesDerive = this.onPatchesDerive.bind(this); this.patches = []; Object.defineProperty(this.onList, 'name', { value: 'live.list new list::' + canReflect.getName(observableOrList) }); Object.defineProperty(this.onPatchesNotify, 'name', { value: 'live.list notify::' + canReflect.getName(observableOrList) }); Object.defineProperty(this.onPatchesDerive, 'name', { value: 'live.list derive::' + canReflect.getName(observableOrList) }); }; Patcher.prototype = { constructor: Patcher, setup: function () { if (this.observableOrList[onValueSymbol]) { canReflect.onValue(this.observableOrList, this.onList, 'notify'); this.setupList(canReflect.getValue(this.observableOrList)); } else { this.setupList(this.observableOrList || []); } }, teardown: function () { if (this.observableOrList[offValueSymbol]) { canReflect.offValue(this.observableOrList, this.onList, 'notify'); } }, setupList: function (list) { this.currentList = list; if (list[onPatchesSymbol]) { list[onPatchesSymbol](this.onPatchesNotify, 'notify'); } }, onList: function onList(newList) { var current = this.currentList || []; newList = newList || []; if (current[offPatchesSymbol]) { current[offPatchesSymbol](this.onPatchesNotify, 'notify'); } var patches = diff(current, newList); this.currentList = newList; this.onPatchesNotify(patches); if (newList[onPatchesSymbol]) { newList[onPatchesSymbol](this.onPatchesNotify, 'notify'); } }, onPatchesNotify: function onPatchesNotify(patches) { this.patches.push.apply(this.patches, patches); queues.deriveQueue.enqueue(this.onPatchesDerive, this, [], { priority: this.priority }); }, onPatchesDerive: function onPatchesDerive() { var patches = this.patches; this.patches = []; queues.enqueueByQueue(this.handlers.getNode([]), this.currentList, [ patches, this.currentList ], null, [ 'Apply patches', patches ]); } }; canReflect.assignSymbols(Patcher.prototype, { 'can.onPatches': function (handler, queue) { this.handlers.add([ queue || 'mutate', handler ]); }, 'can.offPatches': function (handler, queue) { this.handlers.delete([ queue || 'mutate', handler ]); } }); module.exports = Patcher; }); /*can-view-live@4.0.0-pre.17#lib/list*/ define('can-view-live/lib/list', [ 'require', 'exports', 'module', 'can-view-live/lib/core', 'can-view-nodelist', 'can-util/dom/frag/frag', 'can-util/dom/mutate/mutate', 'can-util/dom/child-nodes/child-nodes', 'can-util/js/make-array/make-array', 'can-util/js/each/each', 'can-symbol', 'can-reflect', 'can-reflect-dependencies', 'can-simple-observable', 'can-view-live/lib/set-observable', 'can-view-live/lib/patcher' ], function (require, exports, module) { var live = require('can-view-live/lib/core'); var nodeLists = require('can-view-nodelist'); var frag = require('can-util/dom/frag/frag'); var domMutate = require('can-util/dom/mutate/mutate'); var childNodes = require('can-util/dom/child-nodes/child-nodes'); var makeArray = require('can-util/js/make-array/make-array'); var each = require('can-util/js/each/each'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var canReflectDeps = require('can-reflect-dependencies'); var SimpleObservable = require('can-simple-observable'); var SetObservable = require('can-view-live/lib/set-observable'); var Patcher = require('can-view-live/lib/patcher'); var splice = [].splice; var renderAndAddToNodeLists = function (newNodeLists, parentNodeList, render, context, args) { var itemNodeList = []; if (parentNodeList) { nodeLists.register(itemNodeList, null, parentNodeList, true); itemNodeList.parentList = parentNodeList; itemNodeList.expression = '#each SUBEXPRESSION'; } var itemHTML = render.apply(context, args.concat([itemNodeList])), itemFrag = frag(itemHTML); var children = makeArray(childNodes(itemFrag)); if (parentNodeList) { nodeLists.update(itemNodeList, children); newNodeLists.push(itemNodeList); } else { newNodeLists.push(nodeLists.register(children)); } return itemFrag; }, removeFromNodeList = function (masterNodeList, index, length) { var removedMappings = masterNodeList.splice(index + 1, length), itemsToRemove = []; each(removedMappings, function (nodeList) { var nodesToRemove = nodeLists.unregister(nodeList); [].push.apply(itemsToRemove, nodesToRemove); }); return itemsToRemove; }; var onPatchesSymbol = canSymbol.for('can.onPatches'); var offPatchesSymbol = canSymbol.for('can.offPatches'); function ListDOMPatcher(el, compute, render, context, parentNode, nodeList, falseyRender) { this.patcher = new Patcher(compute); parentNode = live.getParentNode(el, parentNode); this.value = compute; this.render = render; this.context = context; this.parentNode = parentNode; this.falseyRender = falseyRender; this.masterNodeList = nodeList || nodeLists.register([el], null, true); this.placeholder = el; this.indexMap = []; this.isValueLike = canReflect.isValueLike(this.value); this.isObservableLike = canReflect.isObservableLike(this.value); this.onPatches = this.onPatches.bind(this); var data = this.data = live.setup(parentNode, this.setupValueBinding.bind(this), this.teardownValueBinding.bind(this)); this.masterNodeList.unregistered = function () { data.teardownCheck(); }; Object.defineProperty(this.onPatches, 'name', { value: 'live.list update::' + canReflect.getName(compute) }); } var onPatchesSymbol = canSymbol.for('can.onPatches'); var offPatchesSymbol = canSymbol.for('can.offPatches'); ListDOMPatcher.prototype = { setupValueBinding: function () { this.patcher[onPatchesSymbol](this.onPatches, 'domUI'); if (this.patcher.currentList && this.patcher.currentList.length) { this.onPatches([{ insert: this.patcher.currentList, index: 0, deleteCount: 0 }]); } else { this.addFalseyIfEmpty(); } canReflectDeps.addMutatedBy(this.parentNode, this.patcher.observableOrList); }, teardownValueBinding: function () { this.patcher[offPatchesSymbol](this.onPatches, 'domUI'); this.exit = true; this.remove({ length: this.patcher.currentList.length }, 0, true); canReflectDeps.deleteMutatedBy(this.parentNode, this.patcher.observableOrList); }, onPatches: function ListDOMPatcher_onPatches(patches) { if (this.exit) { return; } for (var i = 0, patchLen = patches.length; i < patchLen; i++) { var patch = patches[i]; if (patch.type === 'move') { this.move(patch.toIndex, patch.fromIndex); } else { if (patch.deleteCount) { this.remove({ length: patch.deleteCount }, patch.index, true); } if (patch.insert && patch.insert.length) { this.add(patch.insert, patch.index); } } } }, add: function (items, index) { var frag = this.placeholder.ownerDocument.createDocumentFragment(), newNodeLists = [], newIndicies = [], masterNodeList = this.masterNodeList, render = this.render, context = this.context; each(items, function (item, key) { var itemIndex = new SimpleObservable(key + index), itemCompute = new SetObservable(item, function (newVal) { canReflect.setKeyValue(this.patcher.currentList, itemIndex.get(), newVal); }.bind(this)), itemFrag = renderAndAddToNodeLists(newNodeLists, masterNodeList, render, context, [ itemCompute, itemIndex ]); frag.appendChild(itemFrag); newIndicies.push(itemIndex); }, this); var masterListIndex = index + 1; if (!this.indexMap.length) { var falseyItemsToRemove = removeFromNodeList(masterNodeList, 0, masterNodeList.length - 1); nodeLists.remove(falseyItemsToRemove); } if (!masterNodeList[masterListIndex]) { nodeLists.after(masterListIndex === 1 ? [this.placeholder] : [nodeLists.last(this.masterNodeList[masterListIndex - 1])], frag); } else { var el = nodeLists.first(masterNodeList[masterListIndex]); domMutate.insertBefore.call(el.parentNode, frag, el); } splice.apply(this.masterNodeList, [ masterListIndex, 0 ].concat(newNodeLists)); splice.apply(this.indexMap, [ index, 0 ].concat(newIndicies)); for (var i = index + newIndicies.length, len = this.indexMap.length; i < len; i++) { this.indexMap[i].set(i); } }, remove: function (items, index) { if (index < 0) { index = this.indexMap.length + index; } var itemsToRemove = removeFromNodeList(this.masterNodeList, index, items.length); var indexMap = this.indexMap; indexMap.splice(index, items.length); for (var i = index, len = indexMap.length; i < len; i++) { indexMap[i].set(i); } if (!this.exit) { this.addFalseyIfEmpty(); nodeLists.remove(itemsToRemove); } else { nodeLists.unregister(this.masterNodeList); } }, addFalseyIfEmpty: function () { if (this.falseyRender && this.indexMap.length === 0) { var falseyNodeLists = []; var falseyFrag = renderAndAddToNodeLists(falseyNodeLists, this.masterNodeList, this.falseyRender, this.currentList, [this.currentList]); nodeLists.after([this.masterNodeList[0]], falseyFrag); this.masterNodeList.push(falseyNodeLists[0]); } }, move: function move(newIndex, currentIndex) { newIndex = newIndex + 1; currentIndex = currentIndex + 1; var masterNodeList = this.masterNodeList, indexMap = this.indexMap; var referenceNodeList = masterNodeList[newIndex]; var movedElements = frag(nodeLists.flatten(masterNodeList[currentIndex])); var referenceElement; if (currentIndex < newIndex) { referenceElement = nodeLists.last(referenceNodeList).nextSibling; } else { referenceElement = nodeLists.first(referenceNodeList); } var parentNode = masterNodeList[0].parentNode; parentNode.insertBefore(movedElements, referenceElement); var temp = masterNodeList[currentIndex]; [].splice.apply(masterNodeList, [ currentIndex, 1 ]); [].splice.apply(masterNodeList, [ newIndex, 0, temp ]); newIndex = newIndex - 1; currentIndex = currentIndex - 1; var indexCompute = indexMap[currentIndex]; [].splice.apply(indexMap, [ currentIndex, 1 ]); [].splice.apply(indexMap, [ newIndex, 0, indexCompute ]); var i = Math.min(currentIndex, newIndex); var len = indexMap.length; for (i, len; i < len; i++) { indexMap[i].set(i); } }, set: function (newVal, index) { this.remove({ length: 1 }, index, true); this.add([newVal], index); } }; live.list = function (el, list, render, context, parentNode, nodeList, falseyRender) { if (el.nodeType !== Node.TEXT_NODE) { var textNode; if (!nodeList) { textNode = document.createTextNode(''); el.parentNode.replaceChild(textNode, el); el = textNode; } else { textNode = document.createTextNode(''); nodeLists.replace(nodeList, textNode); nodeLists.update(nodeList, [textNode]); el = textNode; } } new ListDOMPatcher(el, list, render, context, parentNode, nodeList, falseyRender); }; }); /*can-view-live@4.0.0-pre.17#lib/text*/ define('can-view-live/lib/text', [ 'require', 'exports', 'module', 'can-view-live/lib/core', 'can-view-nodelist', 'can-reflect' ], function (require, exports, module) { var live = require('can-view-live/lib/core'); var nodeLists = require('can-view-nodelist'); var canReflect = require('can-reflect'); live.text = function (el, compute, parentNode, nodeList) { if (el.nodeType !== Node.TEXT_NODE) { var textNode; if (!nodeList) { textNode = document.createTextNode(''); el.parentNode.replaceChild(textNode, el); el = textNode; } else { textNode = document.createTextNode(''); nodeLists.replace(nodeList, textNode); nodeLists.update(nodeList, [textNode]); el = textNode; } } var parent = live.getParentNode(el, parentNode); el.nodeValue = live.makeString(canReflect.getValue(compute)); function liveTextUpdateTextNode(newVal) { el.nodeValue = live.makeString(newVal); } Object.defineProperty(liveTextUpdateTextNode, 'name', { value: 'live.text update::' + canReflect.getName(compute) }); var data = live.listen(parent, compute, liveTextUpdateTextNode); if (!nodeList) { nodeList = nodeLists.register([el], null, true); } nodeList.unregistered = data.teardownCheck; data.nodeList = nodeList; }; }); /*can-view-live@4.0.0-pre.17#can-view-live*/ define('can-view-live', [ 'require', 'exports', 'module', 'can-view-live/lib/core', 'can-view-live/lib/attr', 'can-view-live/lib/attrs', 'can-view-live/lib/html', 'can-view-live/lib/list', 'can-view-live/lib/text' ], function (require, exports, module) { var live = require('can-view-live/lib/core'); require('can-view-live/lib/attr'); require('can-view-live/lib/attrs'); require('can-view-live/lib/html'); require('can-view-live/lib/list'); require('can-view-live/lib/text'); module.exports = live; }); /*can-stache@4.0.0-pre.26#src/key-observable*/ define('can-stache/src/key-observable', [ 'require', 'exports', 'module', 'can-simple-observable/settable/settable', 'can-stache-key' ], function (require, exports, module) { var SettableObservable = require('can-simple-observable/settable/settable'); var stacheKey = require('can-stache-key'); function KeyObservable(root, key) { key = '' + key; this.key = key; this.root = root; SettableObservable.call(this, function () { return stacheKey.get(this, key); }, root); } KeyObservable.prototype = Object.create(SettableObservable.prototype); KeyObservable.prototype.set = function (newVal) { stacheKey.set(this.root, this.key, newVal); }; module.exports = KeyObservable; }); /*can-stache@4.0.0-pre.26#src/utils*/ define('can-stache/src/utils', [ 'require', 'exports', 'module', 'can-view-scope', 'can-observation', 'can-observation-recorder', 'can-stache-key', 'can-reflect', 'can-stache/src/key-observable', 'can-log/dev/dev', 'can-util/js/is-empty-object/is-empty-object', 'can-util/js/is-array-like/is-array-like' ], function (require, exports, module) { var Scope = require('can-view-scope'); var Observation = require('can-observation'); var ObservationRecorder = require('can-observation-recorder'); var observationReader = require('can-stache-key'); var canReflect = require('can-reflect'); var KeyObservable = require('can-stache/src/key-observable'); var dev = require('can-log/dev/dev'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var isArrayLike = require('can-util/js/is-array-like/is-array-like'); var Options = Scope.Options; var noop = function () { }; module.exports = { isArrayLike: isArrayLike, emptyHandler: function () { }, jsonParse: function (str) { if (str[0] === '\'') { return str.substr(1, str.length - 2); } else if (str === 'undefined') { return undefined; } else { return JSON.parse(str); } }, mixins: { last: function () { return this.stack[this.stack.length - 1]; }, add: function (chars) { this.last().add(chars); }, subSectionDepth: function () { return this.stack.length - 1; } }, convertToScopes: function (helperOptions, scope, nodeList, truthyRenderer, falseyRenderer, isStringOnly) { helperOptions.fn = truthyRenderer ? this.makeRendererConvertScopes(truthyRenderer, scope, nodeList, isStringOnly) : noop; helperOptions.inverse = falseyRenderer ? this.makeRendererConvertScopes(falseyRenderer, scope, nodeList, isStringOnly) : noop; helperOptions.isSection = !!(truthyRenderer || falseyRenderer); }, makeRendererConvertScopes: function (renderer, parentScope, nodeList, observeObservables) { var rendererWithScope = function (ctx, parentNodeList) { return renderer(ctx || parentScope, parentNodeList); }; var convertedRenderer = function (newScope, newOptions, parentNodeList) { if (newScope !== undefined && !(newScope instanceof Scope)) { if (parentScope) { newScope = parentScope.add(newScope); } else { newScope = new Scope(newScope || {}); } } var result = rendererWithScope(newScope, parentNodeList || nodeList); return result; }; return observeObservables ? convertedRenderer : ObservationRecorder.ignore(convertedRenderer); }, getItemsStringContent: function (items, isObserveList, helperOptions) { var txt = '', len = observationReader.get(items, 'length'), isObservable = canReflect.isObservableLike(items); for (var i = 0; i < len; i++) { var item = isObservable ? new KeyObservable(items, i) : items[i]; txt += helperOptions.fn(item); } return txt; }, getItemsFragContent: function (items, helperOptions, scope) { var result = [], len = observationReader.get(items, 'length'), isObservable = canReflect.isObservableLike(items), hashExprs = helperOptions.exprData && helperOptions.exprData.hashExprs, hashOptions; if (!isEmptyObject(hashExprs)) { hashOptions = {}; canReflect.eachKey(hashExprs, function (exprs, key) { hashOptions[exprs.key] = key; }); } for (var i = 0; i < len; i++) { var aliases = {}; var item = isObservable ? new KeyObservable(items, i) : items[i]; if (!isEmptyObject(hashOptions)) { if (hashOptions.value) { aliases[hashOptions.value] = item; } if (hashOptions.index) { aliases[hashOptions.index] = i; } } result.push(helperOptions.fn(scope.add(aliases, { notContext: true }).add({ index: i }, { special: true }).add(item))); } return result; }, Options: Options }; }); /*can-util@3.10.18#js/base-url/base-url*/ define('can-util/js/base-url/base-url', [ 'require', 'exports', 'module', 'can-globals/global/global', 'can-globals/document/document' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getGlobal = require('can-globals/global/global'); var getDomDocument = require('can-globals/document/document'); var setBaseUrl; module.exports = function (setUrl) { if (setUrl !== undefined) { setBaseUrl = setUrl; } if (setBaseUrl !== undefined) { return setBaseUrl; } var global = getGlobal(); var domDocument = getDomDocument(); if (domDocument && 'baseURI' in domDocument) { return domDocument.baseURI; } else if (global.location) { var href = global.location.href; var lastSlash = href.lastIndexOf('/'); return lastSlash !== -1 ? href.substr(0, lastSlash) : href; } else if (typeof process !== 'undefined') { return process.cwd(); } }; }(function () { return this; }(), require, exports, module)); }); /*can-parse-uri@1.0.1#can-parse-uri*/ define('can-parse-uri', function (require, exports, module) { module.exports = function (url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); return m ? { href: m[0] || '', protocol: m[1] || '', authority: m[2] || '', host: m[3] || '', hostname: m[4] || '', port: m[5] || '', pathname: m[6] || '', search: m[7] || '', hash: m[8] || '' } : null; }; }); /*can-util@3.10.18#js/join-uris/join-uris*/ define('can-util/js/join-uris/join-uris', [ 'require', 'exports', 'module', 'can-parse-uri' ], function (require, exports, module) { 'use strict'; var parseURI = require('can-parse-uri'); module.exports = function (base, href) { function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '').replace(/\/(\.(\/|$))+/g, '/').replace(/\/\.\.$/, '/../').replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = parseURI(href || ''); base = parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : href.pathname ? (base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname : base.pathname) + (href.protocol || href.authority || href.pathname ? href.search : href.search || base.search) + href.hash; }; }); /*can-stache@4.0.0-pre.26#helpers/-debugger*/ define('can-stache/helpers/-debugger', [ 'require', 'exports', 'module', 'can-log', 'can-reflect', 'can-symbol' ], function (require, exports, module) { var canLog = require('can-log'); function noop() { } ; var resolveValue = noop; var evaluateArgs = noop; var __testing = {}; var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); __testing = { allowDebugger: true }; resolveValue = function (value) { if (value && value[canSymbol.for('can.getValue')]) { return canReflect.getValue(value); } return value; }; evaluateArgs = function (left, right) { switch (arguments.length) { case 0: return true; case 1: return !!resolveValue(left); case 2: return resolveValue(left) === resolveValue(right); default: canLog.log([ 'Usage:', ' {{debugger}}: break any time this helper is evaluated', ' {{debugger condition}}: break when `condition` is truthy', ' {{debugger left right}}: break when `left` === `right`' ].join('\n')); throw new Error('{{debugger}} must have less than three arguments'); } }; function debuggerHelper(left, right) { var shouldBreak = evaluateArgs.apply(null, Array.prototype.slice.call(arguments, 0, -1)); if (!shouldBreak) { return; } var options = arguments[arguments.length - 1]; var get = function (path) { return options.scope.get(path); }; canLog.log('Use `get(<path>)` to debug this template'); var allowDebugger = __testing.allowDebugger; if (allowDebugger) { debugger; return; } canLog.warn('Forgotten {{debugger}} helper'); } module.exports = { helper: debuggerHelper, evaluateArgs: evaluateArgs, resolveValue: resolveValue, __testing: __testing }; }); /*can-stache@4.0.0-pre.26#src/truthy-observable*/ define('can-stache/src/truthy-observable', [ 'require', 'exports', 'module', 'can-observation', 'can-reflect' ], function (require, exports, module) { var Observation = require('can-observation'); var canReflect = require('can-reflect'); module.exports = function (observable) { return new Observation(function truthyObservation() { var val = canReflect.getValue(observable); return !!val; }); }; }); /*can-stache@4.0.0-pre.26#src/lookup-priorities*/ define('can-stache/src/lookup-priorities', function (require, exports, module) { var priorities = [ 'LOCAL_HELPER', 'BUILT_IN_HELPER', 'SCOPE_FUNCTION', 'SCOPE_PROPERTY', 'GLOBAL_HELPER', 'MAX' ].reduce(function (priorities, key, index) { priorities[key] = index + 1; return priorities; }, {}); module.exports = priorities; }); /*can-stache@4.0.0-pre.26#helpers/core*/ define('can-stache/helpers/core', [ 'require', 'exports', 'module', 'can-view-live', 'can-view-nodelist', 'can-stache/src/utils', 'can-util/js/base-url/base-url', 'can-util/js/join-uris/join-uris', 'can-assign', 'can-util/js/is-iterable/is-iterable', 'can-log/dev/dev', 'can-symbol', 'can-reflect', 'can-util/js/is-empty-object/is-empty-object', 'can-stache/expressions/hashes', 'can-stache/helpers/-debugger', 'can-stache/src/key-observable', 'can-observation', 'can-stache/src/truthy-observable', 'can-observation-recorder', 'can-stache/src/lookup-priorities', 'can-util/dom/data/data' ], function (require, exports, module) { var live = require('can-view-live'); var nodeLists = require('can-view-nodelist'); var utils = require('can-stache/src/utils'); var getBaseURL = require('can-util/js/base-url/base-url'); var joinURIs = require('can-util/js/join-uris/join-uris'); var assign = require('can-assign'); var isIterable = require('can-util/js/is-iterable/is-iterable'); var dev = require('can-log/dev/dev'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var Hashes = require('can-stache/expressions/hashes'); var debuggerHelper = require('can-stache/helpers/-debugger').helper; var KeyObservable = require('can-stache/src/key-observable'); var Observation = require('can-observation'); var TruthyObservable = require('can-stache/src/truthy-observable'); var observationRecorder = require('can-observation-recorder'); var lookupPriorities = require('can-stache/src/lookup-priorities'); var domData = require('can-util/dom/data/data'); var looksLikeOptions = function (options) { return options && typeof options.fn === 'function' && typeof options.inverse === 'function'; }; var getValueSymbol = canSymbol.for('can.getValue'), isValueLikeSymbol = canSymbol.for('can.isValueLike'); var resolve = function (value) { if (value && canReflect.isValueLike(value)) { return canReflect.getValue(value); } else { return value; } }; var resolveHash = function (hash) { var params = {}; for (var prop in hash) { params[prop] = resolve(hash[prop]); } return params; }; var peek = observationRecorder.ignore(resolve); var helpers = { 'each': { metadata: { isLiveBound: true }, fn: function (items) { var args = [].slice.call(arguments), options = args.pop(), argsLen = args.length, argExprs = options.exprData.argExprs, hashExprs = options.exprData.hashExprs, resolved = peek(items), hashOptions, aliases, key; if (!isEmptyObject(hashExprs)) { hashOptions = {}; canReflect.eachKey(hashExprs, function (exprs, key) { hashOptions[exprs.key] = key; }); } if ((canReflect.isObservableLike(resolved) && canReflect.isListLike(resolved) || utils.isArrayLike(resolved) && canReflect.isValueLike(items)) && !options.stringOnly) { return function (el) { var nodeList = [el]; nodeList.expression = 'live.list'; nodeLists.register(nodeList, null, options.nodeList, true); nodeLists.update(options.nodeList, [el]); var cb = function (item, index, parentNodeList) { var aliases = {}; if (!isEmptyObject(hashOptions)) { if (hashOptions.value) { aliases[hashOptions.value] = item; } if (hashOptions.index) { aliases[hashOptions.index] = index; } } return options.fn(options.scope.add(aliases, { notContext: true }).add({ index: index }, { special: true }).add(item), options.options, parentNodeList); }; live.list(el, items, cb, options.context, el.parentNode, nodeList, function (list, parentNodeList) { return options.inverse(options.scope.add(list), options.options, parentNodeList); }); }; } var expr = resolve(items), result; if (!!expr && utils.isArrayLike(expr)) { result = utils.getItemsFragContent(expr, options, options.scope); return options.stringOnly ? result.join('') : result; } else if (canReflect.isObservableLike(expr) && canReflect.isMapLike(expr) || expr instanceof Object) { result = []; canReflect.each(expr, function (val, key) { var value = new KeyObservable(expr, key); aliases = {}; if (!isEmptyObject(hashOptions)) { if (hashOptions.value) { aliases[hashOptions.value] = value; } if (hashOptions.key) { aliases[hashOptions.key] = key; } } result.push(options.fn(options.scope.add(aliases, { notContext: true }).add({ key: key }, { special: true }).add(value))); }); return options.stringOnly ? result.join('') : result; } } }, 'index': { fn: function (offset, options) { if (!options) { options = offset; offset = 0; } var index = options.scope.peek('scope.index'); return '' + ((typeof index === 'function' ? index() : index) + offset); } }, 'if': { fn: function (expr, options) { var value; if (expr && canReflect.isValueLike(expr)) { value = canReflect.getValue(new TruthyObservable(expr)); } else { value = !!resolve(expr); } if (value) { return options.fn(options.scope || this); } else { return options.inverse(options.scope || this); } } }, 'is': { fn: function () { var lastValue, curValue, options = arguments[arguments.length - 1]; if (arguments.length - 2 <= 0) { return options.inverse(); } var args = arguments; var callFn = new Observation(function () { for (var i = 0; i < args.length - 1; i++) { curValue = resolve(args[i]); curValue = typeof curValue === 'function' ? curValue() : curValue; if (i > 0) { if (curValue !== lastValue) { return false; } } lastValue = curValue; } return true; }); return callFn.get() ? options.fn() : options.inverse(); } }, 'eq': { fn: function () { return helpers.is.fn.apply(this, arguments); } }, 'unless': { fn: function (expr, options) { return helpers['if'].fn.apply(this, [ expr, assign(assign({}, options), { fn: options.inverse, inverse: options.fn }) ]); } }, 'with': { fn: function (expr, options) { var ctx = expr; if (!options) { options = expr; expr = true; ctx = options.hash; } else { expr = resolve(expr); if (options.hash && !isEmptyObject(options.hash)) { ctx = options.scope.add(options.hash, { notContext: true }).add(ctx); } } return options.fn(ctx || {}); } }, 'log': { fn: function (options) { var logs = []; canReflect.eachIndex(arguments, function (val) { if (!looksLikeOptions(val)) { logs.push(val); } }); if (typeof console !== 'undefined' && console.log) { if (!logs.length) { console.log(options.context); } else { console.log.apply(console, logs); } } } }, 'data': { fn: function (attr) { var data = arguments.length === 2 ? this : arguments[1]; return function (el) { domData.set.call(el, attr, data || this.context); }; } }, 'switch': { fn: function (expression, options) { resolve(expression); var found = false; var localHelpers = options.scope.templateContext.helpers; var caseHelper = function (value, options) { if (!found && resolve(expression) === resolve(value)) { found = true; return options.fn(options.scope || this); } }; var defaultHelper = function (options) { if (!found) { return options.fn(options.scope || this); } }; canReflect.setKeyValue(localHelpers, 'case', caseHelper); canReflect.setKeyValue(localHelpers, 'default', defaultHelper); return options.fn(options.scope, options); } }, 'joinBase': { fn: function (firstExpr) { var args = [].slice.call(arguments); var options = args.pop(); var moduleReference = args.map(function (expr) { var value = resolve(expr); return typeof value === 'function' ? value() : value; }).join(''); var templateModule = canReflect.getKeyValue(options.scope.templateContext.helpers, 'module'); var parentAddress = templateModule ? templateModule.uri : undefined; var isRelative = moduleReference[0] === '.'; if (isRelative && parentAddress) { return joinURIs(parentAddress, moduleReference); } else { var baseURL = typeof System !== 'undefined' && (System.renderingBaseURL || System.baseURL) || getBaseURL(); if (moduleReference[0] !== '/' && baseURL[baseURL.length - 1] !== '/') { baseURL += '/'; } return joinURIs(baseURL, moduleReference); } } } }; helpers.eachOf = helpers.each; helpers.debugger = { fn: debuggerHelper }; var registerHelper = function (name, callback, metadata) { if (helpers[name]) { dev.warn('The helper ' + name + ' has already been registered.'); } helpers[name] = { metadata: assign({ isHelper: true, priority: lookupPriorities.GLOBAL_HELPER }, metadata), fn: callback }; }; var makeSimpleHelper = function (fn) { return function () { var realArgs = []; canReflect.eachIndex(arguments, function (val) { while (val && val.isComputed) { val = val(); } realArgs.push(val); }); return fn.apply(this, realArgs); }; }; module.exports = { registerHelper: registerHelper, addHelper: function (name, callback) { return registerHelper(name, makeSimpleHelper(callback)); }, addLiveHelper: function (name, callback) { return registerHelper(name, callback, { isLiveBound: true }); }, getHelper: function (name, scope) { var helper = scope && canReflect.getKeyValue(scope.templateContext.helpers, name); if (helper) { helper = { fn: helper, metadata: { priority: lookupPriorities.LOCAL_HELPER } }; } else { helper = assign({}, helpers[name]); if (!isEmptyObject(helper)) { helper.metadata = assign({ priority: lookupPriorities.BUILT_IN_HELPER }, helper.metadata); } } if (!isEmptyObject(helper)) { helper.metadata = assign(helper.metadata, { isHelper: true }); return helper; } }, resolve: resolve, resolveHash: resolveHash, looksLikeOptions: looksLikeOptions }; }); /*can-stache@4.0.0-pre.26#src/lookup-value-or-helper*/ define('can-stache/src/lookup-value-or-helper', [ 'require', 'exports', 'module', 'can-stache/src/expression-helpers', 'can-stache/helpers/core', 'can-stache/src/lookup-priorities' ], function (require, exports, module) { var expressionHelpers = require('can-stache/src/expression-helpers'); var mustacheHelpers = require('can-stache/helpers/core'); var lookupPriorities = require('can-stache/src/lookup-priorities'); function lookupValueOrHelper(key, scope, readOptions) { var helper, helperPriority, scopeValue, scopeValuePriority; if (key.charAt(0) === '@') { key = key.substr(1); } helper = mustacheHelpers.getHelper(key, scope); helperPriority = helper && helper.metadata.priority || lookupPriorities.MAX; if (helperPriority < lookupPriorities.SCOPE_FUNCTION) { return helper; } scopeValue = expressionHelpers.getObservableValue_fromKey(key, scope, readOptions); if (helper && scopeValue.initialValue === undefined) { return helper; } scopeValuePriority = typeof scopeValue.initialValue === 'function' ? lookupPriorities.SCOPE_FUNCTION : lookupPriorities.SCOPE_PROPERTY; return helperPriority < scopeValuePriority ? helper : scopeValue; } module.exports = lookupValueOrHelper; }); /*can-stache@4.0.0-pre.26#expressions/lookup*/ define('can-stache/expressions/lookup', [ 'require', 'exports', 'module', 'can-stache/src/expression-helpers', 'can-stache/src/lookup-value-or-helper', 'can-reflect', 'can-symbol', 'can-assign' ], function (require, exports, module) { var expressionHelpers = require('can-stache/src/expression-helpers'); var lookupValueOrHelper = require('can-stache/src/lookup-value-or-helper'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var sourceTextSymbol = canSymbol.for('can-stache.sourceText'); var assign = require('can-assign'); var Lookup = function (key, root, sourceText) { this.key = key; this.rootExpr = root; canReflect.setKeyValue(this, sourceTextSymbol, sourceText); }; Lookup.prototype.value = function (scope) { if (this.rootExpr) { return expressionHelpers.getObservableValue_fromDynamicKey_fromObservable(this.key, this.rootExpr.value(scope), scope, {}, {}); } else { var result = lookupValueOrHelper(this.key, scope); assign(this, result.metadata); return result; } }; Lookup.prototype.sourceText = function () { if (this[sourceTextSymbol]) { return this[sourceTextSymbol]; } else if (this.rootExpr) { return this.rootExpr.sourceText() + '.' + this.key; } else { return this.key; } }; module.exports = Lookup; }); /*can-stache@4.0.0-pre.26#expressions/scope-lookup*/ define('can-stache/expressions/scope-lookup', [ 'require', 'exports', 'module', 'can-stache/src/expression-helpers', 'can-stache/expressions/lookup' ], function (require, exports, module) { var expressionHelpers = require('can-stache/src/expression-helpers'); var Lookup = require('can-stache/expressions/lookup'); var ScopeLookup = function (key, root) { Lookup.apply(this, arguments); }; ScopeLookup.prototype.value = function (scope, helperOptions) { if (this.rootExpr) { return expressionHelpers.getObservableValue_fromDynamicKey_fromObservable(this.key, this.rootExpr.value(scope, helperOptions), scope, {}, {}); } return expressionHelpers.getObservableValue_fromKey(this.key, scope, helperOptions); }; ScopeLookup.prototype.sourceText = Lookup.prototype.sourceText; module.exports = ScopeLookup; }); /*can-stache@4.0.0-pre.26#expressions/helper*/ define('can-stache/expressions/helper', [ 'require', 'exports', 'module', 'can-stache/expressions/literal', 'can-stache/expressions/hashes', 'can-observation', 'can-assign', 'can-log/dev/dev', 'can-util/js/is-empty-object/is-empty-object', 'can-stache/src/expression-helpers', 'can-stache/src/utils', 'can-stache/helpers/core', 'can-reflect', 'can-stache/src/lookup-value-or-helper', 'can-view-scope/scope-key-data' ], function (require, exports, module) { var Literal = require('can-stache/expressions/literal'); var Hashes = require('can-stache/expressions/hashes'); var Observation = require('can-observation'); var assign = require('can-assign'); var dev = require('can-log/dev/dev'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var expressionHelpers = require('can-stache/src/expression-helpers'); var utils = require('can-stache/src/utils'); var mustacheHelpers = require('can-stache/helpers/core'); var canReflect = require('can-reflect'); var lookupValueOrHelper = require('can-stache/src/lookup-value-or-helper'); var ScopeKeyData = require('can-view-scope/scope-key-data'); var Helper = function (methodExpression, argExpressions, hashExpressions) { this.methodExpr = methodExpression; this.argExprs = argExpressions; this.hashExprs = hashExpressions; this.mode = null; }; Helper.prototype.args = function (scope) { var args = []; for (var i = 0, len = this.argExprs.length; i < len; i++) { var arg = this.argExprs[i]; args.push(expressionHelpers.toComputeOrValue(arg.value.apply(arg, arguments))); } return args; }; Helper.prototype.hash = function (scope) { var hash = {}; for (var prop in this.hashExprs) { var val = this.hashExprs[prop]; hash[prop] = expressionHelpers.toComputeOrValue(val.value.apply(val, arguments)); } return hash; }; Helper.prototype.helperAndValue = function (scope) { var helperOrValue, computeData, methodKey = this.methodExpr instanceof Literal ? '' + this.methodExpr._value : this.methodExpr.key, initialValue, args; var filename = scope.peek('scope.filename'); helperOrValue = lookupValueOrHelper(methodKey, scope); if (helperOrValue instanceof ScopeKeyData) { args = this.args(scope).map(expressionHelpers.toComputeOrValue); if (typeof helperOrValue.initialValue === 'function') { function helperFn() { return helperOrValue.initialValue.apply(null, args); } Object.defineProperty(helperFn, 'name', { value: canReflect.getName(this) }); return { value: helperFn }; } else if (typeof helperOrValue.initialValue !== 'undefined') { return { value: helperOrValue }; } else { dev.warn('can-stache/expressions/helper.js: Unable to find key or helper "' + methodKey + '".'); } return { value: helperOrValue, args: args }; } return { helper: helperOrValue && helperOrValue.fn }; }; Helper.prototype.evaluator = function (helper, scope, readOptions, nodeList, truthyRenderer, falseyRenderer, stringOnly) { var helperOptionArg = { stringOnly: stringOnly }, context = scope.peek('.'), args = this.args(scope), hash = this.hash(scope); utils.convertToScopes(helperOptionArg, scope, nodeList, truthyRenderer, falseyRenderer, stringOnly); assign(helperOptionArg, { context: context, scope: scope, contexts: scope, hash: hash, nodeList: nodeList, exprData: this }); args.push(helperOptionArg); return function () { return helper.apply(context, args); }; }; Helper.prototype.value = function (scope, nodeList, truthyRenderer, falseyRenderer, stringOnly) { var helperAndValue = this.helperAndValue(scope); var helper = helperAndValue.helper; if (!helper) { return helperAndValue.value; } var fn = this.evaluator(helper, scope, nodeList, truthyRenderer, falseyRenderer, stringOnly); var computeValue = new Observation(fn); Observation.temporarilyBind(computeValue); if (!expressionHelpers.computeHasDependencies(computeValue)) { return computeValue(); } else { return computeValue; } }; Helper.prototype.closingTag = function () { return this.methodExpr.key; }; Helper.prototype.sourceText = function () { var text = [this.methodExpr.sourceText()]; if (this.argExprs.length) { text.push(this.argExprs.map(function (arg) { return arg.sourceText(); }).join(' ')); } if (!isEmptyObject(this.hashExprs)) { text.push(Hashes.prototype.sourceText.call(this)); } return text.join(' '); }; canReflect.assignSymbols(Helper.prototype, { 'can.getName': function () { return canReflect.getName(this.constructor) + '{{' + this.sourceText() + '}}'; } }); module.exports = Helper; }); /*can-stache@4.0.0-pre.26#expressions/helper-lookup*/ define('can-stache/expressions/helper-lookup', [ 'require', 'exports', 'module', 'can-stache/expressions/lookup', 'can-stache/src/lookup-value-or-helper' ], function (require, exports, module) { var Lookup = require('can-stache/expressions/lookup'); var lookupValueOrHelper = require('can-stache/src/lookup-value-or-helper'); var HelperLookup = function () { Lookup.apply(this, arguments); }; HelperLookup.prototype.value = function (scope, helperOptions) { return lookupValueOrHelper(this.key, scope, helperOptions, { isArgument: true, args: [ scope.peek('.'), scope ] }); }; HelperLookup.prototype.sourceText = Lookup.prototype.sourceText; module.exports = HelperLookup; }); /*can-stache@4.0.0-pre.26#expressions/helper-scope-lookup*/ define('can-stache/expressions/helper-scope-lookup', [ 'require', 'exports', 'module', 'can-stache/expressions/lookup', 'can-stache/src/expression-helpers' ], function (require, exports, module) { var Lookup = require('can-stache/expressions/lookup'); var expressionHelpers = require('can-stache/src/expression-helpers'); var HelperScopeLookup = function () { Lookup.apply(this, arguments); }; HelperScopeLookup.prototype.value = function (scope, helperOptions) { return expressionHelpers.getObservableValue_fromKey(this.key, scope, { filename: scope.peek('scope.filename'), lineNumber: scope.peek('scope.lineNumber'), args: [ scope.peek('.'), scope ] }); }; HelperScopeLookup.prototype.sourceText = Lookup.prototype.sourceText; module.exports = HelperScopeLookup; }); /*can-util@3.10.18#js/last/last*/ define('can-util/js/last/last', function (require, exports, module) { 'use strict'; module.exports = function (arr) { return arr && arr[arr.length - 1]; }; }); /*can-stache@4.0.0-pre.26#src/expression*/ define('can-stache/src/expression', [ 'require', 'exports', 'module', 'can-stache/expressions/arg', 'can-stache/expressions/literal', 'can-stache/expressions/hashes', 'can-stache/expressions/bracket', 'can-stache/expressions/call', 'can-stache/expressions/scope-lookup', 'can-stache/expressions/helper', 'can-stache/expressions/lookup', 'can-stache/expressions/helper-lookup', 'can-stache/expressions/helper-scope-lookup', 'can-stache/src/set-identifier', 'can-stache/src/expression-helpers', 'can-stache/src/utils', 'can-assign', 'can-util/js/last/last', 'can-reflect', 'can-symbol' ], function (require, exports, module) { var Arg = require('can-stache/expressions/arg'); var Literal = require('can-stache/expressions/literal'); var Hashes = require('can-stache/expressions/hashes'); var Bracket = require('can-stache/expressions/bracket'); var Call = require('can-stache/expressions/call'); var ScopeLookup = require('can-stache/expressions/scope-lookup'); var Helper = require('can-stache/expressions/helper'); var Lookup = require('can-stache/expressions/lookup'); var HelperLookup = require('can-stache/expressions/helper-lookup'); var HelperScopeLookup = require('can-stache/expressions/helper-scope-lookup'); var SetIdentifier = require('can-stache/src/set-identifier'); var expressionHelpers = require('can-stache/src/expression-helpers'); var utils = require('can-stache/src/utils'); var assign = require('can-assign'); var last = require('can-util/js/last/last'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var sourceTextSymbol = canSymbol.for('can-stache.sourceText'); var Hash = function () { }; var keyRegExp = /[\w\.\\\-_@\/\&%]+/, tokensRegExp = /('.*?'|".*?"|=|[\w\.\\\-_@\/*%\$]+|[\(\)]|,|\~|\[|\]\s*|\s*(?=\[))/g, bracketSpaceRegExp = /\]\s+/, literalRegExp = /^('.*?'|".*?"|[0-9]+\.?[0-9]*|true|false|null|undefined)$/; var isTokenKey = function (token) { return keyRegExp.test(token); }; var testDot = /^[\.@]\w/; var isAddingToExpression = function (token) { return isTokenKey(token) && testDot.test(token); }; var ensureChildren = function (type) { if (!type.children) { type.children = []; } return type; }; var Stack = function () { this.root = { children: [], type: 'Root' }; this.current = this.root; this.stack = [this.root]; }; assign(Stack.prototype, { top: function () { return last(this.stack); }, isRootTop: function () { return this.top() === this.root; }, popTo: function (types) { this.popUntil(types); this.pop(); }, pop: function () { if (!this.isRootTop()) { this.stack.pop(); } }, first: function (types) { var curIndex = this.stack.length - 1; while (curIndex > 0 && types.indexOf(this.stack[curIndex].type) === -1) { curIndex--; } return this.stack[curIndex]; }, firstParent: function (types) { var curIndex = this.stack.length - 2; while (curIndex > 0 && types.indexOf(this.stack[curIndex].type) === -1) { curIndex--; } return this.stack[curIndex]; }, popUntil: function (types) { while (types.indexOf(this.top().type) === -1 && !this.isRootTop()) { this.stack.pop(); } return this.top(); }, addTo: function (types, type) { var cur = this.popUntil(types); ensureChildren(cur).children.push(type); }, addToAndPush: function (types, type) { this.addTo(types, type); this.stack.push(type); }, push: function (type) { this.stack.push(type); }, topLastChild: function () { return last(this.top().children); }, replaceTopLastChild: function (type) { var children = ensureChildren(this.top()).children; children.pop(); children.push(type); return type; }, replaceTopLastChildAndPush: function (type) { this.replaceTopLastChild(type); this.stack.push(type); }, replaceTopAndPush: function (type) { var children; if (this.top() === this.root) { children = ensureChildren(this.top()).children; } else { this.stack.pop(); children = ensureChildren(this.top()).children; } children.pop(); children.push(type); this.stack.push(type); return type; } }); var convertKeyToLookup = function (key) { var lastPath = key.lastIndexOf('./'); var lastDot = key.lastIndexOf('.'); if (lastDot > lastPath) { return key.substr(0, lastDot) + '@' + key.substr(lastDot + 1); } var firstNonPathCharIndex = lastPath === -1 ? 0 : lastPath + 2; var firstNonPathChar = key.charAt(firstNonPathCharIndex); if (firstNonPathChar === '.' || firstNonPathChar === '@') { return key.substr(0, firstNonPathCharIndex) + '@' + key.substr(firstNonPathCharIndex + 1); } else { return key.substr(0, firstNonPathCharIndex) + '@' + key.substr(firstNonPathCharIndex); } }; var convertToAtLookup = function (ast) { if (ast.type === 'Lookup') { canReflect.setKeyValue(ast, sourceTextSymbol, ast.key); ast.key = convertKeyToLookup(ast.key); } return ast; }; var convertToHelperIfTopIsLookup = function (stack) { var top = stack.top(); if (top && top.type === 'Lookup') { var base = stack.stack[stack.stack.length - 2]; if (base.type !== 'Helper' && base) { stack.replaceTopAndPush({ type: 'Helper', method: top }); } } }; var expression = { toComputeOrValue: expressionHelpers.toComputeOrValue, convertKeyToLookup: convertKeyToLookup, Literal: Literal, Lookup: Lookup, ScopeLookup: ScopeLookup, Arg: Arg, Hash: Hash, Hashes: Hashes, Call: Call, Helper: Helper, HelperLookup: HelperLookup, HelperScopeLookup: HelperScopeLookup, Bracket: Bracket, SetIdentifier: SetIdentifier, tokenize: function (expression) { var tokens = []; (expression.trim() + ' ').replace(tokensRegExp, function (whole, arg) { if (bracketSpaceRegExp.test(arg)) { tokens.push(arg[0]); tokens.push(arg.slice(1)); } else { tokens.push(arg); } }); return tokens; }, lookupRules: { 'default': function (ast, methodType, isArg) { var name = (methodType === 'Helper' && !ast.root ? 'Helper' : '') + (isArg ? 'Scope' : '') + 'Lookup'; return expression[name]; }, 'method': function (ast, methodType, isArg) { return ScopeLookup; } }, methodRules: { 'default': function (ast) { return ast.type === 'Call' ? Call : Helper; }, 'call': function (ast) { return Call; } }, parse: function (expressionString, options) { options = options || {}; var ast = this.ast(expressionString); if (!options.lookupRule) { options.lookupRule = 'default'; } if (typeof options.lookupRule === 'string') { options.lookupRule = expression.lookupRules[options.lookupRule]; } if (!options.methodRule) { options.methodRule = 'default'; } if (typeof options.methodRule === 'string') { options.methodRule = expression.methodRules[options.methodRule]; } var expr = this.hydrateAst(ast, options, options.baseMethodType || 'Helper'); return expr; }, hydrateAst: function (ast, options, methodType, isArg) { var hashes; if (ast.type === 'Lookup') { var lookup = new (options.lookupRule(ast, methodType, isArg))(ast.key, ast.root && this.hydrateAst(ast.root, options, methodType), ast[sourceTextSymbol]); return lookup; } else if (ast.type === 'Literal') { return new Literal(ast.value); } else if (ast.type === 'Arg') { return new Arg(this.hydrateAst(ast.children[0], options, methodType, isArg), { compute: true }); } else if (ast.type === 'Hash') { throw new Error(''); } else if (ast.type === 'Hashes') { hashes = {}; ast.children.forEach(function (hash) { hashes[hash.prop] = this.hydrateAst(hash.children[0], options, methodType, true); }, this); return new Hashes(hashes); } else if (ast.type === 'Call' || ast.type === 'Helper') { hashes = {}; var args = [], children = ast.children, ExpressionType = options.methodRule(ast); if (children) { for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.type === 'Hashes' && ast.type === 'Helper' && ExpressionType !== Call) { child.children.forEach(function (hash) { hashes[hash.prop] = this.hydrateAst(hash.children[0], options, ast.type, true); }, this); } else { args.push(this.hydrateAst(child, options, ast.type, true)); } } } return new ExpressionType(this.hydrateAst(ast.method, options, ast.type), args, hashes); } else if (ast.type === 'Bracket') { var originalKey; originalKey = ast[canSymbol.for('can-stache.originalKey')]; return new Bracket(this.hydrateAst(ast.children[0], options), ast.root ? this.hydrateAst(ast.root, options) : undefined, originalKey); } }, ast: function (expression) { var tokens = this.tokenize(expression); return this.parseAst(tokens, { index: 0 }); }, parseAst: function (tokens, cursor) { var stack = new Stack(), top, firstParent, lastToken; while (cursor.index < tokens.length) { var token = tokens[cursor.index], nextToken = tokens[cursor.index + 1]; cursor.index++; if (nextToken === '=') { top = stack.top(); if (top && top.type === 'Lookup') { firstParent = stack.firstParent([ 'Call', 'Helper', 'Hash' ]); if (firstParent.type === 'Call' || firstParent.type === 'Root') { stack.popUntil(['Call']); top = stack.top(); stack.replaceTopAndPush({ type: 'Helper', method: top.type === 'Root' ? last(top.children) : top }); } } firstParent = stack.firstParent([ 'Call', 'Helper', 'Hashes' ]); var hash = { type: 'Hash', prop: token }; if (firstParent.type === 'Hashes') { stack.addToAndPush(['Hashes'], hash); } else { stack.addToAndPush([ 'Helper', 'Call' ], { type: 'Hashes', children: [hash] }); stack.push(hash); } cursor.index++; } else if (literalRegExp.test(token)) { convertToHelperIfTopIsLookup(stack); firstParent = stack.first([ 'Helper', 'Call', 'Hash', 'Bracket' ]); if (firstParent.type === 'Hash' && (firstParent.children && firstParent.children.length > 0)) { stack.addTo([ 'Helper', 'Call', 'Bracket' ], { type: 'Literal', value: utils.jsonParse(token) }); } else if (firstParent.type === 'Bracket' && (firstParent.children && firstParent.children.length > 0)) { stack.addTo([ 'Helper', 'Call', 'Hash' ], { type: 'Literal', value: utils.jsonParse(token) }); } else { stack.addTo([ 'Helper', 'Call', 'Hash', 'Bracket' ], { type: 'Literal', value: utils.jsonParse(token) }); } } else if (keyRegExp.test(token)) { lastToken = stack.topLastChild(); firstParent = stack.first([ 'Helper', 'Call', 'Hash', 'Bracket' ]); if (lastToken && (lastToken.type === 'Call' || lastToken.type === 'Bracket') && isAddingToExpression(token)) { stack.replaceTopLastChildAndPush({ type: 'Lookup', root: lastToken, key: token.slice(1) }); } else if (firstParent.type === 'Bracket') { if (!(firstParent.children && firstParent.children.length > 0)) { stack.addToAndPush(['Bracket'], { type: 'Lookup', key: token }); } else { if (stack.first([ 'Helper', 'Call', 'Hash', 'Arg' ]).type === 'Helper' && token[0] !== '.') { stack.addToAndPush(['Helper'], { type: 'Lookup', key: token }); } else { stack.replaceTopAndPush({ type: 'Lookup', key: token.slice(1), root: firstParent }); } } } else { convertToHelperIfTopIsLookup(stack); stack.addToAndPush([ 'Helper', 'Call', 'Hash', 'Arg', 'Bracket' ], { type: 'Lookup', key: token }); } } else if (token === '~') { convertToHelperIfTopIsLookup(stack); stack.addToAndPush([ 'Helper', 'Call', 'Hash' ], { type: 'Arg', key: token }); } else if (token === '(') { top = stack.top(); if (top.type === 'Lookup') { stack.replaceTopAndPush({ type: 'Call', method: convertToAtLookup(top) }); } else { throw new Error('Unable to understand expression ' + tokens.join('')); } } else if (token === ')') { stack.popTo(['Call']); } else if (token === ',') { stack.popUntil(['Call']); } else if (token === '[') { top = stack.top(); lastToken = stack.topLastChild(); if (lastToken && (lastToken.type === 'Call' || lastToken.type === 'Bracket')) { stack.replaceTopAndPush({ type: 'Bracket', root: lastToken }); } else if (top.type === 'Lookup' || top.type === 'Bracket') { var bracket = { type: 'Bracket', root: top }; canReflect.setKeyValue(bracket, canSymbol.for('can-stache.originalKey'), top.key); stack.replaceTopAndPush(bracket); } else if (top.type === 'Call') { stack.addToAndPush(['Call'], { type: 'Bracket' }); } else if (top === ' ') { stack.popUntil(['Lookup']); convertToHelperIfTopIsLookup(stack); stack.addToAndPush([ 'Helper', 'Call', 'Hash' ], { type: 'Bracket' }); } else { stack.replaceTopAndPush({ type: 'Bracket' }); } } else if (token === ']') { stack.pop(); } else if (token === ' ') { stack.push(token); } } return stack.root.children[0]; } }; module.exports = expression; }); /*can-view-model@4.0.0-pre.5#can-view-model*/ define('can-view-model', [ 'require', 'exports', 'module', 'can-util/dom/data/data', 'can-simple-map', 'can-namespace', 'can-globals/document/document', 'can-util/js/is-array-like/is-array-like', 'can-reflect' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var domData = require('can-util/dom/data/data'); var SimpleMap = require('can-simple-map'); var ns = require('can-namespace'); var getDocument = require('can-globals/document/document'); var isArrayLike = require('can-util/js/is-array-like/is-array-like'); var canReflect = require('can-reflect'); module.exports = ns.viewModel = function (el, attr, val) { var scope; if (typeof el === 'string') { el = getDocument().querySelector(el); } else if (isArrayLike(el) && !el.nodeType) { el = el[0]; } if (canReflect.isObservableLike(attr) && canReflect.isMapLike(attr)) { return domData.set.call(el, 'viewModel', attr); } scope = domData.get.call(el, 'viewModel'); if (!scope) { scope = new SimpleMap(); domData.set.call(el, 'viewModel', scope); } switch (arguments.length) { case 0: case 1: return scope; case 2: return canReflect.getKeyValue(scope, attr); default: canReflect.setKeyValue(scope, attr, val); return el; } }; }(function () { return this; }(), require, exports, module)); }); /*can-stache-bindings@4.0.0-pre.21#can-event*/ define('can-stache-bindings/can-event', [ 'require', 'exports', 'module', 'can-reflect', 'can-util/dom/events/events' ], function (require, exports, module) { var canReflect = require('can-reflect'); var domEvents = require('can-util/dom/events/events'); var canEvent = { on: function on(eventName, handler, queue) { var listenWithDOM = domEvents.canAddEventListener.call(this); if (listenWithDOM) { domEvents.addEventListener.call(this, eventName, handler, queue); } else { canReflect.onKeyValue(this, eventName, handler, queue); } }, off: function off(eventName, handler, queue) { var listenWithDOM = domEvents.canAddEventListener.call(this); if (listenWithDOM) { domEvents.removeEventListener.call(this, eventName, handler, queue); } else { canReflect.offKeyValue(this, eventName, handler, queue); } }, one: function one(event, handler, queue) { var one = function () { canEvent.off.call(this, event, one, queue); return handler.apply(this, arguments); }; canEvent.on.call(this, event, one, queue); return this; } }; module.exports = canEvent; }); /*can-stache-bindings@4.0.0-pre.21#attribute-observable/get-event-name*/ define('can-stache-bindings/attribute-observable/get-event-name', [ 'require', 'exports', 'module', 'can-util/dom/attr/attr' ], function (require, exports, module) { var attr = require('can-util/dom/attr/attr'); var isRadioInput = function isRadioInput(el) { return el.nodeName.toLowerCase() === 'input' && el.type === 'radio'; }; var isValidProp = function isValidProp(prop, bindingData) { return prop === 'checked' && !bindingData.legacyBindings; }; var isSpecialProp = function isSpecialProp(prop) { return attr.special[prop] && attr.special[prop].addEventListener; }; module.exports = function getEventName(el, prop, bindingData) { var event = 'change'; if (isRadioInput(el) && isValidProp(prop, bindingData)) { event = 'radiochange'; } if (isSpecialProp(prop)) { event = prop; } return event; }; }); /*can-stache-bindings@4.0.0-pre.21#attribute-observable/attribute-observable*/ define('can-stache-bindings/attribute-observable/attribute-observable', [ 'require', 'exports', 'module', 'can-queues', 'can-stache-bindings/can-event', 'can-reflect', 'can-observation', 'can-util/dom/attr/attr', 'can-stache-bindings/attribute-observable/get-event-name', 'can-reflect-dependencies', 'can-observation-recorder', 'can-simple-observable/settable/settable' ], function (require, exports, module) { var queues = require('can-queues'); var canEvent = require('can-stache-bindings/can-event'); var canReflect = require('can-reflect'); var Observation = require('can-observation'); var attr = require('can-util/dom/attr/attr'); var getEventName = require('can-stache-bindings/attribute-observable/get-event-name'); var canReflectDeps = require('can-reflect-dependencies'); var ObservationRecorder = require('can-observation-recorder'); var SettableObservable = require('can-simple-observable/settable/settable'); var isSelect = function isSelect(el) { return el.nodeName.toLowerCase() === 'select'; }; var isMultipleSelect = function isMultipleSelect(el, prop) { return isSelect(el) && prop === 'value' && el.multiple; }; function AttributeObservable(el, prop, bindingData, event) { this.el = el; this.bound = false; this.bindingData = bindingData; this.prop = isMultipleSelect(el, prop) ? 'values' : prop; this.event = event || getEventName(el, prop, bindingData); this.handler = this.handler.bind(this); canReflectDeps.addMutatedBy(this.el, this.prop, this); canReflect.assignSymbols(this, { 'can.getName': function getName() { return 'AttributeObservable<' + el.nodeName.toLowerCase() + '.' + this.prop + '>'; } }); } AttributeObservable.prototype = Object.create(SettableObservable.prototype); Object.assign(AttributeObservable.prototype, { constructor: AttributeObservable, get: function get() { if (ObservationRecorder.isRecording()) { ObservationRecorder.add(this); if (!this.bound) { Observation.temporarilyBind(this); } } return attr.get(this.el, this.prop); }, set: function set(newVal) { attr.setAttrOrProp(this.el, this.prop, newVal); this.value = newVal; return newVal; }, handler: function handler(newVal) { var old = this.value; this.value = attr.get(this.el, this.prop); if (this.value !== old) { if (typeof this._log === 'function') { this._log(old, newVal); } queues.enqueueByQueue(this.handlers.getNode([]), this, [ newVal, old ], function () { return {}; }); } }, onBound: function onBound() { var observable = this; observable.bound = true; observable._handler = function () { observable.handler(attr.get(observable.el, observable.prop)); }; if (observable.event === 'radiochange') { canEvent.on.call(observable.el, 'change', observable._handler); } canEvent.on.call(observable.el, observable.event, observable._handler); this.value = attr.get(this.el, this.prop); }, onUnbound: function onUnbound() { var observable = this; observable.bound = false; if (observable.event === 'radiochange') { canEvent.off.call(observable.el, 'change', observable._handler); } canEvent.off.call(observable.el, observable.event, observable._handler); }, valueHasDependencies: function valueHasDependencies() { return true; }, getValueDependencies: function getValueDependencies() { return { keyDependencies: new Map([[ this.el, new Set([this.prop]) ]]) }; } }); canReflect.assignSymbols(AttributeObservable.prototype, { 'can.isMapLike': false, 'can.getValue': AttributeObservable.prototype.get, 'can.setValue': AttributeObservable.prototype.set, 'can.onValue': AttributeObservable.prototype.on, 'can.offValue': AttributeObservable.prototype.off, 'can.valueHasDependencies': AttributeObservable.prototype.hasDependencies, 'can.getValueDependencies': AttributeObservable.prototype.getValueDependencies }); module.exports = AttributeObservable; }); /*can-dom-events@1.0.7#helpers/util*/ define('can-dom-events/helpers/util', [ 'require', 'exports', 'module', 'can-globals/document/document', 'can-globals/is-browser-window/is-browser-window' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var getCurrentDocument = require('can-globals/document/document'); var isBrowserWindow = require('can-globals/is-browser-window/is-browser-window'); function getTargetDocument(target) { return target.ownerDocument || getCurrentDocument(); } function createEvent(target, eventData, bubbles, cancelable) { var doc = getTargetDocument(target); var event = doc.createEvent('HTMLEvents'); var eventType; if (typeof eventData === 'string') { eventType = eventData; } else { eventType = eventData.type; for (var prop in eventData) { if (event[prop] === undefined) { event[prop] = eventData[prop]; } } } if (bubbles === undefined) { bubbles = true; } event.initEvent(eventType, bubbles, cancelable); return event; } function isDomEventTarget(obj) { if (!(obj && obj.nodeName)) { return obj === window; } var nodeType = obj.nodeType; return nodeType === 1 || nodeType === 9 || nodeType === 11; } function addDomContext(context, args) { if (isDomEventTarget(context)) { args = Array.prototype.slice.call(args, 0); args.unshift(context); } return args; } function removeDomContext(context, args) { if (!isDomEventTarget(context)) { args = Array.prototype.slice.call(args, 0); context = args.shift(); } return { context: context, args: args }; } var fixSyntheticEventsOnDisabled = false; (function () { if (!isBrowserWindow()) { return; } var testEventName = 'fix_synthetic_events_on_disabled_test'; var input = document.createElement('input'); input.disabled = true; var timer = setTimeout(function () { fixSyntheticEventsOnDisabled = true; }, 50); var onTest = function onTest() { clearTimeout(timer); input.removeEventListener(testEventName, onTest); }; input.addEventListener(testEventName, onTest); try { var event = document.create('HTMLEvents'); event.initEvent(testEventName, false); input.dispatchEvent(event); } catch (e) { onTest(); fixSyntheticEventsOnDisabled = true; } }()); function isDispatchingOnDisabled(element, event) { var eventType = event.type; var isInsertedOrRemoved = eventType === 'inserted' || eventType === 'removed'; var isDisabled = !!element.disabled; return isInsertedOrRemoved && isDisabled; } function forceEnabledForDispatch(element, event) { return fixSyntheticEventsOnDisabled && isDispatchingOnDisabled(element, event); } module.exports = { createEvent: createEvent, addDomContext: addDomContext, removeDomContext: removeDomContext, isDomEventTarget: isDomEventTarget, getTargetDocument: getTargetDocument, forceEnabledForDispatch: forceEnabledForDispatch }; }(function () { return this; }(), require, exports, module)); }); /*can-dom-events@1.0.7#helpers/add-event-compat*/ define('can-dom-events/helpers/add-event-compat', [ 'require', 'exports', 'module', 'can-dom-events/helpers/util' ], function (require, exports, module) { 'use strict'; var util = require('can-dom-events/helpers/util'); var addDomContext = util.addDomContext; var removeDomContext = util.removeDomContext; function isDomEvents(obj) { return !!(obj && obj.addEventListener && obj.removeEventListener && obj.dispatch); } function isNewEvents(obj) { return typeof obj.addEvent === 'function'; } module.exports = function addEventCompat(domEvents, customEvent, customEventType) { if (!isDomEvents(domEvents)) { throw new Error('addEventCompat() must be passed can-dom-events or can-util/dom/events/events'); } customEventType = customEventType || customEvent.defaultEventType; if (isNewEvents(domEvents)) { return domEvents.addEvent(customEvent, customEventType); } var registry = domEvents._compatRegistry; if (!registry) { registry = domEvents._compatRegistry = {}; } if (registry[customEventType]) { return function noopRemoveOverride() { }; } registry[customEventType] = customEvent; var newEvents = { addEventListener: function () { var data = removeDomContext(this, arguments); return domEvents.addEventListener.apply(data.context, data.args); }, removeEventListener: function () { var data = removeDomContext(this, arguments); return domEvents.removeEventListener.apply(data.context, data.args); }, dispatch: function () { var data = removeDomContext(this, arguments); var eventData = data.args[0]; var eventArgs = typeof eventData === 'object' ? eventData.args : []; data.args.splice(1, 0, eventArgs); return domEvents.dispatch.apply(data.context, data.args); } }; var isOverriding = true; var oldAddEventListener = domEvents.addEventListener; var addEventListener = domEvents.addEventListener = function addEventListener(eventName) { if (isOverriding && eventName === customEventType) { var args = addDomContext(this, arguments); customEvent.addEventListener.apply(newEvents, args); } return oldAddEventListener.apply(this, arguments); }; var oldRemoveEventListener = domEvents.removeEventListener; var removeEventListener = domEvents.removeEventListener = function removeEventListener(eventName) { if (isOverriding && eventName === customEventType) { var args = addDomContext(this, arguments); customEvent.removeEventListener.apply(newEvents, args); } return oldRemoveEventListener.apply(this, arguments); }; return function removeOverride() { isOverriding = false; registry[customEventType] = null; if (domEvents.addEventListener === addEventListener) { domEvents.addEventListener = oldAddEventListener; } if (domEvents.removeEventListener === removeEventListener) { domEvents.removeEventListener = oldRemoveEventListener; } }; }; }); /*can-event-dom-enter@1.0.4#can-event-dom-enter*/ define('can-event-dom-enter', [ 'require', 'exports', 'module', 'can-dom-data-state', 'can-cid' ], function (require, exports, module) { 'use strict'; var domData = require('can-dom-data-state'); var canCid = require('can-cid'); var baseEventType = 'keyup'; function isEnterEvent(event) { var hasEnterKey = event.key === 'Enter'; var hasEnterCode = event.keyCode === 13; return hasEnterKey || hasEnterCode; } function getHandlerKey(eventType, handler) { return eventType + ':' + canCid(handler); } function associateHandler(target, eventType, handler, otherHandler) { var key = getHandlerKey(eventType, handler); domData.set.call(target, key, otherHandler); } function disassociateHandler(target, eventType, handler) { var key = getHandlerKey(eventType, handler); var otherHandler = domData.get.call(target, key); if (otherHandler) { domData.clean.call(target, key); } return otherHandler; } module.exports = { defaultEventType: 'enter', addEventListener: function (target, eventType, handler) { var keyHandler = function (event) { if (isEnterEvent(event)) { return handler.apply(this, arguments); } }; associateHandler(target, eventType, handler, keyHandler); this.addEventListener(target, baseEventType, keyHandler); }, removeEventListener: function (target, eventType, handler) { var keyHandler = disassociateHandler(target, eventType, handler); if (keyHandler) { this.removeEventListener(target, baseEventType, keyHandler); } } }; }); /*can-event-dom-enter@1.0.4#compat*/ define('can-event-dom-enter/compat', [ 'require', 'exports', 'module', 'can-dom-events/helpers/add-event-compat', 'can-event-dom-enter' ], function (require, exports, module) { var addEventCompat = require('can-dom-events/helpers/add-event-compat'); var radioChange = require('can-event-dom-enter'); module.exports = function (domEvents, eventType) { return addEventCompat(domEvents, radioChange, eventType); }; }); /*can-dom-events@1.0.7#helpers/make-event-registry*/ define('can-dom-events/helpers/make-event-registry', function (require, exports, module) { 'use strict'; function EventRegistry() { this._registry = {}; } module.exports = function makeEventRegistry() { return new EventRegistry(); }; EventRegistry.prototype.has = function (eventType) { return !!this._registry[eventType]; }; EventRegistry.prototype.get = function (eventType) { return this._registry[eventType]; }; EventRegistry.prototype.add = function (event, eventType) { if (!event) { throw new Error('An EventDefinition must be provided'); } if (typeof event.addEventListener !== 'function') { throw new TypeError('EventDefinition addEventListener must be a function'); } if (typeof event.removeEventListener !== 'function') { throw new TypeError('EventDefinition removeEventListener must be a function'); } eventType = eventType || event.defaultEventType; if (typeof eventType !== 'string') { throw new TypeError('Event type must be a string, not ' + eventType); } if (this.has(eventType)) { throw new Error('Event "' + eventType + '" is already registered'); } this._registry[eventType] = event; var self = this; return function remove() { self._registry[eventType] = undefined; }; }; }); /*can-dom-events@1.0.7#can-dom-events*/ define('can-dom-events', [ 'require', 'exports', 'module', 'can-namespace', 'can-dom-events/helpers/util', 'can-dom-events/helpers/make-event-registry' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var namespace = require('can-namespace'); var util = require('can-dom-events/helpers/util'); var makeEventRegistry = require('can-dom-events/helpers/make-event-registry'); var domEvents = { _eventRegistry: makeEventRegistry(), addEvent: function (event, eventType) { return this._eventRegistry.add(event, eventType); }, addEventListener: function (target, eventType) { var hasCustomEvent = domEvents._eventRegistry.has(eventType); if (hasCustomEvent) { var event = domEvents._eventRegistry.get(eventType); return event.addEventListener.apply(domEvents, arguments); } var eventArgs = Array.prototype.slice.call(arguments, 1); return target.addEventListener.apply(target, eventArgs); }, removeEventListener: function (target, eventType) { var hasCustomEvent = domEvents._eventRegistry.has(eventType); if (hasCustomEvent) { var event = domEvents._eventRegistry.get(eventType); return event.removeEventListener.apply(domEvents, arguments); } var eventArgs = Array.prototype.slice.call(arguments, 1); return target.removeEventListener.apply(target, eventArgs); }, dispatch: function (target, eventData, bubbles, cancelable) { var event = util.createEvent(target, eventData, bubbles, cancelable); var enableForDispatch = util.forceEnabledForDispatch(target, event); if (enableForDispatch) { target.disabled = false; } var ret = target.dispatchEvent(event); if (enableForDispatch) { target.disabled = true; } return ret; } }; module.exports = namespace.domEvents = domEvents; }(function () { return this; }(), require, exports, module)); }); /*can-event-dom-radiochange@1.0.5#can-event-dom-radiochange*/ define('can-event-dom-radiochange', [ 'require', 'exports', 'module', 'can-dom-data-state', 'can-globals/document/document', 'can-dom-events', 'can-cid/map/map' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var domData = require('can-dom-data-state'); var getDocument = require('can-globals/document/document'); var domEvents = require('can-dom-events'); var CIDMap = require('can-cid/map/map'); function getRoot(el) { return el.ownerDocument || getDocument().documentElement; } function getRegistryName(eventName) { return 'can-event-radiochange:' + eventName + ':registry'; } function getListenerName(eventName) { return 'can-event-radiochange:' + eventName + ':listener'; } function getRegistry(root, eventName) { var name = getRegistryName(eventName); var registry = domData.get.call(root, name); if (!registry) { registry = new CIDMap(); domData.set.call(root, name, registry); } return registry; } function findParentForm(el) { while (el) { if (el.nodeName === 'FORM') { break; } el = el.parentNode; } return el; } function shouldReceiveEventFromRadio(source, dest) { var name = source.getAttribute('name'); return name && name === dest.getAttribute('name') && findParentForm(source) === findParentForm(dest); } function isRadioInput(el) { return el.nodeName === 'INPUT' && el.type === 'radio'; } function dispatch(eventName, target) { var root = getRoot(target); var registry = getRegistry(root, eventName); registry.forEach(function (el) { if (shouldReceiveEventFromRadio(target, el)) { domEvents.dispatch(el, eventName); } }); } function attachRootListener(root, eventName, events) { var listenerName = getListenerName(eventName); var listener = domData.get.call(root, listenerName); if (listener) { return; } var newListener = function (event) { var target = event.target; if (isRadioInput(target)) { dispatch(eventName, target); } }; events.addEventListener(root, 'change', newListener); domData.set.call(root, listenerName, newListener); } function detachRootListener(root, eventName, events) { var listenerName = getListenerName(eventName); var listener = domData.get.call(root, listenerName); if (!listener) { return; } var registry = getRegistry(root, eventName); if (registry.size > 0) { return; } events.removeEventListener(root, 'change', listener); domData.clean.call(root, listenerName); } function addListener(eventName, el, events) { if (!isRadioInput(el)) { throw new Error('Listeners for ' + eventName + ' must be radio inputs'); } var root = getRoot(el); getRegistry(root, eventName).set(el, el); attachRootListener(root, eventName, events); } function removeListener(eventName, el, events) { var root = getRoot(el); getRegistry(root, eventName).delete(el); detachRootListener(root, eventName, events); } module.exports = { defaultEventType: 'radiochange', addEventListener: function (target, eventName, handler) { addListener(eventName, target, this); target.addEventListener(eventName, handler); }, removeEventListener: function (target, eventName, handler) { removeListener(eventName, target, this); target.removeEventListener(eventName, handler); } }; }(function () { return this; }(), require, exports, module)); }); /*can-event-dom-radiochange@1.0.5#compat*/ define('can-event-dom-radiochange/compat', [ 'require', 'exports', 'module', 'can-dom-events/helpers/add-event-compat', 'can-event-dom-radiochange' ], function (require, exports, module) { var addEventCompat = require('can-dom-events/helpers/add-event-compat'); var radioChange = require('can-event-dom-radiochange'); module.exports = function (domEvents, eventType) { return addEventCompat(domEvents, radioChange, eventType); }; }); /*can-stache-bindings@4.0.0-pre.21#can-stache-bindings*/ define('can-stache-bindings', [ 'require', 'exports', 'module', 'can-stache/src/expression', 'can-view-callbacks', 'can-view-model', 'can-stache-key', 'can-observation-recorder', 'can-simple-observable', 'can-util/js/assign/assign', 'can-util/js/make-array/make-array', 'can-util/js/each/each', 'can-log/dev/dev', 'can-util/dom/events/events', 'can-util/dom/events/removed/removed', 'can-util/dom/data/data', 'can-symbol', 'can-reflect', 'can-reflect-dependencies', 'can-attribute-encoder', 'can-queues', 'can-simple-observable/setter/setter', 'can-stache-bindings/attribute-observable/attribute-observable', 'can-view-scope/make-compute-like', 'can-event-dom-enter/compat', 'can-event-dom-radiochange/compat', 'can-stache-bindings/can-event' ], function (require, exports, module) { var expression = require('can-stache/src/expression'); var viewCallbacks = require('can-view-callbacks'); var canViewModel = require('can-view-model'); var observeReader = require('can-stache-key'); var ObservationRecorder = require('can-observation-recorder'); var SimpleObservable = require('can-simple-observable'); var assign = require('can-util/js/assign/assign'); var makeArray = require('can-util/js/make-array/make-array'); var each = require('can-util/js/each/each'); var dev = require('can-log/dev/dev'); var domEvents = require('can-util/dom/events/events'); require('can-util/dom/events/removed/removed'); var domData = require('can-util/dom/data/data'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var canReflectDeps = require('can-reflect-dependencies'); var encoder = require('can-attribute-encoder'); var queues = require('can-queues'); var SettableObservable = require('can-simple-observable/setter/setter'); var AttributeObservable = require('can-stache-bindings/attribute-observable/attribute-observable'); var makeCompute = require('can-view-scope/make-compute-like'); var addEnterEvent = require('can-event-dom-enter/compat'); addEnterEvent(domEvents); var addRadioChange = require('can-event-dom-radiochange/compat'); addRadioChange(domEvents); var canEvent = require('can-stache-bindings/can-event'); var noop = function () { }; var onMatchStr = 'on:', vmMatchStr = 'vm:', elMatchStr = 'el:', byMatchStr = ':by:', toMatchStr = ':to', fromMatchStr = ':from', bindMatchStr = ':bind', attributesEventStr = 'attributes', removedStr = 'removed', viewModelBindingStr = 'viewModel', attributeBindingStr = 'attribute', scopeBindingStr = 'scope', viewModelOrAttributeBindingStr = 'viewModelOrAttribute', getValueSymbol = canSymbol.for('can.getValue'), onValueSymbol = canSymbol.for('can.onValue'), getChangesSymbol = canSymbol.for('can.getChangesDependencyRecord'); var throwOnlyOneTypeOfBindingError = function () { throw new Error('can-stache-bindings - you can not have contextual bindings ( this:from=\'value\' ) and key bindings ( prop:from=\'value\' ) on one element.'); }; var checkBindingState = function (bindingState, dataBinding) { var isSettingOnViewModel = dataBinding.bindingInfo.parentToChild && dataBinding.bindingInfo.child === viewModelBindingStr; if (isSettingOnViewModel) { var bindingName = dataBinding.bindingInfo.childName; var isSettingViewModel = isSettingOnViewModel && (bindingName === 'this' || bindingName === '.'); if (isSettingViewModel) { if (bindingState.isSettingViewModel || bindingState.isSettingOnViewModel) { throwOnlyOneTypeOfBindingError(); } else { return { isSettingViewModel: true, initialViewModelData: undefined }; } } else { if (bindingState.isSettingViewModel) { throwOnlyOneTypeOfBindingError(); } else { return { isSettingOnViewModel: true, initialViewModelData: bindingState.initialViewModelData }; } } } else { return bindingState; } }; var behaviors = { viewModel: function (el, tagData, makeViewModel, initialViewModelData, staticDataBindingsOnly) { var bindingsSemaphore = {}, viewModel, onCompleteBindings = [], onTeardowns = {}, bindingInfos = {}, attributeViewModelBindings = assign({}, initialViewModelData), bindingsState = { isSettingOnViewModel: false, isSettingViewModel: false, initialViewModelData: initialViewModelData || {} }, hasDataBinding = false; each(makeArray(el.attributes), function (node) { var dataBinding = makeDataBinding(node, el, { templateType: tagData.templateType, scope: tagData.scope, semaphore: bindingsSemaphore, getViewModel: function () { return viewModel; }, attributeViewModelBindings: attributeViewModelBindings, alreadyUpdatedChild: true, nodeList: tagData.parentNodeList, favorViewModel: true }); if (dataBinding) { bindingsState = checkBindingState(bindingsState, dataBinding); hasDataBinding = true; if (dataBinding.onCompleteBinding) { if (dataBinding.bindingInfo.parentToChild && dataBinding.value !== undefined) { if (bindingsState.isSettingViewModel) { bindingsState.initialViewModelData = dataBinding.value; } else { bindingsState.initialViewModelData[cleanVMName(dataBinding.bindingInfo.childName, tagData.scope)] = dataBinding.value; } } onCompleteBindings.push(dataBinding.onCompleteBinding); } onTeardowns[node.name] = dataBinding.onTeardown; } }); if (staticDataBindingsOnly && !hasDataBinding) { return; } viewModel = makeViewModel(bindingsState.initialViewModelData, hasDataBinding); for (var i = 0, len = onCompleteBindings.length; i < len; i++) { onCompleteBindings[i](); } var attributeListener; if (!bindingsState.isSettingViewModel) { attributeListener = function (ev) { var attrName = ev.attributeName, value = el.getAttribute(attrName); if (onTeardowns[attrName]) { onTeardowns[attrName](); } var parentBindingWasAttribute = bindingInfos[attrName] && bindingInfos[attrName].parent === attributeBindingStr; if (value !== null || parentBindingWasAttribute) { var dataBinding = makeDataBinding({ name: attrName, value: value }, el, { templateType: tagData.templateType, scope: tagData.scope, semaphore: {}, getViewModel: function () { return viewModel; }, attributeViewModelBindings: attributeViewModelBindings, initializeValues: true, nodeList: tagData.parentNodeList }); if (dataBinding) { if (dataBinding.onCompleteBinding) { dataBinding.onCompleteBinding(); } bindingInfos[attrName] = dataBinding.bindingInfo; onTeardowns[attrName] = dataBinding.onTeardown; } } }; domEvents.addEventListener.call(el, attributesEventStr, attributeListener); } return function () { domEvents.removeEventListener.call(el, attributesEventStr, attributeListener); for (var attrName in onTeardowns) { onTeardowns[attrName](); } }; }, data: function (el, attrData) { if (domData.get.call(el, 'preventDataBindings')) { return; } var viewModel, getViewModel = ObservationRecorder.ignore(function () { return viewModel || (viewModel = canViewModel(el)); }), semaphore = {}, teardown; var dataBinding = makeDataBinding({ name: attrData.attributeName, value: el.getAttribute(attrData.attributeName), nodeList: attrData.nodeList }, el, { templateType: attrData.templateType, scope: attrData.scope, semaphore: semaphore, getViewModel: getViewModel, syncChildWithParent: false }); if (dataBinding.bindingInfo.child === 'viewModel' && !domData.get(el, 'viewModel')) { dev.warn('This element does not have a viewModel. (Attempting to bind `' + dataBinding.bindingInfo.bindingAttributeName + '="' + dataBinding.bindingInfo.parentName + '"`)'); } if (dataBinding.onCompleteBinding) { dataBinding.onCompleteBinding(); } var attributeListener = function (ev) { var attrName = ev.attributeName, value = el.getAttribute(attrName); if (attrName === attrData.attributeName) { if (teardown) { teardown(); } if (value !== null) { var dataBinding = makeDataBinding({ name: attrName, value: value }, el, { templateType: attrData.templateType, scope: attrData.scope, semaphore: semaphore, getViewModel: getViewModel, initializeValues: true, nodeList: attrData.nodeList, syncChildWithParent: false }); if (dataBinding) { if (dataBinding.onCompleteBinding) { dataBinding.onCompleteBinding(); } teardown = dataBinding.onTeardown; } } } }; domEvents.addEventListener.call(el, attributesEventStr, attributeListener); teardown = dataBinding.onTeardown; canEvent.one.call(el, removedStr, function () { teardown(); domEvents.removeEventListener.call(el, attributesEventStr, attributeListener); }); }, event: function (el, data) { var attributeName = encoder.decode(data.attributeName), event, bindingContext; if (attributeName.indexOf(toMatchStr + ':') !== -1 || attributeName.indexOf(fromMatchStr + ':') !== -1 || attributeName.indexOf(bindMatchStr + ':') !== -1) { return this.data(el, data); } if (startsWith.call(attributeName, onMatchStr)) { event = attributeName.substr(onMatchStr.length); var viewModel = domData.get.call(el, viewModelBindingStr); var byParent = data.scope; if (startsWith.call(event, elMatchStr)) { event = event.substr(elMatchStr.length); bindingContext = el; } else { if (startsWith.call(event, vmMatchStr)) { event = event.substr(vmMatchStr.length); bindingContext = viewModel; byParent = viewModel; } else { bindingContext = viewModel || el; } var byIndex = event.indexOf(byMatchStr); if (byIndex >= 0) { bindingContext = byParent.get(event.substr(byIndex + byMatchStr.length)); event = event.substr(0, byIndex); } } } else { throw new Error('can-stache-bindings - unsupported event bindings ' + attributeName); } var handler = function (ev) { var attrVal = el.getAttribute(encoder.encode(attributeName)); if (!attrVal) { return; } var viewModel = canViewModel(el); var expr = expression.parse(attrVal, { lookupRule: function () { return expression.Lookup; }, methodRule: 'call' }); if (!(expr instanceof expression.Call)) { throw new Error('can-stache-bindings: Event bindings must be a call expression. Make sure you have a () in ' + data.attributeName + '=' + JSON.stringify(attrVal)); } var specialValues = { element: el, event: ev, viewModel: viewModel, arguments: arguments }; var localScope = data.scope.add(specialValues, { special: true }); var updateFn = function () { var value = expr.value(localScope, { doNotWrapInObservation: true }); value = canReflect.isValueLike(value) ? canReflect.getValue(value) : value; return typeof value === 'function' ? value(el) : value; }; Object.defineProperty(updateFn, 'name', { value: attributeName + '="' + attrVal + '"' }); queues.batch.start(); queues.notifyQueue.enqueue(updateFn, null, null, { reasonLog: [ el, ev, attributeName + '=' + attrVal ] }); queues.batch.stop(); }; var attributesHandler = function (ev) { var isEventAttribute = ev.attributeName === attributeName; var isRemoved = !this.getAttribute(attributeName); var isEventAttributeRemoved = isEventAttribute && isRemoved; if (isEventAttributeRemoved) { unbindEvent(); } }; var removedHandler = function (ev) { unbindEvent(); }; var unbindEvent = function () { canEvent.off.call(bindingContext, event, handler); canEvent.off.call(el, attributesEventStr, attributesHandler); canEvent.off.call(el, removedStr, removedHandler); }; canEvent.on.call(bindingContext, event, handler); canEvent.on.call(el, attributesEventStr, attributesHandler); canEvent.on.call(el, removedStr, removedHandler); } }; viewCallbacks.attr(/[\w\.:]+:to$/, behaviors.data); viewCallbacks.attr(/[\w\.:]+:from$/, behaviors.data); viewCallbacks.attr(/[\w\.:]+:bind$/, behaviors.data); viewCallbacks.attr(/[\w\.:]+:to:on:[\w\.:]+/, behaviors.data); viewCallbacks.attr(/[\w\.:]+:from:on:[\w\.:]+/, behaviors.data); viewCallbacks.attr(/[\w\.:]+:bind:on:[\w\.:]+/, behaviors.data); viewCallbacks.attr(/on:[\w\.:]+/, behaviors.event); var getObservableFrom = { viewModelOrAttribute: function (el, scope, vmNameOrProp, bindingData, mustBeSettable, stickyCompute, event) { var viewModel = domData.get.call(el, viewModelBindingStr); if (viewModel) { return this.viewModel.apply(this, arguments); } else { return this.attribute.apply(this, arguments); } }, scope: function (el, scope, scopeProp, bindingData, mustBeSettable, stickyCompute) { if (!scopeProp) { return new SimpleObservable(); } else { if (mustBeSettable) { var parentExpression = expression.parse(scopeProp, { baseMethodType: 'Call' }); return parentExpression.value(scope); } else { var observation = {}; canReflect.assignSymbols(observation, { 'can.getValue': function getValue() { }, 'can.valueHasDependencies': function hasValueDependencies() { return false; }, 'can.setValue': function setValue(newVal) { scope.set(cleanVMName(scopeProp, scope), newVal); }, 'can.getWhatIChange': function getWhatIChange() { var data = scope.getDataForScopeSet(cleanVMName(scopeProp, scope)); return { mutate: { keyDependencies: new Map([[ data.parent, new Set([data.key]) ]]) } }; }, 'can.getName': function getName() { var result = 'ObservableFromScope<>'; var data = scope.getDataForScopeSet(cleanVMName(scopeProp, scope)); if (data.parent && data.key) { result = 'ObservableFromScope<' + canReflect.getName(data.parent) + '.' + data.key + '>'; } return result; } }); var data = scope.getDataForScopeSet(cleanVMName(scopeProp, scope)); if (data.parent && data.key) { canReflectDeps.addMutatedBy(data.parent, data.key, observation); } return observation; } } }, viewModel: function (el, scope, vmName, bindingData, mustBeSettable, stickyCompute, childEvent) { var setName = cleanVMName(vmName, scope); var isBoundToContext = vmName === '.' || vmName === 'this'; var keysToRead = isBoundToContext ? [] : observeReader.reads(vmName); function getViewModelProperty() { var viewModel = bindingData.getViewModel(); return observeReader.read(viewModel, keysToRead, {}).value; } Object.defineProperty(getViewModelProperty, 'name', { value: 'viewModel.' + vmName }); var observation = new SettableObservable(getViewModelProperty, function setViewModelProperty(newVal) { var viewModel = bindingData.getViewModel(); if (stickyCompute) { var oldValue = canReflect.getKeyValue(viewModel, setName); if (canReflect.isObservableLike(oldValue)) { canReflect.setValue(oldValue, newVal); } else { canReflect.setKeyValue(viewModel, setName, new SimpleObservable(canReflect.getValue(stickyCompute))); } } else { if (isBoundToContext) { canReflect.setValue(viewModel, newVal); } else { canReflect.setKeyValue(viewModel, setName, newVal); } } }); var viewModel = bindingData.getViewModel(); if (viewModel && setName) { canReflectDeps.addMutatedBy(viewModel, setName, observation); } return observation; }, attribute: function (el, scope, prop, bindingData, mustBeSettable, stickyCompute, event, bindingInfo) { return new AttributeObservable(el, prop, bindingData, event); } }; var bind = { childToParent: function (el, parentObservable, childObservable, bindingsSemaphore, attrName, syncChild, bindingInfo) { function updateParent(newVal) { if (!bindingsSemaphore[attrName]) { if (parentObservable && parentObservable[getValueSymbol]) { var hasDependencies = canReflect.valueHasDependencies(parentObservable); if (!hasDependencies || canReflect.getValue(parentObservable) !== newVal) { canReflect.setValue(parentObservable, newVal); } if (syncChild && hasDependencies) { if (canReflect.getValue(parentObservable) !== canReflect.getValue(childObservable)) { bindingsSemaphore[attrName] = (bindingsSemaphore[attrName] || 0) + 1; queues.batch.start(); canReflect.setValue(childObservable, canReflect.getValue(parentObservable)); queues.mutateQueue.enqueue(function decrementChildToParentSemaphore() { --bindingsSemaphore[attrName]; }, null, [], {}); queues.batch.stop(); } } } else if (canReflect.isMapLike(parentObservable)) { var attrValue = el.getAttribute(attrName); dev.warn('can-stache-bindings: Merging ' + attrName + ' into ' + attrValue + ' because its parent is non-observable'); canReflect.eachKey(parentObservable, function (prop) { canReflect.deleteKeyValue(parentObservable, prop); }); canReflect.setValue(parentObservable, newVal && newVal.serialize ? newVal.serialize() : newVal, true); } } } Object.defineProperty(updateParent, 'name', { value: 'update ' + bindingInfo.parent + '.' + bindingInfo.parentName + ' of <' + el.nodeName.toLowerCase() + '>' }); if (childObservable && childObservable[getValueSymbol]) { canReflect.onValue(childObservable, updateParent, 'domUI'); updateParent[getChangesSymbol] = function () { return { valueDependencies: new Set([parentObservable]) }; }; canReflectDeps.addMutatedBy(parentObservable, childObservable); } return updateParent; }, parentToChild: function (el, parentObservable, childObservable, bindingsSemaphore, attrName, bindingInfo) { var updateChild = function (newValue) { bindingsSemaphore[attrName] = (bindingsSemaphore[attrName] || 0) + 1; queues.batch.start(); canReflect.setValue(childObservable, newValue); queues.mutateQueue.enqueue(function decrementParentToChildSemaphore() { --bindingsSemaphore[attrName]; }, null, [], {}); queues.batch.stop(); }; Object.defineProperty(updateChild, 'name', { value: 'update ' + bindingInfo.child + '.' + bindingInfo.childName + ' of <' + el.nodeName.toLowerCase() + '>' }); if (parentObservable && parentObservable[getValueSymbol]) { canReflect.onValue(parentObservable, updateChild, 'domUI'); canReflectDeps.addMutatedBy(childObservable, parentObservable); } return updateChild; } }; var startsWith = String.prototype.startsWith || function (text) { return this.indexOf(text) === 0; }; function getEventName(result) { if (result.special.on !== undefined) { return result.tokens[result.special.on + 1]; } } var bindingRules = { to: { childToParent: true, parentToChild: false, syncChildWithParent: false }, from: { childToParent: false, parentToChild: true, syncChildWithParent: false }, bind: { childToParent: true, parentToChild: true, syncChildWithParent: true } }; var bindingNames = []; var special = { vm: true, on: true }; each(bindingRules, function (value, key) { bindingNames.push(key); special[key] = true; }); function tokenize(source) { var splitByColon = source.split(':'); var result = { tokens: [], special: {} }; splitByColon.forEach(function (token) { if (special[token]) { result.special[token] = result.tokens.push(token) - 1; } else { result.tokens.push(token); } }); return result; } var getChildBindingStr = function (tokens, favorViewModel) { if (tokens.indexOf('vm') >= 0) { return viewModelBindingStr; } else if (tokens.indexOf('el') >= 0) { return attributeBindingStr; } else { return favorViewModel ? viewModelBindingStr : viewModelOrAttributeBindingStr; } }; var getBindingInfo = function (node, attributeViewModelBindings, templateType, tagName, favorViewModel) { var bindingInfo, attributeName = encoder.decode(node.name), attributeValue = node.value || ''; var result = tokenize(attributeName), dataBindingName, specialIndex; bindingNames.forEach(function (name) { if (result.special[name] !== undefined && result.special[name] > 0) { dataBindingName = name; specialIndex = result.special[name]; return false; } }); if (dataBindingName) { var childEventName = getEventName(result); var initializeValues = childEventName ? false : true; bindingInfo = assign({ parent: scopeBindingStr, child: getChildBindingStr(result.tokens, favorViewModel), childName: result.tokens[specialIndex - 1], childEvent: childEventName, bindingAttributeName: attributeName, parentName: attributeValue, initializeValues: initializeValues }, bindingRules[dataBindingName]); if (attributeValue.trim().charAt(0) === '~') { bindingInfo.stickyParentToChild = true; } return bindingInfo; } }; var makeDataBinding = function (node, el, bindingData) { var bindingInfo = getBindingInfo(node, bindingData.attributeViewModelBindings, bindingData.templateType, el.nodeName.toLowerCase(), bindingData.favorViewModel); if (!bindingInfo) { return; } bindingInfo.alreadyUpdatedChild = bindingData.alreadyUpdatedChild; if (bindingData.initializeValues) { bindingInfo.initializeValues = true; } var parentObservable = getObservableFrom[bindingInfo.parent](el, bindingData.scope, bindingInfo.parentName, bindingData, bindingInfo.parentToChild, undefined, undefined, bindingInfo), childObservable = getObservableFrom[bindingInfo.child](el, bindingData.scope, bindingInfo.childName, bindingData, bindingInfo.childToParent, bindingInfo.stickyParentToChild && parentObservable, bindingInfo.childEvent, bindingInfo), updateParent, updateChild; if (bindingData.nodeList) { if (parentObservable) { canReflect.setPriority(parentObservable, bindingData.nodeList.nesting + 1); } if (childObservable) { canReflect.setPriority(childObservable, bindingData.nodeList.nesting + 1); } } if (bindingInfo.parentToChild) { updateChild = bind.parentToChild(el, parentObservable, childObservable, bindingData.semaphore, bindingInfo.bindingAttributeName, bindingInfo); } var completeBinding = function () { if (bindingInfo.childToParent) { updateParent = bind.childToParent(el, parentObservable, childObservable, bindingData.semaphore, bindingInfo.bindingAttributeName, bindingInfo.syncChildWithParent, bindingInfo); } else if (bindingInfo.stickyParentToChild && childObservable[onValueSymbol]) { canReflect.onValue(childObservable, noop, 'mutate'); } if (bindingInfo.initializeValues) { initializeValues(bindingInfo, childObservable, parentObservable, updateChild, updateParent); } }; var onTeardown = function () { unbindUpdate(parentObservable, updateChild); unbindUpdate(childObservable, updateParent); unbindUpdate(childObservable, noop); }; if (bindingInfo.child === viewModelBindingStr) { return { value: bindingInfo.stickyParentToChild ? makeCompute(parentObservable) : canReflect.getValue(parentObservable), onCompleteBinding: completeBinding, bindingInfo: bindingInfo, onTeardown: onTeardown }; } else { completeBinding(); return { bindingInfo: bindingInfo, onTeardown: onTeardown }; } }; var initializeValues = function (bindingInfo, childObservable, parentObservable, updateChild, updateParent) { var doUpdateParent = false; if (bindingInfo.parentToChild && !bindingInfo.childToParent) { } else if (!bindingInfo.parentToChild && bindingInfo.childToParent) { doUpdateParent = true; } else if (canReflect.getValue(childObservable) === undefined) { } else if (canReflect.getValue(parentObservable) === undefined) { doUpdateParent = true; } if (doUpdateParent) { updateParent(canReflect.getValue(childObservable)); } else { if (!bindingInfo.alreadyUpdatedChild) { updateChild(canReflect.getValue(parentObservable)); } } }; var unbindUpdate = function (observable, updater) { if (observable && observable[getValueSymbol] && typeof updater === 'function') { canReflect.offValue(observable, updater, 'domUI'); } }, cleanVMName = function (name, scope) { if (name.indexOf('@') >= 0) { var filename = scope.peek('scope.filename'); var lineNumber = scope.peek('scope.lineNumber'); dev.warn((filename ? filename + ':' : '') + (lineNumber ? lineNumber + ': ' : '') + 'functions are no longer called by default so @ is unnecessary in \'' + name + '\'.'); } return name.replace(/@/g, ''); }; module.exports = { behaviors: behaviors, getBindingInfo: getBindingInfo }; }); /*can-util@3.10.18#js/log/log*/ define('can-util/js/log/log', [ 'require', 'exports', 'module', 'can-log' ], function (require, exports, module) { 'use strict'; module.exports = require('can-log'); }); /*can-component@4.0.0-pre.14#can-component*/ define('can-component', [ 'require', 'exports', 'module', 'can-component/control/control', 'can-namespace', 'can-construct', 'can-stache-bindings', 'can-view-scope', 'can-view-callbacks', 'can-view-nodelist', 'can-util/dom/data/data', 'can-util/dom/mutate/mutate', 'can-util/dom/child-nodes/child-nodes', 'can-util/dom/dispatch/dispatch', 'can-util/js/string/string', 'can-reflect', 'can-util/js/each/each', 'can-util/js/assign/assign', 'can-util/js/is-function/is-function', 'can-util/js/log/log', 'can-util/js/dev/dev', 'can-util/js/make-array/make-array', 'can-util/js/is-empty-object/is-empty-object', 'can-simple-observable', 'can-simple-map', 'can-util/dom/events/events', 'can-util/dom/events/inserted/inserted', 'can-util/dom/events/removed/removed', 'can-view-model', 'can-globals/document/document' ], function (require, exports, module) { (function (global, require, exports, module) { var ComponentControl = require('can-component/control/control'); var namespace = require('can-namespace'); var Construct = require('can-construct'); var stacheBindings = require('can-stache-bindings'); var Scope = require('can-view-scope'); var viewCallbacks = require('can-view-callbacks'); var nodeLists = require('can-view-nodelist'); var domData = require('can-util/dom/data/data'); var domMutate = require('can-util/dom/mutate/mutate'); var getChildNodes = require('can-util/dom/child-nodes/child-nodes'); var domDispatch = require('can-util/dom/dispatch/dispatch'); var string = require('can-util/js/string/string'); var canReflect = require('can-reflect'); var canEach = require('can-util/js/each/each'); var assign = require('can-util/js/assign/assign'); var isFunction = require('can-util/js/is-function/is-function'); var canLog = require('can-util/js/log/log'); var canDev = require('can-util/js/dev/dev'); var makeArray = require('can-util/js/make-array/make-array'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var SimpleObservable = require('can-simple-observable'); var SimpleMap = require('can-simple-map'); var domEvents = require('can-util/dom/events/events'); require('can-util/dom/events/inserted/inserted'); require('can-util/dom/events/removed/removed'); require('can-view-model'); var DOCUMENT = require('can-globals/document/document'); function addContext(el, tagData, insertionElementTagData) { var vm; domData.set.call(el, 'preventDataBindings', true); var teardown = stacheBindings.behaviors.viewModel(el, insertionElementTagData, function (initialData) { return vm = new SimpleObservable(initialData); }, undefined, true); if (!teardown) { return tagData; } else { return assign(assign({}, tagData), { teardown: teardown, scope: tagData.scope.add(vm) }); } } function makeInsertionTagCallback(tagName, componentTagData, shadowTagData, leakScope, getPrimaryTemplate) { var options = shadowTagData.options; return function hookupFunction(el, insertionElementTagData) { var template = getPrimaryTemplate(el) || insertionElementTagData.subtemplate, renderingLightContent = template !== insertionElementTagData.subtemplate; if (template) { delete options.tags[tagName]; var tagData; if (renderingLightContent) { if (leakScope.toLightContent) { tagData = addContext(el, { scope: insertionElementTagData.scope.cloneFromRef(), options: insertionElementTagData.options }, insertionElementTagData); } else { tagData = addContext(el, componentTagData, insertionElementTagData); } } else { tagData = addContext(el, insertionElementTagData, insertionElementTagData); } var nodeList = nodeLists.register([el], function () { if (tagData.teardown) { tagData.teardown(); } }, insertionElementTagData.parentNodeList || true, false); nodeList.expression = '<can-slot name=\'' + el.getAttribute('name') + '\'/>'; var frag = template(tagData.scope, tagData.options, nodeList); var newNodes = makeArray(getChildNodes(frag)); nodeLists.replace(nodeList, frag); nodeLists.update(nodeList, newNodes); options.tags[tagName] = hookupFunction; } }; } var Component = Construct.extend({ setup: function () { Construct.setup.apply(this, arguments); if (Component) { var self = this; if (!isEmptyObject(this.prototype.events)) { this.Control = ComponentControl.extend(this.prototype.events); } if (this.prototype.viewModel && canReflect.isConstructorLike(this.prototype.viewModel)) { canDev.warn('can-component: Assigning a DefineMap or constructor type to the viewModel property may not be what you intended. Did you mean ViewModel instead? More info: https://canjs.com/doc/can-component.prototype.ViewModel.html'); } var protoViewModel = this.prototype.viewModel || this.prototype.scope; if (protoViewModel && this.prototype.ViewModel) { throw new Error('Cannot provide both a ViewModel and a viewModel property'); } var vmName = string.capitalize(string.camelize(this.prototype.tag)) + 'VM'; if (this.prototype.ViewModel) { if (typeof this.prototype.ViewModel === 'function') { this.ViewModel = this.prototype.ViewModel; } else { canLog.warn('can-component: ' + this.prototype.tag + ' is extending the ViewModel into a can-simple-map'); this.ViewModel = SimpleMap.extend(vmName, {}, this.prototype.ViewModel); } } else { if (protoViewModel) { if (typeof protoViewModel === 'function') { if (canReflect.isObservableLike(protoViewModel.prototype) && canReflect.isMapLike(protoViewModel.prototype)) { this.ViewModel = protoViewModel; } else { this.viewModelHandler = protoViewModel; } } else { if (canReflect.isObservableLike(protoViewModel) && canReflect.isMapLike(protoViewModel)) { canLog.warn('can-component: ' + this.prototype.tag + ' is sharing a single map across all component instances'); this.viewModelInstance = protoViewModel; } else { canLog.warn('can-component: ' + this.prototype.tag + ' is extending the viewModel into a can-simple-map'); this.ViewModel = SimpleMap.extend(vmName, {}, protoViewModel); } } } else { this.ViewModel = SimpleMap.extend(vmName, {}, {}); } } if (this.prototype.template) { canLog.warn('can-component.prototype.template: is deprecated and will be removed in a future release. Use can-component.prototype.view'); this.renderer = this.prototype.template; } if (this.prototype.view) { this.renderer = this.prototype.view; } viewCallbacks.tag(this.prototype.tag, function (el, options) { new self(el, options); }); if (this.prototype.autoMount) { canEach(DOCUMENT().getElementsByTagName(this.prototype.tag), function (el) { if (!domData.get.call(el, 'viewModel')) { new self(el, { scope: new Scope(), options: {}, templates: {}, subtemplate: null, mounted: true }); } }); } } } }, { setup: function (el, componentTagData) { var component = this; var teardownFunctions = []; var initialViewModelData = {}; var callTeardownFunctions = function () { for (var i = 0, len = teardownFunctions.length; i < len; i++) { teardownFunctions[i](); } }; var setupBindings = !domData.get.call(el, 'preventDataBindings'); var viewModel, frag; var teardownBindings; if (setupBindings) { var setupFn = componentTagData.setupBindings || function (el, callback, data) { return stacheBindings.behaviors.viewModel(el, componentTagData, callback, data); }; teardownBindings = setupFn(el, function (initialViewModelData) { var ViewModel = component.constructor.ViewModel, viewModelHandler = component.constructor.viewModelHandler, viewModelInstance = component.constructor.viewModelInstance; if (viewModelHandler) { var scopeResult = viewModelHandler.call(component, initialViewModelData, componentTagData.scope, el); if (canReflect.isObservableLike(scopeResult) && canReflect.isMapLike(scopeResult)) { viewModelInstance = scopeResult; } else if (canReflect.isObservableLike(scopeResult.prototype) && canReflect.isMapLike(scopeResult.prototype)) { ViewModel = scopeResult; } else { ViewModel = SimpleMap.extend(scopeResult); } } if (ViewModel) { viewModelInstance = new component.constructor.ViewModel(initialViewModelData); } viewModel = viewModelInstance; return viewModelInstance; }, initialViewModelData); } this.viewModel = viewModel; domData.set.call(el, 'viewModel', viewModel); domData.set.call(el, 'preventDataBindings', true); var options = { helpers: {}, tags: {} }; canEach(this.helpers || {}, function (val, prop) { if (isFunction(val)) { options.helpers[prop] = val.bind(viewModel); } }); if (this.constructor.Control) { this._control = new this.constructor.Control(el, { scope: this.viewModel, viewModel: this.viewModel, destroy: callTeardownFunctions }); } else { domEvents.addEventListener.call(el, 'removed', callTeardownFunctions); } var leakScope = { toLightContent: this.leakScope === true, intoShadowContent: this.leakScope === true }; var hasShadowTemplate = !!this.constructor.renderer; var betweenTagsRenderer; var betweenTagsTagData; if (hasShadowTemplate) { var shadowTagData; if (leakScope.intoShadowContent) { shadowTagData = { scope: componentTagData.scope.add(this.viewModel), options: options }; } else { shadowTagData = { scope: new Scope(this.viewModel), options: options }; } options.tags['can-slot'] = makeInsertionTagCallback('can-slot', componentTagData, shadowTagData, leakScope, function (el) { return componentTagData.templates[el.getAttribute('name')]; }); options.tags.content = makeInsertionTagCallback('content', componentTagData, shadowTagData, leakScope, function () { return componentTagData.subtemplate; }); betweenTagsRenderer = this.constructor.renderer; betweenTagsTagData = shadowTagData; } else { var lightTemplateTagData = { scope: componentTagData.scope.add(this.viewModel, { viewModel: true }), options: options }; betweenTagsTagData = lightTemplateTagData; betweenTagsRenderer = componentTagData.subtemplate || el.ownerDocument.createDocumentFragment.bind(el.ownerDocument); } var disconnectedCallback; if (viewModel.connectedCallback) { if (componentTagData.mounted === true) { disconnectedCallback = viewModel.connectedCallback(el); } else { domEvents.addEventListener.call(el, 'inserted', function connectedHandler() { domEvents.removeEventListener.call(el, 'inserted', connectedHandler); disconnectedCallback = viewModel.connectedCallback(el); }); } } var nodeList = nodeLists.register([], function () { domDispatch.call(el, 'beforeremove', [], false); if (teardownBindings) { teardownBindings(); } if (disconnectedCallback) { disconnectedCallback(el); } }, componentTagData.parentNodeList || true, false); nodeList.expression = '<' + this.tag + '>'; teardownFunctions.push(function () { nodeLists.unregister(nodeList); }); frag = betweenTagsRenderer(betweenTagsTagData.scope, betweenTagsTagData.options, nodeList); domMutate.appendChild.call(el, frag); nodeLists.update(nodeList, getChildNodes(el)); } }); module.exports = namespace.Component = Component; }(function () { return this; }(), require, exports, module)); }); /*can-connect@2.0.0-pre.12#connect*/ define('can-connect/connect', [ 'require', 'exports', 'module', 'can-util/js/assign/assign' ], function (require, exports, module) { var assign = require('can-util/js/assign/assign'); var connect = function (behaviors, options) { behaviors = behaviors.map(function (behavior, index) { var sortedIndex = -1; if (typeof behavior === 'string') { sortedIndex = connect.order.indexOf(behavior); behavior = behaviorsMap[behavior]; } else if (behavior.isBehavior) { sortedIndex = connect.order.indexOf(behavior.behaviorName); } else { behavior = connect.behavior(behavior); } return { originalIndex: index, sortedIndex: sortedIndex, behavior: behavior }; }); behaviors.sort(function (b1, b2) { if (~b1.sortedIndex && ~b2.sortedIndex) { return b1.sortedIndex - b2.sortedIndex; } return b1.originalIndex - b2.originalIndex; }); behaviors = behaviors.map(function (b) { return b.behavior; }); var behavior = connect.base(connect.behavior('options', function () { return options; })()); behaviors.forEach(function (behave) { behavior = behave(behavior); }); if (behavior.init) { behavior.init(); } return behavior; }; connect.order = [ 'data/localstorage-cache', 'data/url', 'data/parse', 'cache-requests', 'data/combine-requests', 'constructor', 'constructor/store', 'can/map', 'can/ref', 'fall-through-cache', 'data/worker', 'real-time', 'data/callbacks-cache', 'data/callbacks', 'constructor/callbacks-once' ]; connect.behavior = function (name, behavior) { if (typeof name !== 'string') { behavior = name; name = undefined; } var behaviorMixin = function (base) { var Behavior = function () { }; Behavior.name = name; Behavior.prototype = base; var newBehavior = new Behavior(); var res = typeof behavior === 'function' ? behavior.apply(newBehavior, arguments) : behavior; assign(newBehavior, res); newBehavior.__behaviorName = name; return newBehavior; }; if (name) { behaviorMixin.behaviorName = name; behaviorsMap[name] = behaviorMixin; } behaviorMixin.isBehavior = true; return behaviorMixin; }; var behaviorsMap = {}; module.exports = connect; }); /*can-connect@2.0.0-pre.12#base/base*/ define('can-connect/base/base', [ 'require', 'exports', 'module', 'can-connect/connect' ], function (require, exports, module) { var connect = require('can-connect/connect'); module.exports = connect.behavior('base', function (baseConnection) { return { id: function (instance) { var ids = [], algebra = this.algebra; if (algebra && algebra.clauses && algebra.clauses.id) { for (var prop in algebra.clauses.id) { ids.push(instance[prop]); } } if (this.idProp && !ids.length) { ids.push(instance[this.idProp]); } if (!ids.length) { ids.push(instance.id); } return ids.length > 1 ? ids.join('@|@') : ids[0]; }, idProp: baseConnection.idProp || 'id', listSet: function (list) { return list[this.listSetProp]; }, listSetProp: '__listSet', init: function () { } }; }); }); /*can-connect@2.0.0-pre.12#can-connect*/ define('can-connect', [ 'require', 'exports', 'module', 'can-connect/connect', 'can-connect/base/base', 'can-namespace' ], function (require, exports, module) { var connect = require('can-connect/connect'); var base = require('can-connect/base/base'); var ns = require('can-namespace'); connect.base = base; module.exports = ns.connect = connect; }); /*can-connect@2.0.0-pre.12#helpers/get-items*/ define('can-connect/helpers/get-items', function (require, exports, module) { module.exports = function (data) { if (Array.isArray(data)) { return data; } else { return data.data; } }; }); /*can-set@1.3.3#src/helpers*/ define('can-set/src/helpers', [ 'require', 'exports', 'module', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-util/js/last/last' ], function (require, exports, module) { var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var last = require('can-util/js/last/last'); var IgnoreType = function () { }; var helpers; module.exports = helpers = { eachInUnique: function (a, acb, b, bcb, defaultReturn) { var bCopy = assign({}, b), res; for (var prop in a) { res = acb(a[prop], b[prop], a, b, prop); if (res !== undefined) { return res; } delete bCopy[prop]; } for (prop in bCopy) { res = bcb(undefined, b[prop], a, b, prop); if (res !== undefined) { return res; } } return defaultReturn; }, doubleLoop: function (arr, callbacks) { if (typeof callbacks === 'function') { callbacks = { iterate: callbacks }; } var i = 0; while (i < arr.length) { if (callbacks.start) { callbacks.start(arr[i]); } var j = i + 1; while (j < arr.length) { if (callbacks.iterate(arr[j], j, arr[i], i) === false) { arr.splice(j, 1); } else { j++; } } if (callbacks.end) { callbacks.end(arr[i]); } i++; } }, identityMap: function (arr) { var map = {}; each(arr, function (value) { map[value] = 1; }); return map; }, arrayUnionIntersectionDifference: function (arr1, arr2) { var map = {}; var intersection = []; var union = []; var difference = arr1.slice(0); each(arr1, function (value) { map[value] = true; union.push(value); }); each(arr2, function (value) { if (map[value]) { intersection.push(value); var index = helpers.indexOf.call(difference, value); if (index !== -1) { difference.splice(index, 1); } } else { union.push(value); } }); return { intersection: intersection, union: union, difference: difference }; }, arraySame: function (arr1, arr2) { if (arr1.length !== arr2.length) { return false; } var map = helpers.identityMap(arr1); for (var i = 0; i < arr2.length; i++) { var val = map[arr2[i]]; if (!val) { return false; } else if (val > 1) { return false; } else { map[arr2[i]]++; } } return true; }, indexOf: Array.prototype.indexOf || function (item) { for (var i = 0, thisLen = this.length; i < thisLen; i++) { if (this[i] === item) { return i; } } return -1; }, map: Array.prototype.map || function (cb) { var out = []; for (var i = 0, len = this.length; i < len; i++) { out.push(cb(this[i], i, this)); } return out; }, filter: Array.prototype.filter || function (cb) { var out = []; for (var i = 0, len = this.length; i < len; i++) { if (cb(this[i], i, this)) { out.push(this[i]); } } return out; }, ignoreType: new IgnoreType(), firstProp: function (set) { for (var prop in set) { return prop; } }, index: function (compare, items, props) { if (!items || !items.length) { return undefined; } if (compare(props, items[0]) === -1) { return 0; } else if (compare(props, last(items)) === 1) { return items.length; } var low = 0, high = items.length; while (low < high) { var mid = low + high >>> 1, item = items[mid], computed = compare(props, item); if (computed === -1) { high = mid; } else { low = mid + 1; } } return high; }, defaultSort: function (sortPropValue, item1, item2) { var parts = sortPropValue.split(' '); var sortProp = parts[0]; var item1Value = item1[sortProp]; var item2Value = item2[sortProp]; var temp; var desc = parts[1] || ''; desc = desc.toLowerCase() === 'desc'; if (desc) { temp = item1Value; item1Value = item2Value; item2Value = temp; } if (item1Value < item2Value) { return -1; } if (item1Value > item2Value) { return 1; } return 0; } }; }); /*can-set@1.3.3#src/clause*/ define('can-set/src/clause', [ 'require', 'exports', 'module', 'can-util/js/assign/assign', 'can-util/js/each/each' ], function (require, exports, module) { var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var clause = {}; module.exports = clause; clause.TYPES = [ 'where', 'order', 'paginate', 'id' ]; each(clause.TYPES, function (type) { var className = type.charAt(0).toUpperCase() + type.substr(1); clause[className] = function (compare) { assign(this, compare); }; clause[className].type = type; }); }); /*can-set@1.3.3#src/compare*/ define('can-set/src/compare', [ 'require', 'exports', 'module', 'can-set/src/helpers', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-util/js/make-array/make-array' ], function (require, exports, module) { var h = require('can-set/src/helpers'); var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var makeArray = require('can-util/js/make-array/make-array'); var compareHelpers; var loop = function (a, b, aParent, bParent, prop, compares, options) { var checks = options.checks; for (var i = 0; i < checks.length; i++) { var res = checks[i](a, b, aParent, bParent, prop, compares || {}, options); if (res !== undefined) { return res; } } return options['default']; }; var addIntersectedPropertyToResult = function (a, b, aParent, bParent, prop, compares, options) { var subsetCheck; if (!(prop in aParent)) { subsetCheck = 'subsetB'; } else if (prop in bParent) { return false; } if (!(prop in bParent)) { subsetCheck = 'subsetA'; } if (subsetCheck === 'subsetB') { options.result[prop] = b; } else { options.result[prop] = a; } return undefined; }; var addToResult = function (fn, name) { return function (a, b, aParent, bParent, prop, compares, options) { var res = fn.apply(this, arguments); if (res === true) { if (prop !== undefined && !(prop in options.result)) { options.result[prop] = a; } return true; } else { return res; } }; }; var addResultsToNewObject = function (fn, name) { return function (a, b, aParent, bParent, prop, compares, options) { var existingResult = options.result; options.result = {}; var res = fn.apply(this, arguments); if (res) { if (prop !== undefined) { existingResult[prop] = options.result; } else { assign(existingResult, options.result); } } options.result = existingResult; return res; }; }; module.exports = compareHelpers = { equal: function (a, b, aParent, bParent, prop, compares, options) { options.checks = [ compareHelpers.equalComparesType, compareHelpers.equalBasicTypes, compareHelpers.equalArrayLike, compareHelpers.equalObject ]; options['default'] = false; return loop(a, b, aParent, bParent, prop, compares, options); }, equalComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { return compareResult; } else if (compareResult && typeof compareResult === 'object') { if ('intersection' in compareResult && !('difference' in compareResult)) { var reverseResult = compares(b, a, bParent, aParent, prop, options); return 'intersection' in reverseResult && !('difference' in reverseResult); } return false; } return compareResult; } }, equalBasicTypes: function (a, b, aParent, bParent, prop, compares, options) { if (a === null || b === null) { return a === b; } if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } if (options.deep === -1) { return typeof a === 'object' || a === b; } if (typeof a !== typeof b || Array.isArray(a) !== Array.isArray(b)) { return false; } if (a === b) { return true; } }, equalArrayLike: function (a, b, aParent, bParent, prop, compares, options) { if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return false; } for (var i = 0; i < a.length; i++) { var compare = compares[i] === undefined ? compares['*'] : compares[i]; if (!loop(a[i], b[i], a, b, i, compare, options)) { return false; } } return true; } }, equalObject: function (a, b, aParent, bParent, parentProp, compares, options) { var aType = typeof a; if (aType === 'object' || aType === 'function') { var bCopy = assign({}, b); if (options.deep === false) { options.deep = -1; } for (var prop in a) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; if (!loop(a[prop], b[prop], a, b, prop, compare, options)) { return false; } delete bCopy[prop]; } for (prop in bCopy) { if (compares[prop] === undefined || !loop(undefined, b[prop], a, b, prop, compares[prop], options)) { return false; } } return true; } }, subset: function (a, b, aParent, bParent, prop, compares, options) { options.checks = [ compareHelpers.subsetComparesType, compareHelpers.equalBasicTypes, compareHelpers.equalArrayLike, compareHelpers.subsetObject ]; options.getSubsets = []; options['default'] = false; return loop(a, b, aParent, bParent, prop, compares, options); }, subsetObject: function (a, b, aParent, bParent, parentProp, compares, options) { var aType = typeof a; if (aType === 'object' || aType === 'function') { return h.eachInUnique(a, function (a, b, aParent, bParent, prop) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; if (!loop(a, b, aParent, bParent, prop, compare, options) && prop in bParent) { return false; } }, b, function (a, b, aParent, bParent, prop) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; if (!loop(a, b, aParent, bParent, prop, compare, options)) { return false; } }, true); } }, subsetComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { return compareResult; } else if (compareResult && typeof compareResult === 'object') { if (compareResult.getSubset) { if (h.indexOf.call(options.getSubsets, compareResult.getSubset) === -1) { options.getSubsets.push(compareResult.getSubset); } } if (compareResult.intersection === h.ignoreType || compareResult.difference === h.ignoreType) { return true; } if ('intersection' in compareResult && !('difference' in compareResult)) { var reverseResult = compares(b, a, bParent, aParent, prop, options); return 'intersection' in reverseResult; } return false; } return compareResult; } }, properSupersetObject: function (a, b, aParent, bParent, parentProp, compares, options) { var bType = typeof b; var hasAdditionalProp = false; if (bType === 'object' || bType === 'function') { var aCopy = assign({}, a); if (options.deep === false) { options.deep = -1; } for (var prop in b) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; var compareResult = loop(a[prop], b[prop], a, b, prop, compare, options); if (compareResult === h.ignoreType) { } else if (!(prop in a) || options.performedDifference) { hasAdditionalProp = true; } else if (!compareResult) { return false; } delete aCopy[prop]; } for (prop in aCopy) { if (compares[prop] === undefined || !loop(a[prop], undefined, a, b, prop, compares[prop], options)) { return false; } } return hasAdditionalProp; } }, properSubsetComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { return compareResult; } else if (compareResult && typeof compareResult === 'object') { if ('intersection' in compareResult && !('difference' in compareResult)) { var reverseResult = compares(b, a, bParent, aParent, prop, options); return 'intersection' in reverseResult && 'difference' in reverseResult; } return false; } return compareResult; } }, difference: function (a, b, aParent, bParent, prop, compares, options) { options.result = {}; options.performedDifference = 0; options.checks = [ compareHelpers.differenceComparesType, addToResult(compareHelpers.equalBasicTypes, 'equalBasicTypes'), addToResult(compareHelpers.equalArrayLike, 'equalArrayLike'), addToResult(compareHelpers.properSupersetObject, 'properSubsetObject') ]; options['default'] = true; var res = loop(a, b, aParent, bParent, prop, compares, options); if (res === true && options.performedDifference) { return options.result; } return res; }, differenceComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { if (compareResult === true) { options.result[prop] = a; return true; } else { return compareResult; } } else if (compareResult && typeof compareResult === 'object') { if ('difference' in compareResult) { if (compareResult.difference === h.ignoreType) { return h.ignoreType; } else if (compareResult.difference != null) { options.result[prop] = compareResult.difference; options.performedDifference++; return true; } else { return true; } } else { if (compareHelpers.equalComparesType.apply(this, arguments)) { options.performedDifference++; options.result[prop] = compareResult.union; } else { return false; } } } } }, union: function (a, b, aParent, bParent, prop, compares, options) { options.result = {}; options.performedUnion = 0; options.checks = [ compareHelpers.unionComparesType, addToResult(compareHelpers.equalBasicTypes, 'equalBasicTypes'), addToResult(compareHelpers.unionArrayLike, 'unionArrayLike'), addResultsToNewObject(compareHelpers.unionObject, 'unionObject') ]; options.getUnions = []; options['default'] = false; var res = loop(a, b, aParent, bParent, prop, compares, options); if (res === true) { return options.result; } return false; }, unionComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { if (compareResult === true) { options.result[prop] = a; return true; } else { return compareResult; } } else if (compareResult && typeof compareResult === 'object') { if (compareResult.getUnion) { if (h.indexOf.call(options.getUnions, compareResult.getUnion) === -1) { options.getUnions.push(compareResult.getUnion); } } if ('union' in compareResult) { if (compareResult.union === h.ignoreType) { return compareResult.union; } if (compareResult.union !== undefined) { options.result[prop] = compareResult.union; } options.performedUnion++; return true; } } } }, unionObject: function (a, b, aParent, bParent, prop, compares, options) { var subsetCompare = function (a, b, aParent, bParent, prop) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; if (!loop(a, b, aParent, bParent, prop, compare, options)) { var subsetCheck; if (!(prop in aParent)) { subsetCheck = 'subsetB'; } if (!(prop in bParent)) { subsetCheck = 'subsetA'; } if (subsetCheck) { if (!options.subset) { options.subset = subsetCheck; } return options.subset === subsetCheck ? undefined : false; } return false; } }; var aType = typeof a; if (aType === 'object' || aType === 'function') { return h.eachInUnique(a, subsetCompare, b, subsetCompare, true); } }, unionArrayLike: function (a, b, aParent, bParent, prop, compares, options) { if (Array.isArray(a) && Array.isArray(b)) { var combined = makeArray(a).concat(makeArray(b)); h.doubleLoop(combined, function (item, j, cur, i) { var res = !compareHelpers.equal(cur, item, aParent, bParent, undefined, compares['*'], { 'default': false }); return res; }); options.result[prop] = combined; return true; } }, count: function (a, b, aParent, bParent, prop, compares, options) { options.checks = [ compareHelpers.countComparesType, compareHelpers.equalBasicTypes, compareHelpers.equalArrayLike, compareHelpers.loopObject ]; options['default'] = false; loop(a, b, aParent, bParent, prop, compares, options); if (typeof options.count === 'number') { return options.count; } return Infinity; }, countComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { return true; } else if (compareResult && typeof compareResult === 'object') { if (typeof compareResult.count === 'number') { if (!('count' in options) || compareResult.count === options.count) { options.count = compareResult.count; } else { options.count = Infinity; } } return true; } } }, loopObject: function (a, b, aParent, bParent, prop, compares, options) { var aType = typeof a; if (aType === 'object' || aType === 'function') { each(a, function (aValue, prop) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; loop(aValue, b[prop], a, b, prop, compare, options); }); return true; } }, intersection: function (a, b, aParent, bParent, prop, compares, options) { options.result = {}; options.performedIntersection = 0; options.checks = [ compareHelpers.intersectionComparesType, addToResult(compareHelpers.equalBasicTypes, 'equalBasicTypes'), addToResult(compareHelpers.intersectionArrayLike, 'intersectionArrayLike'), addResultsToNewObject(compareHelpers.intersectionObject) ]; options['default'] = false; var res = loop(a, b, aParent, bParent, prop, compares, options); if (res === true) { return options.result; } return false; }, intersectionComparesType: function (a, b, aParent, bParent, prop, compares, options) { if (typeof compares === 'function') { var compareResult = compares(a, b, aParent, bParent, prop, options); if (typeof compareResult === 'boolean') { if (compareResult === true) { options.result[prop] = a; return true; } else { return compareResult; } } else if (compareResult && typeof compareResult === 'object') { if ('intersection' in compareResult) { if (compareResult.intersection !== undefined) { options.result[prop] = compareResult.intersection; } options.performedIntersection++; return true; } } } }, intersectionObject: function (a, b, aParent, bParent, prop, compares, options) { var subsetCompare = function (a, b, aParent, bParent, prop) { var compare = compares[prop] === undefined ? compares['*'] : compares[prop]; if (!loop(a, b, aParent, bParent, prop, compare, options)) { return addIntersectedPropertyToResult(a, b, aParent, bParent, prop, compares, options); } }; var aType = typeof a; if (aType === 'object' || aType === 'function') { return h.eachInUnique(a, subsetCompare, b, subsetCompare, true); } }, intersectionArrayLike: function (a, b, aParent, bParent, prop, compares, options) { if (Array.isArray(a) && Array.isArray(b)) { var intersection = []; each(makeArray(a), function (cur) { for (var i = 0; i < b.length; i++) { if (compareHelpers.equal(cur, b[i], aParent, bParent, undefined, compares['*'], { 'default': false })) { intersection.push(cur); break; } } }); options.result[prop] = intersection; return true; } } }; }); /*can-set@1.3.3#src/get*/ define('can-set/src/get', [ 'require', 'exports', 'module', 'can-set/src/compare', 'can-set/src/helpers', 'can-util/js/each/each' ], function (require, exports, module) { var compare = require('can-set/src/compare'); var h = require('can-set/src/helpers'); var each = require('can-util/js/each/each'); var filterData = function (data, clause, props) { return h.filter.call(data, function (item) { var isSubset = compare.subset(item, clause, undefined, undefined, undefined, props, {}); return isSubset; }); }; module.exports = { subsetData: function (a, b, bData, algebra) { var aClauseProps = algebra.getClauseProperties(a); var bClauseProps = algebra.getClauseProperties(b); var options = {}; var aData = filterData(bData, aClauseProps.where, algebra.clauses.where); if (aData.length && (aClauseProps.enabled.order || bClauseProps.enabled.order)) { options = {}; var propName = h.firstProp(aClauseProps.order), compareOrder = algebra.clauses.order[propName]; aData = aData.sort(function (aItem, bItem) { return compareOrder(a[propName], aItem, bItem); }); } if (aData.length && (aClauseProps.enabled.paginate || bClauseProps.enabled.paginate)) { options = {}; compare.subset(aClauseProps.paginate, bClauseProps.paginate, undefined, undefined, undefined, algebra.clauses.paginate, options); each(options.getSubsets, function (filter) { aData = filter(a, b, aData, algebra, options); }); } return aData; } }; }); /*can-set@1.3.3#src/set-core*/ define('can-set/src/set-core', [ 'require', 'exports', 'module', 'can-set/src/helpers', 'can-set/src/clause', 'can-set/src/compare', 'can-set/src/get', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-util/js/make-array/make-array', 'can-util/js/is-empty-object/is-empty-object' ], function (require, exports, module) { var h = require('can-set/src/helpers'); var clause = require('can-set/src/clause'); var compare = require('can-set/src/compare'); var get = require('can-set/src/get'); var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var makeArray = require('can-util/js/make-array/make-array'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); function Translate(clause, options) { if (typeof options === 'string') { var path = options; options = { fromSet: function (set, setRemainder) { return set[path] || {}; }, toSet: function (set, wheres) { set[path] = wheres; return set; } }; } this.clause = clause; assign(this, options); } var Algebra = function () { var clauses = this.clauses = { where: {}, order: {}, paginate: {}, id: {} }; this.translators = { where: new Translate('where', { fromSet: function (set, setRemainder) { return setRemainder; }, toSet: function (set, wheres) { return assign(set, wheres); } }) }; var self = this; each(arguments, function (arg) { if (arg) { if (arg instanceof Translate) { self.translators[arg.clause] = arg; } else { assign(clauses[arg.constructor.type || 'where'], arg); } } }); }; Algebra.make = function (compare, count) { if (compare instanceof Algebra) { return compare; } else { return new Algebra(compare, count); } }; assign(Algebra.prototype, { getClauseProperties: function (set, options) { options = options || {}; var setClone = assign({}, set); var clauses = this.clauses; var checkClauses = [ 'order', 'paginate', 'id' ]; var clauseProps = { enabled: { where: true, order: false, paginate: false, id: false } }; if (options.omitClauses) { checkClauses = h.arrayUnionIntersectionDifference(checkClauses, options.omitClauses).difference; } each(checkClauses, function (clauseName) { var valuesForClause = {}; var prop; for (prop in clauses[clauseName]) { if (prop in setClone) { valuesForClause[prop] = setClone[prop]; if (clauseName !== 'id') { delete setClone[prop]; } } } clauseProps[clauseName] = valuesForClause; clauseProps.enabled[clauseName] = !isEmptyObject(valuesForClause); }); clauseProps.where = options.isProperties ? setClone : this.translators.where.fromSet(set, setClone); return clauseProps; }, getDifferentClauseTypes: function (aClauses, bClauses) { var self = this; var differentTypes = []; each(clause.TYPES, function (type) { if (!self.evaluateOperator(compare.equal, aClauses[type], bClauses[type], { isProperties: true }, { isProperties: true })) { differentTypes.push(type); } }); return differentTypes; }, updateSet: function (set, clause, result, useSet) { if (result && typeof result === 'object' && useSet !== false) { if (this.translators[clause]) { set = this.translators.where.toSet(set, result); } else { set = assign(set, result); } return true; } else if (result) { return useSet === undefined ? undefined : false; } else { return false; } }, evaluateOperator: function (operator, a, b, aOptions, bOptions, evaluateOptions) { aOptions = aOptions || {}; bOptions = bOptions || {}; evaluateOptions = assign({ evaluateWhere: operator, evaluatePaginate: operator, evaluateOrder: operator, shouldEvaluatePaginate: function (aClauseProps, bClauseProps) { return aClauseProps.enabled.paginate || bClauseProps.enabled.paginate; }, shouldEvaluateOrder: function (aClauseProps, bClauseProps) { return aClauseProps.enabled.order && compare.equal(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined, {}, {}); } }, evaluateOptions || {}); var aClauseProps = this.getClauseProperties(a, aOptions), bClauseProps = this.getClauseProperties(b, bOptions), set = {}, useSet; var result = evaluateOptions.evaluateWhere(aClauseProps.where, bClauseProps.where, undefined, undefined, undefined, this.clauses.where, {}); useSet = this.updateSet(set, 'where', result, useSet); if (result && evaluateOptions.shouldEvaluatePaginate(aClauseProps, bClauseProps)) { if (evaluateOptions.shouldEvaluateOrder(aClauseProps, bClauseProps)) { result = evaluateOptions.evaluateOrder(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined, {}, {}); useSet = this.updateSet(set, 'order', result, useSet); } if (result) { result = evaluateOptions.evaluatePaginate(aClauseProps.paginate, bClauseProps.paginate, undefined, undefined, undefined, this.clauses.paginate, {}); useSet = this.updateSet(set, 'paginate', result, useSet); } } else if (result && evaluateOptions.shouldEvaluateOrder(aClauseProps, bClauseProps)) { result = operator(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined, {}, {}); useSet = this.updateSet(set, 'order', result, useSet); } return result && useSet ? set : result; }, equal: function (a, b) { return this.evaluateOperator(compare.equal, a, b); }, subset: function (a, b) { var aClauseProps = this.getClauseProperties(a); var bClauseProps = this.getClauseProperties(b); var compatibleSort = true; var result; if (bClauseProps.enabled.paginate && (aClauseProps.enabled.order || bClauseProps.enabled.order)) { compatibleSort = compare.equal(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined, {}, {}); } if (!compatibleSort) { result = false; } else { result = this.evaluateOperator(compare.subset, a, b); } return result; }, properSubset: function (a, b) { return this.subset(a, b) && !this.equal(a, b); }, difference: function (a, b) { var aClauseProps = this.getClauseProperties(a); var bClauseProps = this.getClauseProperties(b); var differentClauses = this.getDifferentClauseTypes(aClauseProps, bClauseProps); var result; switch (differentClauses.length) { case 0: { result = false; break; } case 1: { var clause = differentClauses[0]; result = compare.difference(aClauseProps[clause], bClauseProps[clause], undefined, undefined, undefined, this.clauses[clause], {}); if (this.translators[clause] && typeof result === 'object') { result = this.translators[clause].toSet({}, result); } break; } } return result; }, union: function (a, b) { return this.evaluateOperator(compare.union, a, b); }, intersection: function (a, b) { return this.evaluateOperator(compare.intersection, a, b); }, count: function (set) { return this.evaluateOperator(compare.count, set, {}); }, has: function (set, props) { var aClauseProps = this.getClauseProperties(set); var propsClauseProps = this.getClauseProperties(props, { isProperties: true }); var compatibleSort = true; var result; if ((propsClauseProps.enabled.paginate || aClauseProps.enabled.paginate) && (propsClauseProps.enabled.order || aClauseProps.enabled.order)) { compatibleSort = compare.equal(propsClauseProps.order, aClauseProps.order, undefined, undefined, undefined, {}, {}); } if (!compatibleSort) { result = false; } else { result = this.evaluateOperator(compare.subset, props, set, { isProperties: true }, undefined, { shouldEvaluatePaginate: function () { return false; } }); } return result; }, index: function (set, items, item) { var aClauseProps = this.getClauseProperties(set); var propName = h.firstProp(aClauseProps.order), compare, orderValue; if (propName) { compare = this.clauses.order[propName]; orderValue = set[propName]; return h.index(function (itemA, itemB) { return compare(orderValue, itemA, itemB); }, items, item); } propName = h.firstProp(this.clauses.id); if (propName) { compare = h.defaultSort; orderValue = propName; return h.index(function (itemA, itemB) { return compare(orderValue, itemA, itemB); }, items, item); } return; }, getSubset: function (a, b, bData) { var aClauseProps = this.getClauseProperties(a); var bClauseProps = this.getClauseProperties(b); var isSubset = this.subset(assign({}, aClauseProps.where, aClauseProps.paginate), assign({}, bClauseProps.where, bClauseProps.paginate)); if (isSubset) { return get.subsetData(a, b, bData, this); } }, getUnion: function (a, b, aItems, bItems) { var aClauseProps = this.getClauseProperties(a); var bClauseProps = this.getClauseProperties(b); var algebra = this; var options; if (this.subset(a, b)) { return bItems; } else if (this.subset(b, a)) { return aItems; } var combined; if (aClauseProps.enabled.paginate || bClauseProps.enabled.paginate) { options = {}; var isUnion = compare.union(aClauseProps.paginate, bClauseProps.paginate, undefined, undefined, undefined, this.clauses.paginate, options); if (!isUnion) { return; } else { each(options.getUnions, function (filter) { var items = filter(a, b, aItems, bItems, algebra, options); aItems = items[0]; bItems = items[1]; }); combined = aItems.concat(bItems); } } else { combined = aItems.concat(bItems); } if (combined.length && aClauseProps.enabled.order && compare.equal(aClauseProps.order, bClauseProps.order, undefined, undefined, undefined, {}, {})) { options = {}; var propName = h.firstProp(aClauseProps.order), compareOrder = algebra.clauses.order[propName]; combined = combined.sort(function (aItem, bItem) { return compareOrder(a[propName], aItem, bItem); }); } return combined; }, id: function (props) { var keys = Object.keys(this.clauses.id); if (keys.length === 1) { return props[keys[0]]; } else { var id = {}; keys.forEach(function (key) { id[key] = props[key]; }); return JSON.stringify(id); } } }); var callOnAlgebra = function (methodName, algebraArgNumber) { return function () { var args = makeArray(arguments).slice(0, algebraArgNumber); var algebra = Algebra.make(arguments[algebraArgNumber]); return algebra[methodName].apply(algebra, args); }; }; module.exports = { Algebra: Algebra, Translate: Translate, difference: callOnAlgebra('difference', 2), equal: callOnAlgebra('equal', 2), subset: callOnAlgebra('subset', 2), properSubset: callOnAlgebra('properSubset', 2), union: callOnAlgebra('union', 2), intersection: callOnAlgebra('intersection', 2), count: callOnAlgebra('count', 1), has: callOnAlgebra('has', 2), index: callOnAlgebra('index', 3), getSubset: callOnAlgebra('getSubset', 3), getUnion: callOnAlgebra('getUnion', 4) }; }); /*can-set@1.3.3#src/props*/ define('can-set/src/props', [ 'require', 'exports', 'module', 'can-set/src/helpers', 'can-set/src/clause', 'can-util/js/each/each' ], function (require, exports, module) { var h = require('can-set/src/helpers'); var clause = require('can-set/src/clause'); var each = require('can-util/js/each/each'); var within = function (value, range) { return value >= range[0] && value <= range[1]; }; var numericProperties = function (setA, setB, property1, property2) { return { sAv1: +setA[property1], sAv2: +setA[property2], sBv1: +setB[property1], sBv2: +setB[property2] }; }; var diff = function (setA, setB, property1, property2) { var numProps = numericProperties(setA, setB, property1, property2); var sAv1 = numProps.sAv1, sAv2 = numProps.sAv2, sBv1 = numProps.sBv1, sBv2 = numProps.sBv2, count = sAv2 - sAv1 + 1; var after = { difference: [ sBv2 + 1, sAv2 ], intersection: [ sAv1, sBv2 ], union: [ sBv1, sAv2 ], count: count, meta: 'after' }; var before = { difference: [ sAv1, sBv1 - 1 ], intersection: [ sBv1, sAv2 ], union: [ sAv1, sBv2 ], count: count, meta: 'before' }; if (sAv1 === sBv1 && sAv2 === sBv2) { return { intersection: [ sAv1, sAv2 ], union: [ sAv1, sAv2 ], count: count, meta: 'equal' }; } else if (sAv1 === sBv1 && sBv2 < sAv2) { return after; } else if (sAv2 === sBv2 && sBv1 > sAv1) { return before; } else if (within(sAv1, [ sBv1, sBv2 ]) && within(sAv2, [ sBv1, sBv2 ])) { return { intersection: [ sAv1, sAv2 ], union: [ sBv1, sBv2 ], count: count, meta: 'subset' }; } else if (within(sBv1, [ sAv1, sAv2 ]) && within(sBv2, [ sAv1, sAv2 ])) { return { intersection: [ sBv1, sBv2 ], difference: [ null, null ], union: [ sAv1, sAv2 ], count: count, meta: 'superset' }; } else if (sAv1 < sBv1 && within(sAv2, [ sBv1, sBv2 ])) { return before; } else if (sBv1 < sAv1 && within(sBv2, [ sAv1, sAv2 ])) { return after; } else if (sAv2 === sBv1 - 1) { return { difference: [ sAv1, sAv2 ], union: [ sAv1, sBv2 ], count: count, meta: 'disjoint-before' }; } else if (sBv2 === sAv1 - 1) { return { difference: [ sAv1, sAv2 ], union: [ sBv1, sAv2 ], count: count, meta: 'disjoint-after' }; } if (!isNaN(count)) { return { count: count, meta: 'disjoint' }; } }; var cleanUp = function (value, enumData) { if (!value) { return enumData; } if (!Array.isArray(value)) { value = [value]; } if (!value.length) { return enumData; } return value; }; var stringConvert = { '0': false, 'false': false, 'null': undefined, 'undefined': undefined }; var convertToBoolean = function (value) { if (typeof value === 'string') { return value.toLowerCase() in stringConvert ? stringConvert[value.toLowerCase()] : true; } return value; }; var props = { 'enum': function (prop, enumData) { var compares = new clause.Where({}); compares[prop] = function (vA, vB, A, B) { vA = cleanUp(vA, enumData); vB = cleanUp(vB, enumData); var data = h.arrayUnionIntersectionDifference(vA, vB); if (!data.difference.length) { delete data.difference; } each(data, function (value, prop) { if (Array.isArray(value)) { if (h.arraySame(enumData, value)) { data[prop] = undefined; } else if (value.length === 1) { data[prop] = value[0]; } } }); return data; }; return compares; }, paginate: function (propStart, propEnd, translateToStartEnd, reverseTranslate) { var compares = {}; var makeResult = function (result, index) { var res = {}; each([ 'intersection', 'difference', 'union' ], function (prop) { if (result[prop]) { var set = { start: result[prop][0], end: result[prop][1] }; res[prop] = reverseTranslate(set)[index === 0 ? propStart : propEnd]; } }); if (result.count) { res.count = result.count; } return res; }; compares[propStart] = function (vA, vB, A, B) { if (vA === undefined) { return; } var res = diff(translateToStartEnd(A), translateToStartEnd(B), 'start', 'end'); var result = makeResult(res, 0); result.getSubset = function (a, b, bItems, algebra, options) { return bItems; }; result.getUnion = function (a, b, aItems, bItems, algebra, options) { return [ aItems, bItems ]; }; return result; }; compares[propEnd] = function (vA, vB, A, B) { if (vA === undefined) { return; } var data = diff(translateToStartEnd(A), translateToStartEnd(B), 'start', 'end'); var res = makeResult(data, 1); res.getSubset = function (a, b, bItems, algebra, options) { var tA = translateToStartEnd(a); var tB = translateToStartEnd(b); var numProps = numericProperties(tA, tB, 'start', 'end'); var aStartValue = numProps.sAv1, aEndValue = numProps.sAv2; var bStartValue = numProps.sBv1; if (!('end' in tB) || !('end' in tA)) { return bItems.slice(aStartValue, aEndValue + 1); } return bItems.slice(aStartValue - bStartValue, aEndValue - bStartValue + 1); }; res.getUnion = function (a, b, aItems, bItems, algebra, options) { var tA = translateToStartEnd(a); var tB = translateToStartEnd(b); if (data.meta.indexOf('after') >= 0) { if (data.intersection) { bItems = bItems.slice(0, data.intersection[0] - +tB.start); } return [ bItems, aItems ]; } if (data.intersection) { aItems = aItems.slice(0, data.intersection[0] - +tA.start); } return [ aItems, bItems ]; }; return res; }; return new clause.Paginate(compares); }, 'boolean': function (propertyName) { var compares = new clause.Where({}); compares[propertyName] = function (propA, propB) { propA = convertToBoolean(propA); propB = convertToBoolean(propB); var notA = !propA, notB = !propB; if (propA === notB && propB === notA) { return { difference: !propB, union: undefined }; } else if (propA === undefined) { return { difference: !propB, intersection: propB, union: undefined }; } else if (propA === propB) { return true; } }; return compares; }, 'sort': function (prop, sortFunc) { if (!sortFunc) { sortFunc = h.defaultSort; } var compares = {}; compares[prop] = sortFunc; return new clause.Order(compares); }, 'id': function (prop) { var compares = {}; compares[prop] = prop; return new clause.Id(compares); } }; var assignExcept = function (d, s, props) { for (var prop in s) { if (!props[prop]) { d[prop] = s[prop]; } } return d; }; var translateToOffsetLimit = function (set, offsetProp, limitProp) { var newSet = assignExcept({}, set, { start: 1, end: 1 }); if ('start' in set) { newSet[offsetProp] = set.start; } if ('end' in set) { newSet[limitProp] = set.end - set.start + 1; } return newSet; }; var translateToStartEnd = function (set, offsetProp, limitProp) { var except = {}; except[offsetProp] = except[limitProp] = 1; var newSet = assignExcept({}, set, except); if (offsetProp in set) { newSet.start = parseInt(set[offsetProp], 10); } if (limitProp in set) { newSet.end = newSet.start + parseInt(set[limitProp]) - 1; } return newSet; }; props.offsetLimit = function (offsetProp, limitProp) { offsetProp = offsetProp || 'offset'; limitProp = limitProp || 'limit'; return props.paginate(offsetProp, limitProp, function (set) { return translateToStartEnd(set, offsetProp, limitProp); }, function (set) { return translateToOffsetLimit(set, offsetProp, limitProp); }); }; props.rangeInclusive = function (startIndexProperty, endIndexProperty) { startIndexProperty = startIndexProperty || 'start'; endIndexProperty = endIndexProperty || 'end'; return props.paginate(startIndexProperty, endIndexProperty, function (set) { var except = {}; except[startIndexProperty] = except[endIndexProperty] = 1; var newSet = assignExcept({}, set, except); if (startIndexProperty in set) { newSet.start = set[startIndexProperty]; } if (endIndexProperty in set) { newSet.end = set[endIndexProperty]; } return newSet; }, function (set) { var except = { start: 1, end: 1 }; var newSet = assignExcept({}, set, except); newSet[startIndexProperty] = set.start; newSet[endIndexProperty] = set.end; return newSet; }); }; var nestedLookup = function (obj, propNameArray) { if (obj === undefined) { return undefined; } if (propNameArray.length === 1) { return obj[propNameArray[0]]; } else { return nestedLookup(obj[propNameArray[0]], propNameArray.slice(1)); } }; props.dotNotation = function (dotProperty) { var compares = new clause.Where({}); compares[dotProperty] = function (aVal, bVal, a, b, propertyName) { if (aVal === undefined) { aVal = nestedLookup(a, propertyName.split('.')); } if (bVal === undefined) { bVal = nestedLookup(b, propertyName.split('.')); } return aVal === bVal; }; return compares; }; module.exports = props; }); /*can-set@1.3.3#src/set*/ define('can-set', [ 'require', 'exports', 'module', 'can-set/src/set-core', 'can-namespace', 'can-set/src/props', 'can-set/src/clause', 'can-set/src/helpers' ], function (require, exports, module) { var set = require('can-set/src/set-core'); var ns = require('can-namespace'); var props = require('can-set/src/props'); var clause = require('can-set/src/clause'); set.comparators = props; set.props = props; set.helpers = require('can-set/src/helpers'); set.clause = clause; module.exports = ns.set = set; }); /*can-validate-interface@1.0.0-pre.2#index*/ define('can-validate-interface', function (require, exports, module) { 'use strict'; function flatten(arrays) { return arrays.reduce(function (ret, val) { return ret.concat(val); }, []); } function makeInterfaceValidator(interfacePropArrays) { var props = flatten(interfacePropArrays); return function (base) { var missingProps = props.reduce(function (missing, prop) { return prop in base ? missing : missing.concat(prop); }, []); return missingProps.length ? { message: 'missing expected properties', related: missingProps } : undefined; }; } module.exports = makeInterfaceValidator; }); /*can-connect@2.0.0-pre.12#helpers/validate*/ define('can-connect/helpers/validate', [ 'require', 'exports', 'module', 'can-validate-interface' ], function (require, exports, module) { var makeInterfaceValidator = require('can-validate-interface'); module.exports = function (extendingBehavior, interfaces) { var validatedBehaviour = validateArgumentInterface(extendingBehavior, 0, interfaces, function (errors, baseBehavior) { throw new BehaviorInterfaceError(baseBehavior, extendingBehavior, errors); }); Object.keys(extendingBehavior).forEach(function (k) { validatedBehaviour[k] = extendingBehavior[k]; }); validatedBehaviour.__interfaces = interfaces; return validatedBehaviour; }; function validateArgumentInterface(func, argIndex, interfaces, errorHandler) { return function () { var errors = makeInterfaceValidator(interfaces)(arguments[argIndex]); if (errors && errorHandler) { errorHandler(errors, arguments[argIndex]); } return func.apply(this, arguments); }; } function BehaviorInterfaceError(baseBehavior, extendingBehavior, missingProps) { var extendingName = extendingBehavior.behaviorName || 'anonymous behavior', baseName = baseBehavior.__behaviorName || 'anonymous behavior', message = 'can-connect: Extending behavior "' + extendingName + '" found base behavior "' + baseName + '" was missing required properties: ' + JSON.stringify(missingProps.related), instance = new Error(message); if (Object.setPrototypeOf) { Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); } return instance; } BehaviorInterfaceError.prototype = Object.create(Error.prototype, { constructor: { value: Error } }); if (Object.setPrototypeOf) { Object.setPrototypeOf(BehaviorInterfaceError, Error); } else { BehaviorInterfaceError.__proto__ = Error; } }); /*can-connect@2.0.0-pre.12#cache-requests/cache-requests*/ define('can-connect/cache-requests/cache-requests', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/helpers/get-items', 'can-set', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var getItems = require('can-connect/helpers/get-items'); var canSet = require('can-set'); var forEach = [].forEach; var cacheRequestsBehaviour = connect.behavior('cache-requests', function (baseConnection) { return { getDiff: function (params, availableSets) { var minSets, self = this; forEach.call(availableSets, function (set) { var curSets; var difference = canSet.difference(params, set, self.algebra); if (typeof difference === 'object') { curSets = { needed: difference, cached: canSet.intersection(params, set, self.algebra), count: canSet.count(difference, self.algebra) }; } else if (canSet.subset(params, set, self.algebra)) { curSets = { cached: params, count: 0 }; } if (curSets) { if (!minSets || curSets.count < minSets.count) { minSets = curSets; } } }); if (!minSets) { return { needed: params }; } else { return { needed: minSets.needed, cached: minSets.cached }; } }, getUnion: function (params, diff, neededItems, cachedItems) { return { data: canSet.getUnion(diff.needed, diff.cached, getItems(neededItems), getItems(cachedItems), this.algebra) }; }, getListData: function (set) { set = set || {}; var self = this; return this.cacheConnection.getSets(set).then(function (sets) { var diff = self.getDiff(set, sets); if (!diff.needed) { return self.cacheConnection.getListData(diff.cached); } else if (!diff.cached) { return baseConnection.getListData(diff.needed).then(function (data) { return self.cacheConnection.updateListData(getItems(data), diff.needed).then(function () { return data; }); }); } else { var cachedPromise = self.cacheConnection.getListData(diff.cached); var needsPromise = baseConnection.getListData(diff.needed); var savedPromise = needsPromise.then(function (data) { return self.cacheConnection.updateListData(getItems(data), diff.needed).then(function () { return data; }); }); var combinedPromise = Promise.all([ cachedPromise, needsPromise ]).then(function (result) { var cached = result[0], needed = result[1]; return self.getUnion(set, diff, needed, cached); }); return Promise.all([ combinedPromise, savedPromise ]).then(function (data) { return data[0]; }); } }); } }; }); module.exports = cacheRequestsBehaviour; var validate = require('can-connect/helpers/validate'); module.exports = validate(cacheRequestsBehaviour, [ 'getListData', 'cacheConnection' ]); }); /*can-connect@2.0.0-pre.12#helpers/weak-reference-map*/ define('can-connect/helpers/weak-reference-map', [ 'require', 'exports', 'module', 'can-util/js/assign/assign' ], function (require, exports, module) { var assign = require('can-util/js/assign/assign'); var WeakReferenceMap = function () { this.set = {}; }; assign(WeakReferenceMap.prototype, { has: function (key) { return !!this.set[key]; }, addReference: function (key, item, referenceCount) { if (typeof key === 'undefined') { throw new Error('can-connect: You must provide a key to store a value in a WeakReferenceMap'); } var data = this.set[key]; if (!data) { data = this.set[key] = { item: item, referenceCount: 0, key: key }; } data.referenceCount += referenceCount || 1; }, referenceCount: function (key) { var data = this.set[key]; if (data) { return data.referenceCount; } }, deleteReference: function (key) { var data = this.set[key]; if (data) { data.referenceCount--; if (data.referenceCount === 0) { delete this.set[key]; } } }, get: function (key) { var data = this.set[key]; if (data) { return data.item; } }, forEach: function (cb) { for (var id in this.set) { cb(this.set[id].item, id); } } }); module.exports = WeakReferenceMap; }); /*can-connect@2.0.0-pre.12#helpers/overwrite*/ define('can-connect/helpers/overwrite', function (require, exports, module) { module.exports = function (d, s, id) { for (var prop in d) { if (d.hasOwnProperty(prop) && !(prop.substr(0, 2) === '__') && prop !== id && !(prop in s)) { delete d[prop]; } } for (prop in s) { d[prop] = s[prop]; } return d; }; }); /*can-connect@2.0.0-pre.12#helpers/id-merge*/ define('can-connect/helpers/id-merge', function (require, exports, module) { var map = [].map; module.exports = function (list, update, id, make) { var listIndex = 0, updateIndex = 0; while (listIndex < list.length && updateIndex < update.length) { var listItem = list[listIndex], updateItem = update[updateIndex], lID = id(listItem), uID = id(updateItem); if (id(listItem) === id(updateItem)) { listIndex++; updateIndex++; continue; } if (updateIndex + 1 < update.length && id(update[updateIndex + 1]) === lID) { list.splice(listIndex, 0, make(update[updateIndex])); listIndex++; updateIndex++; continue; } else if (listIndex + 1 < list.length && id(list[listIndex + 1]) === uID) { list.splice(listIndex, 1); listIndex++; updateIndex++; continue; } else { list.splice.apply(list, [ listIndex, list.length - listIndex ].concat(map.call(update.slice(updateIndex), make))); return list; } } if (updateIndex === update.length && listIndex === list.length) { return; } list.splice.apply(list, [ listIndex, list.length - listIndex ].concat(map.call(update.slice(updateIndex), make))); return; }; }); /*can-connect@2.0.0-pre.12#constructor/constructor*/ define('can-connect/constructor/constructor', [ 'require', 'exports', 'module', 'can-util/js/make-array/make-array', 'can-util/js/assign/assign', 'can-connect', 'can-connect/helpers/weak-reference-map', 'can-connect/helpers/overwrite', 'can-connect/helpers/id-merge' ], function (require, exports, module) { var makeArray = require('can-util/js/make-array/make-array'); var assign = require('can-util/js/assign/assign'); var connect = require('can-connect'); var WeakReferenceMap = require('can-connect/helpers/weak-reference-map'); var overwrite = require('can-connect/helpers/overwrite'); var idMerge = require('can-connect/helpers/id-merge'); module.exports = connect.behavior('constructor', function (baseConnection) { var behavior = { cidStore: new WeakReferenceMap(), _cid: 0, get: function (params) { var self = this; return this.getData(params).then(function (data) { return self.hydrateInstance(data); }); }, getList: function (set) { set = set || {}; var self = this; return this.getListData(set).then(function (data) { return self.hydrateList(data, set); }); }, hydrateList: function (listData, set) { if (Array.isArray(listData)) { listData = { data: listData }; } var arr = []; for (var i = 0; i < listData.data.length; i++) { arr.push(this.hydrateInstance(listData.data[i])); } listData.data = arr; if (this.list) { return this.list(listData, set); } else { var list = listData.data.slice(0); list[this.listSetProp || '__listSet'] = set; copyMetadata(listData, list); return list; } }, hydrateInstance: function (props) { if (this.instance) { return this.instance(props); } else { return assign({}, props); } }, save: function (instance) { var serialized = this.serializeInstance(instance); var id = this.id(instance); var self = this; if (id === undefined) { var cid = this._cid++; this.cidStore.addReference(cid, instance); return this.createData(serialized, cid).then(function (data) { if (data !== undefined) { self.createdInstance(instance, data); } self.cidStore.deleteReference(cid, instance); return instance; }); } else { return this.updateData(serialized).then(function (data) { if (data !== undefined) { self.updatedInstance(instance, data); } return instance; }); } }, destroy: function (instance) { var serialized = this.serializeInstance(instance), self = this; return this.destroyData(serialized).then(function (data) { if (data !== undefined) { self.destroyedInstance(instance, data); } return instance; }); }, createdInstance: function (instance, props) { assign(instance, props); }, updatedInstance: function (instance, data) { overwrite(instance, data, this.idProp); }, updatedList: function (list, listData, set) { var instanceList = []; for (var i = 0; i < listData.data.length; i++) { instanceList.push(this.hydrateInstance(listData.data[i])); } idMerge(list, instanceList, this.id.bind(this), this.hydrateInstance.bind(this)); copyMetadata(listData, list); }, destroyedInstance: function (instance, data) { overwrite(instance, data, this.idProp); }, serializeInstance: function (instance) { return assign({}, instance); }, serializeList: function (list) { var self = this; return makeArray(list).map(function (instance) { return self.serializeInstance(instance); }); }, isNew: function (instance) { var id = this.id(instance); return !(id || id === 0); } }; return behavior; }); function copyMetadata(listData, list) { for (var prop in listData) { if (prop !== 'data') { if (typeof list.set === 'function') { list.set(prop, listData[prop]); } else if (typeof list.attr === 'function') { list.attr(prop, listData[prop]); } else { list[prop] = listData[prop]; } } } } }); /*can-connect@2.0.0-pre.12#helpers/sorted-set-json*/ define('can-connect/helpers/sorted-set-json', function (require, exports, module) { var forEach = [].forEach; var keys = Object.keys; module.exports = function (set) { if (set == null) { return set; } else { var sorted = {}; forEach.call(keys(set).sort(), function (prop) { sorted[prop] = set[prop]; }); return JSON.stringify(sorted); } }; }); /*can-connect@2.0.0-pre.12#constructor/callbacks-once/callbacks-once*/ define('can-connect/constructor/callbacks-once/callbacks-once', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/helpers/sorted-set-json', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var sortedSetJSON = require('can-connect/helpers/sorted-set-json'); var forEach = [].forEach; var callbacks = [ 'createdInstance', 'updatedInstance', 'destroyedInstance' ]; var callbacksOnceBehavior = connect.behavior('constructor/callbacks-once', function (baseConnection) { var behavior = {}; forEach.call(callbacks, function (name) { behavior[name] = function (instance, data) { var lastSerialized = this.getInstanceMetaData(instance, 'last-data-' + name); var serialize = sortedSetJSON(data); if (lastSerialized !== serialize) { var result = baseConnection[name].apply(this, arguments); this.addInstanceMetaData(instance, 'last-data-' + name, serialize); return result; } }; }); return behavior; }); module.exports = callbacksOnceBehavior; var validate = require('can-connect/helpers/validate'); module.exports = validate(callbacksOnceBehavior, callbacks); }); /*can-connect@2.0.0-pre.12#helpers/weak-reference-set*/ define('can-connect/helpers/weak-reference-set', [ 'require', 'exports', 'module', 'can-util/js/assign/assign' ], function (require, exports, module) { var assign = require('can-util/js/assign/assign'); var WeakReferenceSet = function () { this.set = []; }; assign(WeakReferenceSet.prototype, { has: function (item) { return this._getIndex(item) !== -1; }, addReference: function (item, referenceCount) { var index = this._getIndex(item); var data = this.set[index]; if (!data) { data = { item: item, referenceCount: 0 }; this.set.push(data); } data.referenceCount += referenceCount || 1; }, deleteReference: function (item) { var index = this._getIndex(item); var data = this.set[index]; if (data) { data.referenceCount--; if (data.referenceCount === 0) { this.set.splice(index, 1); } } }, delete: function (item) { var index = this._getIndex(item); if (index !== -1) { this.set.splice(index, 1); } }, get: function (item) { var data = this.set[this._getIndex(item)]; if (data) { return data.item; } }, referenceCount: function (item) { var data = this.set[this._getIndex(item)]; if (data) { return data.referenceCount; } }, _getIndex: function (item) { var index; this.set.every(function (data, i) { if (data.item === item) { index = i; return false; } }); return index !== undefined ? index : -1; }, forEach: function (cb) { return this.set.forEach(cb); } }); module.exports = WeakReferenceSet; }); /*can-connect@2.0.0-pre.12#constructor/store/store*/ define('can-connect/constructor/store/store', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/helpers/weak-reference-map', 'can-connect/helpers/weak-reference-set', 'can-connect/helpers/sorted-set-json', 'can-event-queue/map/legacy/legacy', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var WeakReferenceMap = require('can-connect/helpers/weak-reference-map'); var WeakReferenceSet = require('can-connect/helpers/weak-reference-set'); var sortedSetJSON = require('can-connect/helpers/sorted-set-json'); var eventQueue = require('can-event-queue/map/legacy/legacy'); var pendingRequests = 0; var noRequestsTimer = null; var requests = { increment: function (connection) { pendingRequests++; clearTimeout(noRequestsTimer); }, decrement: function (connection) { pendingRequests--; if (pendingRequests === 0) { noRequestsTimer = setTimeout(function () { requests.dispatch('end'); }, 10); } }, count: function () { return pendingRequests; } }; eventQueue(requests); var constructorStore = connect.behavior('constructor/store', function (baseConnection) { var behavior = { instanceStore: new WeakReferenceMap(), newInstanceStore: new WeakReferenceSet(), listStore: new WeakReferenceMap(), _requestInstances: {}, _requestLists: {}, _finishedRequest: function () { var id; requests.decrement(this); if (requests.count() === 0) { for (id in this._requestInstances) { this.instanceStore.deleteReference(id); } this._requestInstances = {}; for (id in this._requestLists) { this.listStore.deleteReference(id); } this._requestLists = {}; } }, addInstanceReference: function (instance, id) { var ID = id || this.id(instance); if (ID === undefined) { this.newInstanceStore.addReference(instance); } else { this.instanceStore.addReference(ID, instance); } }, createdInstance: function (instance, props) { baseConnection.createdInstance.apply(this, arguments); this.moveCreatedInstanceToInstanceStore(instance); }, moveCreatedInstanceToInstanceStore: function (instance) { var ID = this.id(instance); if (this.newInstanceStore.has(instance) && ID !== undefined) { var referenceCount = this.newInstanceStore.referenceCount(instance); this.newInstanceStore.delete(instance); this.instanceStore.addReference(ID, instance, referenceCount); } }, addInstanceMetaData: function (instance, name, value) { var data = this.instanceStore.set[this.id(instance)]; if (data) { data[name] = value; } }, getInstanceMetaData: function (instance, name) { var data = this.instanceStore.set[this.id(instance)]; if (data) { return data[name]; } }, deleteInstanceMetaData: function (instance, name) { var data = this.instanceStore.set[this.id(instance)]; delete data[name]; }, deleteInstanceReference: function (instance) { var ID = this.id(instance); if (ID === undefined) { this.newInstanceStore.deleteReference(instance); } else { this.instanceStore.deleteReference(this.id(instance), instance); } }, addListReference: function (list, set) { var id = sortedSetJSON(set || this.listSet(list)); if (id) { this.listStore.addReference(id, list); } }, deleteListReference: function (list, set) { var id = sortedSetJSON(set || this.listSet(list)); if (id) { this.listStore.deleteReference(id, list); } }, hydratedInstance: function (instance) { if (requests.count() > 0) { var id = this.id(instance); if (!this._requestInstances[id]) { this.addInstanceReference(instance); this._requestInstances[id] = instance; } } }, hydrateInstance: function (props) { var id = this.id(props); if ((id || id === 0) && this.instanceStore.has(id)) { var storeInstance = this.instanceStore.get(id); this.updatedInstance(storeInstance, props); return storeInstance; } var instance = baseConnection.hydrateInstance.call(this, props); this.hydratedInstance(instance); return instance; }, hydratedList: function (list, set) { if (requests.count() > 0) { var id = sortedSetJSON(set || this.listSet(list)); if (id) { if (!this._requestLists[id]) { this.addListReference(list, set); this._requestLists[id] = list; } } } }, hydrateList: function (listData, set) { set = set || this.listSet(listData); var id = sortedSetJSON(set); if (id && this.listStore.has(id)) { var storeList = this.listStore.get(id); this.updatedList(storeList, listData, set); return storeList; } var list = baseConnection.hydrateList.call(this, listData, set); this.hydratedList(list, set); return list; }, getList: function (listSet) { var self = this; requests.increment(this); var promise = baseConnection.getList.call(this, listSet); promise.then(function (instances) { self._finishedRequest(); }, function () { self._finishedRequest(); }); return promise; }, get: function (params) { var self = this; requests.increment(this); var promise = baseConnection.get.call(this, params); promise.then(function (instance) { self._finishedRequest(); }, function () { self._finishedRequest(); }); return promise; }, save: function (instance) { var self = this; requests.increment(this); var updating = !this.isNew(instance); if (updating) { this.addInstanceReference(instance); } var promise = baseConnection.save.call(this, instance); promise.then(function (instances) { if (updating) { self.deleteInstanceReference(instance); } self._finishedRequest(); }, function () { self._finishedRequest(); }); return promise; }, destroy: function (instance) { var self = this; this.addInstanceReference(instance); requests.increment(this); var promise = baseConnection.destroy.call(this, instance); promise.then(function (instance) { self._finishedRequest(); self.deleteInstanceReference(instance); }, function () { self._finishedRequest(); }); return promise; } }; return behavior; }); constructorStore.requests = requests; module.exports = constructorStore; var validate = require('can-connect/helpers/validate'); module.exports = validate(constructorStore, [ 'hydrateInstance', 'hydrateList', 'getList', 'get', 'save', 'destroy' ]); }); /*can-connect@2.0.0-pre.12#data/callbacks/callbacks*/ define('can-connect/data/callbacks/callbacks', [ 'require', 'exports', 'module', 'can-connect', 'can-util/js/each/each', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var each = require('can-util/js/each/each'); var pairs = { getListData: 'gotListData', createData: 'createdData', updateData: 'updatedData', destroyData: 'destroyedData' }; var dataCallbackBehavior = connect.behavior('data/callbacks', function (baseConnection) { var behavior = {}; each(pairs, function (callbackName, name) { behavior[name] = function (params, cid) { var self = this; return baseConnection[name].call(this, params).then(function (data) { if (self[callbackName]) { return self[callbackName].call(self, data, params, cid); } else { return data; } }); }; }); return behavior; }); module.exports = dataCallbackBehavior; var validate = require('can-connect/helpers/validate'); module.exports = validate(dataCallbackBehavior, [ 'getListData', 'createData', 'updateData', 'destroyData' ]); }); /*can-connect@2.0.0-pre.12#data/callbacks-cache/callbacks-cache*/ define('can-connect/data/callbacks-cache/callbacks-cache', [ 'require', 'exports', 'module', 'can-connect', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var pairs = { createdData: 'createData', updatedData: 'updateData', destroyedData: 'destroyData' }; var callbackCache = connect.behavior('data/callbacks-cache', function (baseConnection) { var behavior = {}; each(pairs, function (crudMethod, dataCallback) { behavior[dataCallback] = function (data, params, cid) { this.cacheConnection[crudMethod](assign(assign({}, params), data)); if (baseConnection[dataCallback]) { return baseConnection[dataCallback].call(this, data, params, cid); } else { return data; } }; }); return behavior; }); module.exports = callbackCache; var validate = require('can-connect/helpers/validate'); module.exports = validate(callbackCache, []); }); /*can-connect@2.0.0-pre.12#helpers/deferred*/ define('can-connect/helpers/deferred', function (require, exports, module) { module.exports = function () { var def = {}; def.promise = new Promise(function (resolve, reject) { def.resolve = resolve; def.reject = reject; }); return def; }; }); /*can-connect@2.0.0-pre.12#data/combine-requests/combine-requests*/ define('can-connect/data/combine-requests/combine-requests', [ 'require', 'exports', 'module', 'can-connect', 'can-set', 'can-connect/helpers/get-items', 'can-util/js/deep-assign/deep-assign', 'can-connect/helpers/deferred', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var canSet = require('can-set'); var getItems = require('can-connect/helpers/get-items'); var deepAssign = require('can-util/js/deep-assign/deep-assign'); var makeDeferred = require('can-connect/helpers/deferred'); var forEach = [].forEach; var combineRequests = connect.behavior('data/combine-requests', function (baseConnection) { var pendingRequests; return { unionPendingRequests: function (pendingRequests) { var self = this; pendingRequests.sort(function (pReq1, pReq2) { if (canSet.subset(pReq1.set, pReq2.set, self.algebra)) { return 1; } else if (canSet.subset(pReq2.set, pReq1.set, self.algebra)) { return -1; } else { return 0; } }); var combineData = []; var current; doubleLoop(pendingRequests, { start: function (pendingRequest) { current = { set: pendingRequest.set, pendingRequests: [pendingRequest] }; combineData.push(current); }, iterate: function (pendingRequest) { var combined = canSet.union(current.set, pendingRequest.set, self.algebra); if (combined) { current.set = combined; current.pendingRequests.push(pendingRequest); return true; } } }); return Promise.resolve(combineData); }, time: 1, getListData: function (set) { set = set || {}; var self = this; if (!pendingRequests) { pendingRequests = []; setTimeout(function () { var combineDataPromise = self.unionPendingRequests(pendingRequests); pendingRequests = null; combineDataPromise.then(function (combinedData) { forEach.call(combinedData, function (combined) { var combinedSet = deepAssign({}, combined.set); baseConnection.getListData(combinedSet).then(function (data) { if (combined.pendingRequests.length === 1) { combined.pendingRequests[0].deferred.resolve(data); } else { forEach.call(combined.pendingRequests, function (pending) { pending.deferred.resolve({ data: canSet.getSubset(pending.set, combined.set, getItems(data), self.algebra) }); }); } }, function (err) { if (combined.pendingRequests.length === 1) { combined.pendingRequests[0].deferred.reject(err); } else { forEach.call(combined.pendingRequests, function (pending) { pending.deferred.reject(err); }); } }); }); }); }, this.time || 1); } var deferred = makeDeferred(); pendingRequests.push({ deferred: deferred, set: set }); return deferred.promise; } }; }); module.exports = combineRequests; var validate = require('can-connect/helpers/validate'); module.exports = validate(combineRequests, ['getListData']); var doubleLoop = function (arr, callbacks) { var i = 0; while (i < arr.length) { callbacks.start(arr[i]); var j = i + 1; while (j < arr.length) { if (callbacks.iterate(arr[j]) === true) { arr.splice(j, 1); } else { j++; } } i++; } }; }); /*can-connect@2.0.0-pre.12#helpers/set-add*/ define('can-connect/helpers/set-add', [ 'require', 'exports', 'module', 'can-set' ], function (require, exports, module) { var canSet = require('can-set'); module.exports = function (connection, setItems, items, item, algebra) { var index = canSet.index(setItems, items, item, algebra); if (index === undefined) { index = items.length; } var copy = items.slice(0); copy.splice(index, 0, item); return copy; }; }); /*can-connect@2.0.0-pre.12#helpers/get-index-by-id*/ define('can-connect/helpers/get-index-by-id', function (require, exports, module) { module.exports = function (connection, props, items) { var id = connection.id(props); for (var i = 0; i < items.length; i++) { var connId = connection.id(items[i]); if (id == connId) { return i; } } return -1; }; }); /*can-connect@2.0.0-pre.12#data/localstorage-cache/localstorage-cache*/ define('can-connect/data/localstorage-cache/localstorage-cache', [ 'require', 'exports', 'module', 'can-connect/helpers/get-items', 'can-connect', 'can-connect/helpers/sorted-set-json', 'can-set', 'can-connect/helpers/set-add', 'can-connect/helpers/get-index-by-id', 'can-util/js/assign/assign', 'can-connect/helpers/overwrite' ], function (require, exports, module) { var getItems = require('can-connect/helpers/get-items'); var connect = require('can-connect'); var sortedSetJSON = require('can-connect/helpers/sorted-set-json'); var canSet = require('can-set'); var forEach = [].forEach; var map = [].map; var setAdd = require('can-connect/helpers/set-add'); var indexOf = require('can-connect/helpers/get-index-by-id'); var assign = require('can-util/js/assign/assign'); var overwrite = require('can-connect/helpers/overwrite'); module.exports = connect.behavior('data/localstorage-cache', function (baseConnection) { var behavior = { _instances: {}, getSetData: function () { var sets = {}; var self = this; forEach.call(JSON.parse(localStorage.getItem(this.name + '-sets')) || [], function (set) { var setKey = sortedSetJSON(set); if (localStorage.getItem(self.name + '/set/' + setKey)) { sets[setKey] = { set: set, setKey: setKey }; } }); return sets; }, _getSets: function (setData) { var sets = []; setData = setData || this.getSetData(); for (var setKey in setData) { sets.push(JSON.parse(setKey)); } return sets; }, getInstance: function (id) { var res = localStorage.getItem(this.name + '/instance/' + id); if (res) { return JSON.parse(res); } }, updateInstance: function (props) { var id = this.id(props); var instance = this.getInstance(id); if (!instance) { instance = props; } else { overwrite(instance, props, this.idProp); } localStorage.setItem(this.name + '/instance/' + id, JSON.stringify(instance)); return instance; }, getInstances: function (ids) { var self = this; return map.call(ids, function (id) { return self.getInstance(id); }); }, removeSet: function (setKey) { var sets = this.getSetData(); localStorage.removeItem(this.name + '/set/' + setKey); delete sets[setKey]; }, updateSets: function (sets) { var setData = this._getSets(sets); localStorage.setItem(this.name + '-sets', JSON.stringify(setData)); }, updateSet: function (setDatum, items, newSet) { var newSetKey = newSet ? sortedSetJSON(newSet) : setDatum.setKey; if (newSet) { if (newSetKey !== setDatum.setKey) { var sets = this.getSetData(); localStorage.removeItem(this.name + '/set/' + setDatum.setKey); delete sets[setDatum.setKey]; sets[newSetKey] = { setKey: newSetKey, set: newSet }; this.updateSets(sets); } } setDatum.items = items; var self = this; var ids = map.call(items, function (item) { var id = self.id(item); localStorage.setItem(self.name + '/instance/' + id, JSON.stringify(item)); return id; }); localStorage.setItem(this.name + '/set/' + newSetKey, JSON.stringify(ids)); }, addSet: function (set, data) { var items = getItems(data); var sets = this.getSetData(); var setKey = sortedSetJSON(set); sets[setKey] = { setKey: setKey, items: items, set: set }; var self = this; var ids = map.call(items, function (item) { var id = self.id(item); localStorage.setItem(self.name + '/instance/' + id, JSON.stringify(item)); return id; }); localStorage.setItem(this.name + '/set/' + setKey, JSON.stringify(ids)); this.updateSets(sets); }, _eachSet: function (cb) { var sets = this.getSetData(); var self = this; var loop = function (setDatum, setKey) { return cb.call(self, setDatum, setKey, function () { if (!('items' in setDatum)) { var ids = JSON.parse(localStorage.getItem(self.name + '/set/' + setKey)); setDatum.items = self.getInstances(ids); } return setDatum.items; }); }; for (var setKey in sets) { var setDatum = sets[setKey]; var result = loop(setDatum, setKey); if (result !== undefined) { return result; } } }, clear: function () { var sets = this.getSetData(); for (var setKey in sets) { localStorage.removeItem(this.name + '/set/' + setKey); } localStorage.removeItem(this.name + '-sets'); var keys = []; for (var i = 0, len = localStorage.length; i < len; ++i) { if (localStorage.key(i).indexOf(this.name + '/instance/') === 0) { keys.push(localStorage.key(i)); } } forEach.call(keys, function (key) { localStorage.removeItem(key); }); this._instances = {}; }, getSets: function () { return Promise.resolve(this._getSets()); }, getListData: function (set) { set = set || {}; var listData = this.getListDataSync(set); if (listData) { return Promise.resolve(listData); } return Promise.reject({ message: 'no data', error: 404 }); }, getListDataSync: function (set) { var sets = this._getSets(); for (var i = 0; i < sets.length; i++) { var checkSet = sets[i]; if (canSet.subset(set, checkSet, this.algebra)) { var items = canSet.getSubset(set, checkSet, this.__getListData(checkSet), this.algebra); return { data: items }; } } }, __getListData: function (set) { var setKey = sortedSetJSON(set); var setDatum = this.getSetData()[setKey]; if (setDatum) { var localData = localStorage.getItem(this.name + '/set/' + setKey); if (localData) { return this.getInstances(JSON.parse(localData)); } } }, getData: function (params) { var id = this.id(params); var res = localStorage.getItem(this.name + '/instance/' + id); if (res) { return Promise.resolve(JSON.parse(res)); } else { return Promise.reject({ message: 'no data', error: 404 }); } }, updateListData: function (data, set) { set = set || {}; var items = getItems(data); var sets = this.getSetData(); var self = this; for (var setKey in sets) { var setDatum = sets[setKey]; var union = canSet.union(setDatum.set, set, this.algebra); if (union) { return this.getListData(setDatum.set).then(function (setData) { self.updateSet(setDatum, canSet.getUnion(setDatum.set, set, getItems(setData), items, this.algebra), union); }); } } this.addSet(set, data); return Promise.resolve(); }, createData: function (props) { var self = this; var instance = this.updateInstance(props); this._eachSet(function (setDatum, setKey, getItems) { if (canSet.has(setDatum.set, instance, this.algebra)) { self.updateSet(setDatum, setAdd(self, setDatum.set, getItems(), instance, self.algebra), setDatum.set); } }); return Promise.resolve(assign({}, instance)); }, updateData: function (props) { var self = this; var instance = this.updateInstance(props); this._eachSet(function (setDatum, setKey, getItems) { var items = getItems(); var index = indexOf(self, instance, items); if (canSet.has(setDatum.set, instance, this.algebra)) { if (index === -1) { self.updateSet(setDatum, setAdd(self, setDatum.set, getItems(), instance, self.algebra)); } else { items.splice(index, 1, instance); self.updateSet(setDatum, items); } } else if (index !== -1) { items.splice(index, 1); self.updateSet(setDatum, items); } }); return Promise.resolve(assign({}, instance)); }, destroyData: function (props) { var self = this; var instance = this.updateInstance(props); this._eachSet(function (setDatum, setKey, getItems) { var items = getItems(); var index = indexOf(self, instance, items); if (index !== -1) { items.splice(index, 1); self.updateSet(setDatum, items); } }); var id = this.id(instance); localStorage.removeItem(this.name + '/instance/' + id); return Promise.resolve(assign({}, instance)); } }; return behavior; }); }); /*can-connect@2.0.0-pre.12#helpers/clone-data*/ define('can-connect/helpers/clone-data', [ 'require', 'exports', 'module', 'can-util/js/deep-assign/deep-assign' ], function (require, exports, module) { var deepAssign = require('can-util/js/deep-assign/deep-assign'); module.exports = function (data) { return Array.isArray(data) ? data.slice(0) : deepAssign({}, data); }; }); /*can-connect@2.0.0-pre.12#data/memory-cache/memory-cache*/ define('can-connect/data/memory-cache/memory-cache', [ 'require', 'exports', 'module', 'can-connect/helpers/get-items', 'can-connect', 'can-connect/helpers/sorted-set-json', 'can-set', 'can-connect/helpers/overwrite', 'can-connect/helpers/set-add', 'can-connect/helpers/get-index-by-id', 'can-util/js/assign/assign', 'can-connect/helpers/clone-data' ], function (require, exports, module) { var getItems = require('can-connect/helpers/get-items'); var connect = require('can-connect'); var sortedSetJSON = require('can-connect/helpers/sorted-set-json'); var canSet = require('can-set'); var overwrite = require('can-connect/helpers/overwrite'); var setAdd = require('can-connect/helpers/set-add'); var indexOf = require('can-connect/helpers/get-index-by-id'); var assign = require('can-util/js/assign/assign'); var cloneData = require('can-connect/helpers/clone-data'); module.exports = connect.behavior('data/memory-cache', function (baseConnection) { var behavior = { _sets: {}, getSetData: function () { return this._sets; }, __getListData: function (set) { var setsData = this.getSetData(); var setData = setsData[sortedSetJSON(set)]; if (setData) { return setData.items; } }, _instances: {}, getInstance: function (id) { return this._instances[id]; }, removeSet: function (setKey, noUpdate) { var sets = this.getSetData(); delete sets[setKey]; if (noUpdate !== true) { this.updateSets(); } }, updateSets: function () { }, updateInstance: function (props) { var id = this.id(props); if (!(id in this._instances)) { this._instances[id] = props; } else { overwrite(this._instances[id], props, this.idProp); } return this._instances[id]; }, updateSet: function (setDatum, items, newSet) { var newSetKey = newSet ? sortedSetJSON(newSet) : setDatum.setKey; if (newSet) { if (newSetKey !== setDatum.setKey) { var sets = this.getSetData(); var oldSetKey = setDatum.setKey; sets[newSetKey] = setDatum; setDatum.setKey = newSetKey; setDatum.set = assign({}, newSet); this.removeSet(oldSetKey); } } setDatum.items = items; var self = this; items.forEach(function (item) { self.updateInstance(item); }); }, addSet: function (set, data) { var items = getItems(data); var sets = this.getSetData(); var setKey = sortedSetJSON(set); sets[setKey] = { setKey: setKey, items: items, set: assign({}, set) }; var self = this; items.forEach(function (item) { self.updateInstance(item); }); this.updateSets(); }, _eachSet: function (cb) { var sets = this.getSetData(); var self = this; var loop = function (setDatum, setKey) { return cb.call(self, setDatum, setKey, function () { return setDatum.items; }); }; for (var setKey in sets) { var setDatum = sets[setKey]; var result = loop(setDatum, setKey); if (result !== undefined) { return result; } } }, _getSets: function () { var sets = [], setsData = this.getSetData(); for (var prop in setsData) { sets.push(setsData[prop].set); } return sets; }, getSets: function () { return Promise.resolve(this._getSets()); }, clear: function () { this._instances = {}; this._sets = {}; }, getListData: function (set) { set = set || {}; var listData = this.getListDataSync(set); if (listData) { return Promise.resolve(listData); } return Promise.reject({ message: 'no data', error: 404 }); }, getListDataSync: function (set) { var sets = this._getSets(); for (var i = 0; i < sets.length; i++) { var checkSet = sets[i]; if (canSet.subset(set, checkSet, this.algebra)) { var source = this.__getListData(checkSet); var items = canSet.getSubset(set, checkSet, source, this.algebra); return { data: items, count: source.length }; } } }, _getListData: function (set) { return this.getListDataSync(set); }, updateListData: function (data, set) { set = set || {}; var clonedData = cloneData(data); var items = getItems(clonedData); var sets = this.getSetData(); var self = this; for (var setKey in sets) { var setDatum = sets[setKey]; var union = canSet.union(setDatum.set, set, this.algebra); if (union) { var getSet = assign({}, setDatum.set); return this.getListData(getSet).then(function (setData) { self.updateSet(setDatum, canSet.getUnion(getSet, set, getItems(setData), items, self.algebra), union); }); } } this.addSet(set, clonedData); return Promise.resolve(); }, getData: function (params) { var id = this.id(params); var res = this.getInstance(id); if (res) { return Promise.resolve(res); } else { return Promise.reject({ message: 'no data', error: 404 }); } }, createData: function (props) { var self = this; var instance = this.updateInstance(props); this._eachSet(function (setDatum, setKey, getItems) { if (canSet.has(setDatum.set, instance, this.algebra)) { self.updateSet(setDatum, setAdd(self, setDatum.set, getItems(), instance, self.algebra), setDatum.set); } }); return Promise.resolve(assign({}, instance)); }, updateData: function (props) { var self = this; var instance = this.updateInstance(props); this._eachSet(function (setDatum, setKey, getItems) { var items = getItems(); var index = indexOf(self, instance, items); if (canSet.subset(instance, setDatum.set, this.algebra)) { if (index === -1) { self.updateSet(setDatum, setAdd(self, setDatum.set, getItems(), instance, self.algebra)); } else { items.splice(index, 1, instance); self.updateSet(setDatum, items); } } else if (index !== -1) { items.splice(index, 1); self.updateSet(setDatum, items); } }); return Promise.resolve(assign({}, instance)); }, destroyData: function (props) { var self = this; this._eachSet(function (setDatum, setKey, getItems) { var items = getItems(); var index = indexOf(self, props, items); if (index !== -1) { items.splice(index, 1); self.updateSet(setDatum, items); } }); var id = this.id(props); delete this._instances[id]; return Promise.resolve(assign({}, props)); } }; return behavior; }); }); /*can-connect@2.0.0-pre.12#data/parse/parse*/ define('can-connect/data/parse/parse', [ 'require', 'exports', 'module', 'can-connect', 'can-util/js/each/each', 'can-util/js/get/get' ], function (require, exports, module) { var connect = require('can-connect'); var each = require('can-util/js/each/each'); var getObject = require('can-util/js/get/get'); module.exports = connect.behavior('data/parse', function (baseConnection) { var behavior = { parseListData: function (responseData) { if (baseConnection.parseListData) { responseData = baseConnection.parseListData.apply(this, arguments); } var result; if (Array.isArray(responseData)) { result = { data: responseData }; } else { var prop = this.parseListProp || 'data'; responseData.data = getObject(responseData, prop); result = responseData; if (prop !== 'data') { delete responseData[prop]; } if (!Array.isArray(result.data)) { throw new Error('Could not get any raw data while converting using .parseListData'); } } var arr = []; for (var i = 0; i < result.data.length; i++) { arr.push(this.parseInstanceData(result.data[i])); } result.data = arr; return result; }, parseInstanceData: function (props) { if (baseConnection.parseInstanceData) { props = baseConnection.parseInstanceData.apply(this, arguments) || props; } return this.parseInstanceProp ? getObject(props, this.parseInstanceProp) || props : props; } }; each(pairs, function (parseFunction, name) { behavior[name] = function (params) { var self = this; return baseConnection[name].call(this, params).then(function () { return self[parseFunction].apply(self, arguments); }); }; }); return behavior; }); var pairs = { getListData: 'parseListData', getData: 'parseInstanceData', createData: 'parseInstanceData', updateData: 'parseInstanceData', destroyData: 'parseInstanceData' }; }); /*can-param@1.0.2#can-param*/ define('can-param', [ 'require', 'exports', 'module', 'can-namespace' ], function (require, exports, module) { var namespace = require('can-namespace'); function buildParam(prefix, obj, add) { if (Array.isArray(obj)) { for (var i = 0, l = obj.length; i < l; ++i) { add(prefix + '[]', obj[i]); } } else if (obj && typeof obj === 'object') { for (var name in obj) { buildParam(prefix + '[' + name + ']', obj[name], add); } } else { add(prefix, obj); } } module.exports = namespace.param = function param(object) { var pairs = [], add = function (key, value) { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }; for (var name in object) { buildParam(name, object[name], add); } return pairs.join('&').replace(/%20/g, '+'); }; }); /*can-ajax@1.1.4#can-ajax*/ define('can-ajax', [ 'require', 'exports', 'module', 'can-globals/global/global', 'can-reflect', 'can-namespace', 'can-parse-uri', 'can-param' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var Global = require('can-globals/global/global'); var canReflect = require('can-reflect'); var namespace = require('can-namespace'); var parseURI = require('can-parse-uri'); var param = require('can-param'); var xhrs = [ function () { return new XMLHttpRequest(); }, function () { return new ActiveXObject('Microsoft.XMLHTTP'); }, function () { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); }, function () { return new ActiveXObject('MSXML2.XMLHTTP'); } ], _xhrf = null; var originUrl = parseURI(Global().location.href); var globalSettings = {}; var makeXhr = function () { if (_xhrf != null) { return _xhrf(); } for (var i = 0, l = xhrs.length; i < l; i++) { try { var f = xhrs[i], req = f(); if (req != null) { _xhrf = f; return req; } } catch (e) { continue; } } return function () { }; }; var contentTypes = { json: 'application/json', form: 'application/x-www-form-urlencoded' }; var _xhrResp = function (xhr, options) { switch (options.dataType || xhr.getResponseHeader('Content-Type').split(';')[0]) { case 'text/xml': case 'xml': return xhr.responseXML; case 'text/json': case 'application/json': case 'text/javascript': case 'application/javascript': case 'application/x-javascript': case 'json': return xhr.responseText && JSON.parse(xhr.responseText); default: return xhr.responseText; } }; function ajax(o) { var xhr = makeXhr(), timer, n = 0; var deferred = {}; var promise = new Promise(function (resolve, reject) { deferred.resolve = resolve; deferred.reject = reject; }); var requestUrl; promise.abort = function () { xhr.abort(); }; o = [ { userAgent: 'XMLHttpRequest', lang: 'en', type: 'GET', data: null, dataType: 'json' }, globalSettings, o ].reduce(function (a, b, i) { return canReflect.assignDeep(a, b); }); if (!o.contentType) { o.contentType = o.type.toUpperCase() === 'GET' ? contentTypes.form : contentTypes.json; } if (o.crossDomain == null) { try { requestUrl = parseURI(o.url); o.crossDomain = !!(requestUrl.protocol && requestUrl.protocol !== originUrl.protocol || requestUrl.host && requestUrl.host !== originUrl.host); } catch (e) { o.crossDomain = true; } } if (o.timeout) { timer = setTimeout(function () { xhr.abort(); if (o.timeoutFn) { o.timeoutFn(o.url); } }, o.timeout); } xhr.onreadystatechange = function () { try { if (xhr.readyState === 4) { if (timer) { clearTimeout(timer); } if (xhr.status < 300) { if (o.success) { o.success(_xhrResp(xhr, o)); } } else if (o.error) { o.error(xhr, xhr.status, xhr.statusText); } if (o.complete) { o.complete(xhr, xhr.statusText); } if (xhr.status >= 200 && xhr.status < 300) { deferred.resolve(_xhrResp(xhr, o)); } else { deferred.reject(xhr); } } else if (o.progress) { o.progress(++n); } } catch (e) { deferred.reject(e); } }; var url = o.url, data = null, type = o.type.toUpperCase(); var isJsonContentType = o.contentType === contentTypes.json; var isPost = type === 'POST' || type === 'PUT'; if (!isPost && o.data) { url += '?' + (isJsonContentType ? JSON.stringify(o.data) : param(o.data)); } xhr.open(type, url); var isSimpleCors = o.crossDomain && [ 'GET', 'POST', 'HEAD' ].indexOf(type) !== -1; if (isPost) { data = isJsonContentType && !isSimpleCors ? typeof o.data === 'object' ? JSON.stringify(o.data) : o.data : param(o.data); var setContentType = isJsonContentType && !isSimpleCors ? 'application/json' : 'application/x-www-form-urlencoded'; xhr.setRequestHeader('Content-Type', setContentType); } else { xhr.setRequestHeader('Content-Type', o.contentType); } if (!isSimpleCors) { xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); } if (o.xhrFields) { for (var f in o.xhrFields) { xhr[f] = o.xhrFields[f]; } } xhr.send(data); return promise; } module.exports = namespace.ajax = ajax; module.exports.ajaxSetup = function (o) { globalSettings = o || {}; }; }(function () { return this; }(), require, exports, module)); }); /*can-connect@2.0.0-pre.12#helpers/get-id-props*/ define('can-connect/helpers/get-id-props', function (require, exports, module) { module.exports = function (connection) { var ids = [], algebra = connection.algebra; if (algebra && algebra.clauses && algebra.clauses.id) { for (var prop in algebra.clauses.id) { ids.push(prop); } } if (connection.idProp && !ids.length) { ids.push(connection.idProp); } if (!ids.length) { ids.push('id'); } return ids; }; }); /*can-make-rest@0.1.2#can-make-rest*/ define('can-make-rest', [ 'require', 'exports', 'module', 'can-util/js/each/each' ], function (require, exports, module) { var each = require('can-util/js/each/each'); var methodMapping = { item: { 'GET': 'getData', 'PUT': 'updateData', 'DELETE': 'destroyData' }, list: { 'GET': 'getListData', 'POST': 'createData' } }; function inferIdProp(url) { var wrappedInBraces = /\{(.*)\}/; var matches = url.match(wrappedInBraces); var isUniqueMatch = matches && matches.length === 2; if (isUniqueMatch) { return matches[1]; } } function getItemAndListUrls(url, idProp) { idProp = idProp || inferIdProp(url) || 'id'; var itemRegex = new RegExp('\\/\\{' + idProp + '\\}.*'); var rootIsItemUrl = itemRegex.test(url); var listUrl = rootIsItemUrl ? url.replace(itemRegex, '') : url; var itemUrl = rootIsItemUrl ? url : url.trim() + '/{' + idProp + '}'; return { item: itemUrl, list: listUrl }; } module.exports = function (url, idProp) { var data = {}; each(getItemAndListUrls(url, idProp), function (url, type) { each(methodMapping[type], function (interfaceMethod, method) { data[interfaceMethod] = { method: method, url: url }; }); }); return data; }; }); /*can-util@3.10.18#js/is-promise/is-promise*/ define('can-util/js/is-promise/is-promise', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { 'use strict'; var canReflect = require('can-reflect'); module.exports = function (obj) { return canReflect.isPromise(obj); }; }); /*can-util@3.10.18#js/make-promise/make-promise*/ define('can-util/js/make-promise/make-promise', [ 'require', 'exports', 'module', 'can-util/js/is-promise-like/is-promise-like', 'can-util/js/is-promise/is-promise' ], function (require, exports, module) { 'use strict'; var isPromiseLike = require('can-util/js/is-promise-like/is-promise-like'); var isPromise = require('can-util/js/is-promise/is-promise'); module.exports = function (obj) { if (isPromiseLike(obj) && !isPromise(obj)) { return new Promise(function (resolve, reject) { obj.then(resolve, reject); }); } else { return obj; } }; }); /*can-connect@2.0.0-pre.12#data/url/url*/ define('can-connect/data/url/url', [ 'require', 'exports', 'module', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-ajax', 'can-util/js/string/string', 'can-connect/helpers/get-id-props', 'can-util/js/dev/dev', 'can-connect', 'can-make-rest', 'can-util/js/make-promise/make-promise', 'can-connect/helpers/validate' ], function (require, exports, module) { var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var ajax = require('can-ajax'); var string = require('can-util/js/string/string'); var getIdProps = require('can-connect/helpers/get-id-props'); var dev = require('can-util/js/dev/dev'); var connect = require('can-connect'); var makeRest = require('can-make-rest'); var defaultRest = makeRest('/resource/{id}'); var makePromise = require('can-util/js/make-promise/make-promise'); var urlBehavior = connect.behavior('data/url', function (baseConnection) { var behavior = {}; each(defaultRest, function (defaultData, dataInterfaceName) { behavior[dataInterfaceName] = function (params) { var meta = methodMetaData[dataInterfaceName]; if (typeof this.url === 'object') { if (typeof this.url[dataInterfaceName] === 'function') { return makePromise(this.url[dataInterfaceName](params)); } else if (this.url[dataInterfaceName]) { var promise = makeAjax(this.url[dataInterfaceName], params, defaultData.method, this.ajax || ajax, findContentType(this.url, defaultData.method), meta); return makePromise(promise); } } var resource = typeof this.url === 'string' ? this.url : this.url.resource; if (resource) { var idProps = getIdProps(this); var resourceWithoutTrailingSlashes = resource.replace(/\/+$/, ''); var result = makeRest(resourceWithoutTrailingSlashes, idProps[0])[dataInterfaceName]; return makePromise(makeAjax(result.url, params, result.method, this.ajax || ajax, findContentType(this.url, result.method), meta)); } return baseConnection[name].call(this, params); }; }); return behavior; }); var methodMetaData = { getListData: {}, getData: {}, createData: {}, updateData: {}, destroyData: { includeData: false } }; var findContentType = function (url, method) { if (typeof url === 'object' && url.contentType) { var acceptableType = url.contentType === 'application/x-www-form-urlencoded' || url.contentType === 'application/json'; if (acceptableType) { return url.contentType; } else { dev.warn('Unacceptable contentType on can-connect request. ' + 'Use \'application/json\' or \'application/x-www-form-urlencoded\''); } } return method === 'GET' ? 'application/x-www-form-urlencoded' : 'application/json'; }; var makeAjax = function (ajaxOb, data, type, ajax, contentType, reqOptions) { var params = {}; if (typeof ajaxOb === 'string') { var parts = ajaxOb.split(/\s+/); params.url = parts.pop(); if (parts.length) { params.type = parts.pop(); } } else { assign(params, ajaxOb); } params.data = typeof data === 'object' && !Array.isArray(data) ? assign(params.data || {}, data) : data; params.url = string.sub(params.url, params.data, true); params.contentType = contentType; if (reqOptions.includeData === false) { delete params.data; } return ajax(assign({ type: type || 'post', dataType: 'json' }, params)); }; module.exports = urlBehavior; var validate = require('can-connect/helpers/validate'); module.exports = validate(urlBehavior, ['url']); }); /*can-connect@2.0.0-pre.12#fall-through-cache/fall-through-cache*/ define('can-connect/fall-through-cache/fall-through-cache', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/helpers/sorted-set-json', 'can-util/js/log/log', 'can-connect/helpers/validate' ], function (require, exports, module) { var connect = require('can-connect'); var sortedSetJSON = require('can-connect/helpers/sorted-set-json'); var canLog = require('can-util/js/log/log'); var fallThroughCache = connect.behavior('fall-through-cache', function (baseConnection) { var behavior = { hydrateList: function (listData, set) { set = set || this.listSet(listData); var id = sortedSetJSON(set); var list = baseConnection.hydrateList.call(this, listData, set); if (this._getHydrateListCallbacks[id]) { this._getHydrateListCallbacks[id].shift()(list); if (!this._getHydrateListCallbacks[id].length) { delete this._getHydrateListCallbacks[id]; } } return list; }, _getHydrateListCallbacks: {}, _getHydrateList: function (set, callback) { var id = sortedSetJSON(set); if (!this._getHydrateListCallbacks[id]) { this._getHydrateListCallbacks[id] = []; } this._getHydrateListCallbacks[id].push(callback); }, getListData: function (set) { set = set || {}; var self = this; return this.cacheConnection.getListData(set).then(function (data) { self._getHydrateList(set, function (list) { self.addListReference(list, set); setTimeout(function () { baseConnection.getListData.call(self, set).then(function (listData) { self.cacheConnection.updateListData(listData, set); self.updatedList(list, listData, set); self.deleteListReference(list, set); }, function (e) { canLog.log('REJECTED', e); }); }, 1); }); return data; }, function () { var listData = baseConnection.getListData.call(self, set); listData.then(function (listData) { self.cacheConnection.updateListData(listData, set); }); return listData; }); }, hydrateInstance: function (props) { var id = this.id(props); var instance = baseConnection.hydrateInstance.apply(this, arguments); if (this._getMakeInstanceCallbacks[id]) { this._getMakeInstanceCallbacks[id].shift()(instance); if (!this._getMakeInstanceCallbacks[id].length) { delete this._getMakeInstanceCallbacks[id]; } } return instance; }, _getMakeInstanceCallbacks: {}, _getMakeInstance: function (id, callback) { if (!this._getMakeInstanceCallbacks[id]) { this._getMakeInstanceCallbacks[id] = []; } this._getMakeInstanceCallbacks[id].push(callback); }, getData: function (params) { var self = this; return this.cacheConnection.getData(params).then(function (instanceData) { self._getMakeInstance(self.id(instanceData) || self.id(params), function (instance) { self.addInstanceReference(instance); setTimeout(function () { baseConnection.getData.call(self, params).then(function (instanceData2) { self.cacheConnection.updateData(instanceData2); self.updatedInstance(instance, instanceData2); self.deleteInstanceReference(instance); }, function (e) { canLog.log('REJECTED', e); }); }, 1); }); return instanceData; }, function () { var listData = baseConnection.getData.call(self, params); listData.then(function (instanceData) { self.cacheConnection.updateData(instanceData); }); return listData; }); } }; return behavior; }); module.exports = fallThroughCache; var validate = require('can-connect/helpers/validate'); module.exports = validate(fallThroughCache, [ 'hydrateList', 'hydrateInstance', 'getListData', 'getData' ]); }); /*can-connect@2.0.0-pre.12#real-time/real-time*/ define('can-connect/real-time/real-time', [ 'require', 'exports', 'module', 'can-connect', 'can-set', 'can-connect/helpers/set-add', 'can-connect/helpers/get-index-by-id', 'can-util/js/dev/dev' ], function (require, exports, module) { var connect = require('can-connect'); var canSet = require('can-set'); var setAdd = require('can-connect/helpers/set-add'); var indexOf = require('can-connect/helpers/get-index-by-id'); var canDev = require('can-util/js/dev/dev'); module.exports = connect.behavior('real-time', function (baseConnection) { var createPromise = Promise.resolve(); return { createData: function () { var promise = baseConnection.createData.apply(this, arguments); var cleanPromise = promise.catch(function () { return ''; }); createPromise = Promise.all([ createPromise, cleanPromise ]); return promise; }, createInstance: function (props) { var self = this; return new Promise(function (resolve, reject) { createPromise.then(function () { setTimeout(function () { var id = self.id(props); var instance = self.instanceStore.get(id); var serialized; if (instance) { resolve(self.updateInstance(props)); } else { instance = self.hydrateInstance(props); serialized = self.serializeInstance(instance); self.addInstanceReference(instance); Promise.resolve(self.createdData(props, serialized)).then(function () { self.deleteInstanceReference(instance); resolve(instance); }); } }, 1); }); }); }, createdData: function (props, params, cid) { var instance; if (cid !== undefined) { instance = this.cidStore.get(cid); } else { instance = this.instanceStore.get(this.id(props)); } this.addInstanceReference(instance, this.id(props)); this.createdInstance(instance, props); create.call(this, this.serializeInstance(instance)); this.deleteInstanceReference(instance); return undefined; }, updatedData: function (props, params) { var instance = this.instanceStore.get(this.id(params)); this.updatedInstance(instance, props); update.call(this, this.serializeInstance(instance)); return undefined; }, updateInstance: function (props) { var id = this.id(props); var instance = this.instanceStore.get(id); if (!instance) { instance = this.hydrateInstance(props); } this.addInstanceReference(instance); var serialized = this.serializeInstance(instance), self = this; return Promise.resolve(this.updatedData(props, serialized)).then(function () { self.deleteInstanceReference(instance); return instance; }); }, destroyedData: function (props, params) { var id = this.id(params || props); var instance = this.instanceStore.get(id); if (!instance) { instance = this.hydrateInstance(props); } var serialized = this.serializeInstance(instance); this.destroyedInstance(instance, props); destroy.call(this, serialized); return undefined; }, destroyInstance: function (props) { var id = this.id(props); var instance = this.instanceStore.get(id); if (!instance) { instance = this.hydrateInstance(props); } this.addInstanceReference(instance); var serialized = this.serializeInstance(instance), self = this; return Promise.resolve(this.destroyedData(props, serialized)).then(function () { self.deleteInstanceReference(instance); return instance; }); }, gotListData: function (items, set) { var self = this; if (this.algebra) { for (var item, i = 0, l = items.data.length; i < l; i++) { item = items.data[i]; if (!self.algebra.has(set, item)) { var msg = 'One or more items were retrieved which do not match the \'Set\' parameters used to load them. ' + 'Read the docs for more information: https://canjs.com/doc/can-set.html#SolvingCommonIssues' + '\n\nBelow are the \'Set\' parameters:' + '\n' + canDev.stringify(set) + '\n\nAnd below is an item which does not match those parameters:' + '\n' + canDev.stringify(item); canDev.warn(msg); break; } } } return Promise.resolve(items); } }; }); var create = function (props) { var self = this; this.listStore.forEach(function (list, id) { var set = JSON.parse(id); var index = indexOf(self, props, list); if (canSet.has(set, props, self.algebra)) { if (index === -1) { var items = self.serializeList(list); self.updatedList(list, { data: setAdd(self, set, items, props, self.algebra) }, set); } else { } } }); }; var update = function (props) { var self = this; this.listStore.forEach(function (list, id) { var items; var set = JSON.parse(id); var index = indexOf(self, props, list); if (canSet.has(set, props, self.algebra)) { items = self.serializeList(list); if (index === -1) { self.updatedList(list, { data: setAdd(self, set, items, props, self.algebra) }, set); } else { var sortedIndex = canSet.index(set, items, props, self.algebra); if (sortedIndex !== undefined && sortedIndex !== index) { var copy = items.slice(0); if (index < sortedIndex) { copy.splice(sortedIndex, 0, props); copy.splice(index, 1); } else { copy.splice(index, 1); copy.splice(sortedIndex, 0, props); } self.updatedList(list, { data: copy }, set); } } } else if (index !== -1) { items = self.serializeList(list); items.splice(index, 1); self.updatedList(list, { data: items }, set); } }); }; var destroy = function (props) { var self = this; this.listStore.forEach(function (list, id) { var set = JSON.parse(id); var index = indexOf(self, props, list); if (index !== -1) { var items = self.serializeList(list); items.splice(index, 1); self.updatedList(list, { data: items }, set); } }); }; }); /*can-connect@2.0.0-pre.12#can/map/map*/ define('can-connect/can/map/map', [ 'require', 'exports', 'module', 'can-util/js/each/each', 'can-connect', 'can-queues', 'can-event-queue/map/legacy/legacy', 'can-observation-recorder', 'can-util/js/is-plain-object/is-plain-object', 'can-types', 'can-util/js/each/each', 'can-util/js/dev/dev', 'can-reflect', 'can-symbol', 'can-connect/helpers/validate' ], function (require, exports, module) { 'use strict'; var each = require('can-util/js/each/each'); var connect = require('can-connect'); var queues = require('can-queues'); var eventQueue = require('can-event-queue/map/legacy/legacy'); var ObservationRecorder = require('can-observation-recorder'); var isPlainObject = require('can-util/js/is-plain-object/is-plain-object'); var types = require('can-types'); var each = require('can-util/js/each/each'); var dev = require('can-util/js/dev/dev'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var canMapBehavior = connect.behavior('can/map', function (baseConnection) { var behavior = { init: function () { if (!this.Map) { throw new Error('can-connect/can/map/map must be configured with a Map type'); } this.List = this.List || this.Map.List; if (!this.List) { throw new Error('can-connect/can/map/map must be configured with a List type'); } overwrite(this, this.Map, mapOverwrites); overwrite(this, this.List, listOverwrites); var connection = this; if (this.Map[canSymbol.for('can.onInstanceBoundChange')]) { this.Map[canSymbol.for('can.onInstanceBoundChange')](function canConnectMap_onInstanceBoundChange(instance, isBound) { var method = isBound ? 'addInstanceReference' : 'deleteInstanceReference'; if (connection[method]) { connection[method](instance); } }); } else { console.warn('can-connect/can/map is unable to listen to onInstanceBoundChange on the Map type'); } if (this.List[canSymbol.for('can.onInstanceBoundChange')]) { this.List[canSymbol.for('can.onInstanceBoundChange')](function (list, isBound) { var method = isBound ? 'addListReference' : 'deleteListReference'; if (connection[method]) { connection[method](list); } }); } else { console.warn('can-connect/can/map is unable to listen to onInstanceBoundChange on the List type'); } if (this.Map[canSymbol.for('can.onInstancePatches')]) { this.Map[canSymbol.for('can.onInstancePatches')](function canConnectMap_onInstancePatches(instance, patches) { patches.forEach(function (patch) { if ((patch.type === 'add' || patch.type === 'set') && patch.key === connection.idProp && instance[canSymbol.for('can.isBound')]()) { connection.addInstanceReference(instance); } }); }); } else { console.warn('can-connect/can/map is unable to listen to onInstancePatches on the Map type'); } baseConnection.init.apply(this, arguments); }, id: function (instance) { if (!isPlainObject(instance)) { var ids = [], algebra = this.algebra; if (algebra && algebra.clauses && algebra.clauses.id) { for (var prop in algebra.clauses.id) { ids.push(canReflect.getKeyValue(instance, prop)); } } if (this.idProp && !ids.length) { ids.push(canReflect.getKeyValue(instance, this.idProp)); } if (!ids.length) { ids.push(canReflect.getKeyValue(instance, 'id')); } return ids.length > 1 ? ids.join('@|@') : ids[0]; } else { return baseConnection.id(instance); } }, serializeInstance: function (instance) { return canReflect.serialize(instance); }, serializeList: function (list) { return canReflect.serialize(list); }, instance: function (props) { var _Map = this.Map || types.DefaultMap; return new _Map(props); }, list: function (listData, set) { var _List = this.List || this.Map && this.Map.List || types.DefaultList; var list = new _List(listData.data); each(listData, function (val, prop) { if (prop !== 'data') { canReflect.setKeyValue(prop, val); } }); list.__listSet = set; return list; }, updatedList: function (list, listData, set) { queues.batch.start(); queues.mutateQueue.enqueue(baseConnection.updatedList, this, arguments, { reasonLog: [ 'set', set, 'list', list, 'updated with', listData ] }); queues.batch.stop(); }, save: function (instance) { canReflect.setKeyValue(instance, '_saving', true); var done = function () { canReflect.setKeyValue(instance, '_saving', false); }; var base = baseConnection.save.apply(this, arguments); base.then(done, done); return base; }, destroy: function (instance) { canReflect.setKeyValue(instance, '_destroying', true); var done = function () { canReflect.setKeyValue(instance, '_destroying', false); }; var base = baseConnection.destroy.apply(this, arguments); base.then(done, done); return base; } }; each([ 'created', 'updated', 'destroyed' ], function (funcName) { behavior[funcName + 'Instance'] = function (instance, props) { if (props && typeof props === 'object') { if (this.constructor.removeAttr) { canReflect.updateDeep(instance, props); } else { canReflect.assignDeep(instance, props); } } if (funcName === 'created' && this.moveCreatedInstanceToInstanceStore) { this.moveCreatedInstanceToInstanceStore(instance); } canMapBehavior.callbackInstanceEvents(funcName, instance); }; }); return behavior; }); canMapBehavior.callbackInstanceEvents = function (funcName, instance) { var constructor = instance.constructor; eventQueue.dispatch.call(instance, { type: funcName, target: instance }); if (this.id) { dev.log('can-connect/can/map/map.js - ' + (constructor.shortName || this.name) + ' ' + this.id(instance) + ' ' + funcName); } eventQueue.dispatch.call(constructor, funcName, [instance]); }; var mapOverwrites = { static: { getList: function (base, connection) { return function (set) { return connection.getList(set); }; }, findAll: function (base, connection) { return function (set) { return connection.getList(set); }; }, get: function (base, connection) { return function (params) { return connection.get(params); }; }, findOne: function (base, connection) { return function (params) { return connection.get(params); }; } }, prototype: { isNew: function (base, connection) { return function () { return connection.isNew(this); }; }, isSaving: function (base, connection) { return function () { return !!canReflect.getKeyValue(this, '_saving'); }; }, isDestroying: function (base, connection) { return function () { return !!canReflect.getKeyValue(this, '_destroying'); }; }, save: function (base, connection) { return function (success, error) { var promise = connection.save(this); promise.then(success, error); return promise; }; }, destroy: function (base, connection) { return function (success, error) { var promise; if (this.isNew()) { promise = Promise.resolve(this); connection.destroyedInstance(this, {}); } else { promise = connection.destroy(this); } promise.then(success, error); return promise; }; } }, properties: { _saving: { enumerable: false, value: false, configurable: true, writable: true }, _destroying: { enumerable: false, value: false, configurable: true, writable: true } } }; var listOverwrites = { static: { _bubbleRule: function (base, connection) { return function (eventName, list) { var bubbleRules = base(eventName, list); bubbleRules.push('destroyed'); return bubbleRules; }; } }, prototype: { setup: function (base, connection) { return function (params) { if (isPlainObject(params) && !Array.isArray(params)) { this.__listSet = params; base.apply(this); this.replace(canReflect.isPromise(params) ? params : connection.getList(params)); } else { base.apply(this, arguments); } }; } }, properties: {} }; var overwrite = function (connection, Constructor, overwrites) { var prop; for (prop in overwrites.properties) { canReflect.defineInstanceKey(Constructor, prop, overwrites.properties[prop]); } for (prop in overwrites.prototype) { Constructor.prototype[prop] = overwrites.prototype[prop](Constructor.prototype[prop], connection); } if (overwrites.static) { for (prop in overwrites.static) { Constructor[prop] = overwrites.static[prop](Constructor[prop], connection); } } }; module.exports = canMapBehavior; var validate = require('can-connect/helpers/validate'); module.exports = validate(canMapBehavior, [ 'id', 'get', 'updatedList', 'destroy', 'save', 'getList' ]); }); /*can-simple-observable@2.0.0-pre.24#async/async*/ define('can-simple-observable/async/async', [ 'require', 'exports', 'module', 'can-simple-observable', 'can-observation', 'can-queues', 'can-simple-observable/settable/settable', 'can-reflect', 'can-observation-recorder', 'can-event-queue/value/value' ], function (require, exports, module) { var SimpleObservable = require('can-simple-observable'); var Observation = require('can-observation'); var queues = require('can-queues'); var SettableObservable = require('can-simple-observable/settable/settable'); var canReflect = require('can-reflect'); var ObservationRecorder = require('can-observation-recorder'); var valueEventBindings = require('can-event-queue/value/value'); function AsyncObservable(fn, context, initialValue) { this.resolve = this.resolve.bind(this); this.lastSetValue = new SimpleObservable(initialValue); this.handler = this.handler.bind(this); function observe() { this.resolveCalled = false; return fn.call(context, this.lastSetValue.get(), this.bound === true ? this.resolve : undefined); } canReflect.assignSymbols(this, { 'can.getName': function () { return canReflect.getName(this.constructor) + '<' + canReflect.getName(fn) + '>'; } }); Object.defineProperty(this.handler, 'name', { value: canReflect.getName(this) + '.handler' }); Object.defineProperty(observe, 'name', { value: canReflect.getName(fn) + '::' + canReflect.getName(this.constructor) }); this.observation = new Observation(observe, this); } AsyncObservable.prototype = Object.create(SettableObservable.prototype); AsyncObservable.prototype.constructor = AsyncObservable; AsyncObservable.prototype.handler = function (newVal) { if (newVal !== undefined) { SettableObservable.prototype.handler.apply(this, arguments); } }; var peek = ObservationRecorder.ignore(canReflect.getValue.bind(canReflect)); AsyncObservable.prototype.onBound = function () { this.bound = true; canReflect.onValue(this.observation, this.handler, 'notify'); if (!this.resolveCalled) { this.value = peek(this.observation); } }; AsyncObservable.prototype.resolve = function resolve(newVal) { this.resolveCalled = true; var old = this.value; this.value = newVal; if (typeof this._log === 'function') { this._log(old, newVal); } queues.enqueueByQueue(this.handlers.getNode([]), this, [ newVal, old ], function () { return {}; }); }; module.exports = AsyncObservable; }); /*can-event-queue@0.13.1#type/type*/ define('can-event-queue/type/type', [ 'require', 'exports', 'module', 'can-reflect', 'can-symbol', 'can-key-tree', 'can-queues' ], function (require, exports, module) { var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var KeyTree = require('can-key-tree'); var queues = require('can-queues'); var metaSymbol = canSymbol.for('can.meta'); function ensureMeta(obj) { var meta = obj[metaSymbol]; if (!meta) { meta = {}; canReflect.setKeyValue(obj, metaSymbol, meta); } if (!meta.lifecycleHandlers) { meta.lifecycleHandlers = new KeyTree([ Object, Array ]); } if (!meta.instancePatchesHandlers) { meta.instancePatchesHandlers = new KeyTree([ Object, Array ]); } return meta; } module.exports = function (obj) { return canReflect.assignSymbols(obj, { 'can.onInstanceBoundChange': function (handler, queueName) { ensureMeta(this).lifecycleHandlers.add([ queueName || 'mutate', handler ]); }, 'can.offInstanceBoundChange': function (handler, queueName) { ensureMeta(this).lifecycleHandlers.delete([ queueName || 'mutate', handler ]); }, 'can.dispatchInstanceBoundChange': function (obj, isBound) { queues.enqueueByQueue(ensureMeta(this).lifecycleHandlers.getNode([]), this, [ obj, isBound ]); }, 'can.onInstancePatches': function (handler, queueName) { ensureMeta(this).instancePatchesHandlers.add([ queueName || 'mutate', handler ]); }, 'can.offInstancePatches': function (handler, queueName) { ensureMeta(this).instancePatchesHandlers.delete([ queueName || 'mutate', handler ]); }, 'can.dispatchInstanceOnPatches': function (obj, patches) { queues.enqueueByQueue(ensureMeta(this).instancePatchesHandlers.getNode([]), this, [ obj, patches ]); } }); }; }); /*can-util@3.10.18#js/defaults/defaults*/ define('can-util/js/defaults/defaults', function (require, exports, module) { 'use strict'; module.exports = function (target) { var length = arguments.length; for (var i = 1; i < length; i++) { for (var prop in arguments[i]) { if (target[prop] === undefined) { target[prop] = arguments[i][prop]; } } } return target; }; }); /*can-util@3.10.18#js/string-to-any/string-to-any*/ define('can-util/js/string-to-any/string-to-any', function (require, exports, module) { 'use strict'; module.exports = function (str) { switch (str) { case 'NaN': case 'Infinity': return +str; case 'null': return null; case 'undefined': return undefined; case 'true': case 'false': return str === 'true'; default: var val = +str; if (!isNaN(val)) { return val; } else { return str; } } }; }); /*can-define@2.0.0-pre.19#can-define*/ define('can-define', [ 'require', 'exports', 'module', 'can-namespace', 'can-symbol', 'can-reflect', 'can-observation', 'can-observation-recorder', 'can-simple-observable/async/async', 'can-simple-observable/settable/settable', 'can-cid', 'can-event-queue/map/legacy/legacy', 'can-event-queue/type/type', 'can-queues', 'can-util/js/is-empty-object/is-empty-object', 'can-util/js/assign/assign', 'can-log/dev/dev', 'can-util/js/is-plain-object/is-plain-object', 'can-util/js/each/each', 'can-util/js/defaults/defaults', 'can-util/js/string-to-any/string-to-any', 'can-define-lazy-value' ], function (require, exports, module) { 'use strict'; 'format cjs'; var ns = require('can-namespace'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var Observation = require('can-observation'); var ObservationRecorder = require('can-observation-recorder'); var AsyncObservable = require('can-simple-observable/async/async'); var SettableObservable = require('can-simple-observable/settable/settable'); var CID = require('can-cid'); var eventQueue = require('can-event-queue/map/legacy/legacy'); var addTypeEvents = require('can-event-queue/type/type'); var queues = require('can-queues'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var assign = require('can-util/js/assign/assign'); var canLogDev = require('can-log/dev/dev'); var isPlainObject = require('can-util/js/is-plain-object/is-plain-object'); var each = require('can-util/js/each/each'); var defaults = require('can-util/js/defaults/defaults'); var stringToAny = require('can-util/js/string-to-any/string-to-any'); var defineLazyValue = require('can-define-lazy-value'); var eventsProto, define, make, makeDefinition, getDefinitionsAndMethods, isDefineType, getDefinitionOrMethod; var defineConfigurableAndNotEnumerable = function (obj, prop, value) { Object.defineProperty(obj, prop, { configurable: true, enumerable: false, writable: true, value: value }); }; var eachPropertyDescriptor = function (map, cb) { for (var prop in map) { if (map.hasOwnProperty(prop)) { cb.call(map, prop, Object.getOwnPropertyDescriptor(map, prop)); } } }; module.exports = define = ns.define = function (objPrototype, defines, baseDefine) { var prop, dataInitializers = Object.create(baseDefine ? baseDefine.dataInitializers : null), computedInitializers = Object.create(baseDefine ? baseDefine.computedInitializers : null); var result = getDefinitionsAndMethods(defines, baseDefine); result.dataInitializers = dataInitializers; result.computedInitializers = computedInitializers; each(result.definitions, function (definition, property) { define.property(objPrototype, property, definition, dataInitializers, computedInitializers); }); if (objPrototype.hasOwnProperty('_data')) { for (prop in dataInitializers) { defineLazyValue(objPrototype._data, prop, dataInitializers[prop].bind(objPrototype), true); } } else { defineLazyValue(objPrototype, '_data', function () { var map = this; var data = {}; for (var prop in dataInitializers) { defineLazyValue(data, prop, dataInitializers[prop].bind(map), true); } return data; }); } if (objPrototype.hasOwnProperty('_computed')) { for (prop in computedInitializers) { defineLazyValue(objPrototype._computed, prop, computedInitializers[prop].bind(objPrototype)); } } else { defineLazyValue(objPrototype, '_computed', function () { var map = this; var data = Object.create(null); for (var prop in computedInitializers) { defineLazyValue(data, prop, computedInitializers[prop].bind(map)); } return data; }); } if (!objPrototype.hasOwnProperty('_cid')) { defineLazyValue(objPrototype, '_cid', function () { return CID({}); }); } for (prop in eventsProto) { Object.defineProperty(objPrototype, prop, { enumerable: false, value: eventsProto[prop], configurable: true, writable: true }); } Object.defineProperty(objPrototype, '_define', { enumerable: false, value: result, configurable: true, writable: true }); var iteratorSymbol = canSymbol.iterator || canSymbol.for('iterator'); if (!objPrototype[iteratorSymbol]) { defineConfigurableAndNotEnumerable(objPrototype, iteratorSymbol, function () { return new define.Iterator(this); }); } return result; }; define.extensions = function () { }; var onlyType = function (obj) { for (var prop in obj) { if (prop !== 'type') { return false; } } return true; }; define.property = function (objPrototype, prop, definition, dataInitializers, computedInitializers) { var propertyDefinition = define.extensions.apply(this, arguments); if (propertyDefinition) { definition = propertyDefinition; } var type = definition.type; if (type && canReflect.isConstructorLike(type)) { canLogDev.warn('can-define: the definition for ' + prop + (objPrototype.constructor.shortName ? ' on ' + objPrototype.constructor.shortName : '') + ' uses a constructor for "type". Did you mean "Type"?'); } if (type && onlyType(definition) && type === define.types['*']) { Object.defineProperty(objPrototype, prop, { get: make.get.data(prop), set: make.set.events(prop, make.get.data(prop), make.set.data(prop), make.eventType.data(prop)), enumerable: true, configurable: true }); return; } definition.type = type; var dataProperty = definition.get ? 'computed' : 'data', reader = make.read[dataProperty](prop), getter = make.get[dataProperty](prop), setter = make.set[dataProperty](prop), getInitialValue; if (definition.get) { Object.defineProperty(definition.get, 'name', { value: canReflect.getName(objPrototype) + '\'s ' + prop + ' getter' }); } if (definition.set) { Object.defineProperty(definition.set, 'name', { value: canReflect.getName(objPrototype) + '\'s ' + prop + ' setter' }); } var typeConvert = function (val) { return val; }; if (definition.Type) { typeConvert = make.set.Type(prop, definition.Type, typeConvert); } if (type) { typeConvert = make.set.type(prop, type, typeConvert); } var eventsSetter = make.set.events(prop, reader, setter, make.eventType[dataProperty](prop)); if (definition.value !== undefined || definition.Value !== undefined) { if (definition.value !== null && typeof definition.value === 'object') { canLogDev.warn('can-define: The value for ' + prop + ' is set to an object. This will be shared by all instances of the DefineMap. Use a function that returns the object instead.'); } if (definition.value && canReflect.isConstructorLike(definition.value)) { canLogDev.warn('can-define: The "value" for ' + prop + ' is set to a constructor. Did you mean "Value" instead?'); } getInitialValue = ObservationRecorder.ignore(make.get.defaultValue(prop, definition, typeConvert, eventsSetter)); } if (definition.get) { computedInitializers[prop] = make.compute(prop, definition.get, getInitialValue); } else if (getInitialValue) { dataInitializers[prop] = getInitialValue; } if (definition.get && definition.set) { setter = make.set.setter(prop, definition.set, make.read.lastSet(prop), setter, true); } else if (definition.set) { setter = make.set.setter(prop, definition.set, reader, eventsSetter, false); } else if (!definition.get) { setter = eventsSetter; } else if (definition.get.length < 1) { setter = function () { canLogDev.warn('can-define: Set value for property ' + prop + (objPrototype.constructor.shortName ? ' on ' + objPrototype.constructor.shortName : '') + ' ignored, as its definition has a zero-argument getter and no setter'); }; } if (type) { setter = make.set.type(prop, type, setter); } if (definition.Type) { setter = make.set.Type(prop, definition.Type, setter); } Object.defineProperty(objPrototype, prop, { get: getter, set: setter, enumerable: 'serialize' in definition ? !!definition.serialize : !definition.get, configurable: true }); }; define.makeDefineInstanceKey = function (constructor) { constructor[canSymbol.for('can.defineInstanceKey')] = function (property, value) { var defineResult = this.prototype._define; var definition = getDefinitionOrMethod(property, value, defineResult.defaultDefinition); if (definition && typeof definition === 'object') { define.property(constructor.prototype, property, definition, defineResult.dataInitializers, defineResult.computedInitializers); defineResult.definitions[property] = definition; } else { defineResult.methods[property] = definition; } }; }; define.Constructor = function (defines, sealed) { var constructor = function (props) { Object.defineProperty(this, '__inSetup', { configurable: true, enumerable: false, value: true, writable: true }); define.setup.call(this, props, sealed); this.__inSetup = false; }; var result = define(constructor.prototype, defines); addTypeEvents(constructor); define.makeDefineInstanceKey(constructor, result); return constructor; }; make = { compute: function (prop, get, defaultValueFn) { return function () { var map = this, defaultValue = defaultValueFn && defaultValueFn.call(this), observable, computeObj; if (get.length === 0) { observable = new Observation(get, map); } else if (get.length === 1) { observable = new SettableObservable(get, map, defaultValue); } else { observable = new AsyncObservable(get, map, defaultValue); } computeObj = { oldValue: undefined, compute: observable, count: 0, handler: function (newVal) { var oldValue = computeObj.oldValue; computeObj.oldValue = newVal; map.dispatch({ type: prop, target: map }, [ newVal, oldValue ]); } }; Object.defineProperty(computeObj.handler, 'name', { value: canReflect.getName(get).replace('getter', 'event emitter') }); return computeObj; }; }, set: { data: function (prop) { return function (newVal) { this._data[prop] = newVal; }; }, computed: function (prop) { return function (val) { canReflect.setValue(this._computed[prop].compute, val); }; }, events: function (prop, getCurrent, setData, eventType) { return function (newVal) { if (this.__inSetup) { setData.call(this, newVal); } else { var current = getCurrent.call(this); if (newVal !== current) { setData.call(this, newVal); this.dispatch({ patches: [{ type: 'set', key: prop, value: newVal }], type: prop, target: this, reasonLog: [ canReflect.getName(this) + '\'s', prop, 'changed to', newVal, 'from', current ] }, [ newVal, current ]); } } }; }, setter: function (prop, setter, getCurrent, setEvents, hasGetter) { return function (value) { var asyncTimer; var self = this; queues.batch.start(); var setterCalled = false, current = getCurrent.call(this), setValue = setter.call(this, value, function (value) { setEvents.call(self, value); setterCalled = true; clearTimeout(asyncTimer); }, current); if (setterCalled) { queues.batch.stop(); } else { if (hasGetter) { if (setValue !== undefined) { if (current !== setValue) { setEvents.call(this, setValue); } queues.batch.stop(); } else if (setter.length === 0) { setEvents.call(this, value); queues.batch.stop(); return; } else if (setter.length === 1) { queues.batch.stop(); } else { asyncTimer = setTimeout(function () { canLogDev.warn('can/map/setter.js: Setter "' + prop + '" did not return a value or call the setter callback.'); }, canLogDev.warnTimeout); queues.batch.stop(); return; } } else { if (setValue !== undefined) { setEvents.call(this, setValue); queues.batch.stop(); } else if (setter.length === 0) { setEvents.call(this, value); queues.batch.stop(); return; } else if (setter.length === 1) { setEvents.call(this, undefined); queues.batch.stop(); } else { asyncTimer = setTimeout(function () { canLogDev.warn('can/map/setter.js: Setter "' + prop + '" did not return a value or call the setter callback.'); }, canLogDev.warnTimeout); queues.batch.stop(); return; } } } }; }, type: function (prop, type, set) { if (typeof type === 'object') { return make.set.Type(prop, type, set); } else { return function (newValue) { return set.call(this, type.call(this, newValue, prop)); }; } }, Type: function (prop, Type, set) { if (Array.isArray(Type) && define.DefineList) { Type = define.DefineList.extend({ '#': Type[0] }); } else if (typeof Type === 'object') { if (define.DefineMap) { Type = define.DefineMap.extend(Type); } else { Type = define.Constructor(Type); } } return function (newValue) { if (newValue instanceof Type || newValue == null) { return set.call(this, newValue); } else { return set.call(this, new Type(newValue)); } }; } }, eventType: { data: function (prop) { return function (newVal, oldVal) { return oldVal !== undefined || this._data.hasOwnProperty(prop) ? 'set' : 'add'; }; }, computed: function () { return function () { return 'set'; }; } }, read: { data: function (prop) { return function () { return this._data[prop]; }; }, computed: function (prop) { return function () { return canReflect.getValue(this._computed[prop].compute); }; }, lastSet: function (prop) { return function () { var observable = this._computed[prop].compute; if (observable.lastSetValue) { return canReflect.getValue(observable.lastSetValue); } }; } }, get: { defaultValue: function (prop, definition, typeConvert, callSetter) { return function () { var value = definition.value; if (value !== undefined) { if (typeof value === 'function') { value = value.call(this); } value = typeConvert(value); } else { var Value = definition.Value; if (Value) { value = typeConvert(new Value()); } } if (definition.set) { var VALUE; var sync = true; var setter = make.set.setter(prop, definition.set, function () { }, function (value) { if (sync) { VALUE = value; } else { callSetter.call(this, value); } }, definition.get); setter.call(this, value); sync = false; return VALUE; } return value; }; }, data: function (prop) { return function () { if (!this.__inSetup) { ObservationRecorder.add(this, prop); } return this._data[prop]; }; }, computed: function (prop) { return function () { return canReflect.getValue(this._computed[prop].compute); }; } } }; define.behaviors = [ 'get', 'set', 'value', 'Value', 'type', 'Type', 'serialize' ]; var addBehaviorToDefinition = function (definition, behavior, value) { if (behavior === 'enumerable') { definition.serialize = !!value; } else if (behavior === 'type') { var behaviorDef = value; if (typeof behaviorDef === 'string') { behaviorDef = define.types[behaviorDef]; if (typeof behaviorDef === 'object') { assign(definition, behaviorDef); behaviorDef = behaviorDef[behavior]; } } if (typeof behaviorDef !== 'undefined') { definition[behavior] = behaviorDef; } } else { definition[behavior] = value; } }; makeDefinition = function (prop, def, defaultDefinition) { var definition = {}; each(def, function (value, behavior) { addBehaviorToDefinition(definition, behavior, value); }); each(defaultDefinition, function (value, prop) { if (definition[prop] === undefined) { if (prop !== 'type' && prop !== 'Type') { definition[prop] = value; } } }); if (typeof def.type !== 'string') { if (!definition.type && !definition.Type) { defaults(definition, defaultDefinition); } if (isEmptyObject(definition)) { definition.type = define.types['*']; } } return definition; }; getDefinitionOrMethod = function (prop, value, defaultDefinition) { var definition; if (typeof value === 'string') { definition = { type: value }; } else if (typeof value === 'function') { if (canReflect.isConstructorLike(value)) { definition = { Type: value }; } else if (isDefineType(value)) { definition = { type: value }; } } else if (Array.isArray(value)) { definition = { Type: value }; } else if (isPlainObject(value)) { definition = value; } if (definition) { return makeDefinition(prop, definition, defaultDefinition); } else { return value; } }; getDefinitionsAndMethods = function (defines, baseDefines) { var definitions = Object.create(baseDefines ? baseDefines.definitions : null); var methods = {}; var defaults = defines['*'], defaultDefinition; if (defaults) { delete defines['*']; defaultDefinition = getDefinitionOrMethod('*', defaults, {}); } else { defaultDefinition = Object.create(null); } eachPropertyDescriptor(defines, function (prop, propertyDescriptor) { var value; if (propertyDescriptor.get || propertyDescriptor.set) { value = { get: propertyDescriptor.get, set: propertyDescriptor.set }; } else { value = propertyDescriptor.value; } if (prop === 'constructor') { methods[prop] = value; return; } else { var result = getDefinitionOrMethod(prop, value, defaultDefinition); if (result && typeof result === 'object' && !isEmptyObject(result)) { definitions[prop] = result; } else { if (typeof result === 'function') { methods[prop] = result; } else if (typeof result !== 'undefined') { canLogDev.error(prop + (this.constructor.shortName ? ' on ' + this.constructor.shortName : '') + ' does not match a supported propDefinition. See: https://canjs.com/doc/can-define.types.propDefinition.html'); } } } }); if (defaults) { defines['*'] = defaults; } return { definitions: definitions, methods: methods, defaultDefinition: defaultDefinition }; }; eventsProto = eventQueue({}); var canMetaSymbol = canSymbol.for('can.meta'); assign(eventsProto, { _eventSetup: function () { }, _eventTeardown: function () { }, addEventListener: function (eventName, handler, queue) { var computedBinding = this._computed && this._computed[eventName]; if (computedBinding && computedBinding.compute) { if (!computedBinding.count) { computedBinding.count = 1; canReflect.onValue(computedBinding.compute, computedBinding.handler, 'notify'); computedBinding.oldValue = canReflect.getValue(computedBinding.compute); } else { computedBinding.count++; } } return eventQueue.addEventListener.apply(this, arguments); }, removeEventListener: function (eventName, handler) { var computedBinding = this._computed && this._computed[eventName]; if (computedBinding) { if (computedBinding.count === 1) { computedBinding.count = 0; canReflect.offValue(computedBinding.compute, computedBinding.handler, 'notify'); } else { computedBinding.count--; } } return eventQueue.removeEventListener.apply(this, arguments); } }); eventsProto.on = eventsProto.bind = eventsProto.addEventListener; eventsProto.off = eventsProto.unbind = eventsProto.removeEventListener; delete eventsProto.one; define.setup = function (props, sealed) { CID(this); Object.defineProperty(this, '_cid', { value: this._cid, enumerable: false, writable: false }); Object.defineProperty(this, 'constructor', { value: this.constructor, enumerable: false, writable: false }); Object.defineProperty(this, canMetaSymbol, { value: Object.create(null), enumerable: false, writable: false }); var definitions = this._define.definitions; var instanceDefinitions = Object.create(null); var map = this; canReflect.eachKey(props, function (value, prop) { if (definitions[prop] !== undefined) { map[prop] = value; } else { var def = define.makeSimpleGetterSetter(prop); instanceDefinitions[prop] = {}; Object.defineProperty(map, prop, def); map[prop] = define.types.observable(value); } }); if (!isEmptyObject(instanceDefinitions)) { defineConfigurableAndNotEnumerable(this, '_instanceDefinitions', instanceDefinitions); } this._data; this._computed; if (sealed !== false) { Object.seal(this); } }; define.replaceWith = defineLazyValue; define.eventsProto = eventsProto; define.defineConfigurableAndNotEnumerable = defineConfigurableAndNotEnumerable; define.make = make; define.getDefinitionOrMethod = getDefinitionOrMethod; var simpleGetterSetters = {}; define.makeSimpleGetterSetter = function (prop) { if (!simpleGetterSetters[prop]) { var setter = make.set.events(prop, make.get.data(prop), make.set.data(prop), make.eventType.data(prop)); simpleGetterSetters[prop] = { get: make.get.data(prop), set: function (newVal) { return setter.call(this, define.types.observable(newVal)); }, enumerable: true }; } return simpleGetterSetters[prop]; }; define.Iterator = function (obj) { this.obj = obj; this.definitions = Object.keys(obj._define.definitions); this.instanceDefinitions = obj._instanceDefinitions ? Object.keys(obj._instanceDefinitions) : Object.keys(obj); this.hasGet = typeof obj.get === 'function'; }; define.Iterator.prototype.next = function () { var key; if (this.definitions.length) { key = this.definitions.shift(); var def = this.obj._define.definitions[key]; if (def.get) { return this.next(); } } else if (this.instanceDefinitions.length) { key = this.instanceDefinitions.shift(); } else { return { value: undefined, done: true }; } return { value: [ key, this.hasGet ? this.obj.get(key) : this.obj[key] ], done: false }; }; isDefineType = function (func) { return func && func.canDefineType === true; }; function isObservableValue(obj) { return canReflect.isValueLike(obj) && canReflect.isObservableLike(obj); } define.types = { 'date': function (str) { var type = typeof str; if (type === 'string') { str = Date.parse(str); return isNaN(str) ? null : new Date(str); } else if (type === 'number') { return new Date(str); } else { return str; } }, 'number': function (val) { if (val == null) { return val; } return +val; }, 'boolean': function (val) { if (val == null) { return val; } if (val === 'false' || val === '0' || !val) { return false; } return true; }, 'observable': function (newVal) { if (Array.isArray(newVal) && define.DefineList) { newVal = new define.DefineList(newVal); } else if (isPlainObject(newVal) && define.DefineMap) { newVal = new define.DefineMap(newVal); } return newVal; }, 'stringOrObservable': function (newVal) { if (Array.isArray(newVal)) { return new define.DefaultList(newVal); } else if (isPlainObject(newVal)) { return new define.DefaultMap(newVal); } else { return define.types.string(newVal); } }, 'htmlbool': function (val) { if (val === '') { return true; } return !!stringToAny(val); }, '*': function (val) { return val; }, 'any': function (val) { return val; }, 'string': function (val) { if (val == null) { return val; } return '' + val; }, 'compute': { set: function (newValue, setVal, setErr, oldValue) { if (isObservableValue(newValue)) { return newValue; } if (isObservableValue(oldValue)) { canReflect.setValue(oldValue, newValue); return oldValue; } return newValue; }, get: function (value) { return isObservableValue(value) ? canReflect.getValue(value) : value; } } }; }); /*can-connect@2.0.0-pre.12#can/ref/ref*/ define('can-connect/can/ref/ref', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/helpers/get-id-props', 'can-connect/helpers/weak-reference-map', 'can-observation-recorder', 'can-connect/constructor/store/store', 'can-define' ], function (require, exports, module) { var connect = require('can-connect'); var getIdProps = require('can-connect/helpers/get-id-props'); var WeakReferenceMap = require('can-connect/helpers/weak-reference-map'); var ObservationRecorder = require('can-observation-recorder'); var constructorStore = require('can-connect/constructor/store/store'); var define = require('can-define'); var makeRef = function (connection) { var idProp = getIdProps(connection)[0]; var Ref = function (id, value) { if (typeof id === 'object') { value = id; id = value[idProp]; } var storeRef = Ref.store.get(id); if (storeRef) { if (value && !storeRef._value) { if (value instanceof connection.Map) { storeRef._value = value; } else { storeRef._value = connection.hydrateInstance(value); } } return storeRef; } this[idProp] = id; if (value) { if (value instanceof connection.Map) { this._value = value; } else { this._value = connection.hydrateInstance(value); } } if (constructorStore.requests.count() > 0) { if (!Ref._requestInstances[id]) { Ref.store.addReference(id, this); Ref._requestInstances[id] = this; } } }; Ref.store = new WeakReferenceMap(); Ref._requestInstances = {}; Ref.type = function (ref) { if (ref && typeof ref !== 'object') { return new Ref(ref); } else { return new Ref(ref[idProp], ref); } }; var defs = { promise: { get: function () { if (this._value) { return Promise.resolve(this._value); } else { var props = {}; props[idProp] = this[idProp]; return connection.Map.get(props); } } }, _state: { get: function (lastSet, resolve) { if (resolve) { this.promise.then(function () { resolve('resolved'); }, function () { resolve('rejected'); }); } return 'pending'; } }, value: { get: function (lastSet, resolve) { if (this._value) { return this._value; } else if (resolve) { this.promise.then(function (value) { resolve(value); }); } } }, reason: { get: function (lastSet, resolve) { if (this._value) { return undefined; } else { this.promise.catch(function (value) { resolve(value); }); } } } }; defs[idProp] = { type: '*', set: function () { this._value = undefined; } }; define(Ref.prototype, defs); Ref.prototype.unobservedId = ObservationRecorder.ignore(function () { return this[idProp]; }); Ref.prototype.isResolved = function () { return !!this._value || this._state === 'resolved'; }; Ref.prototype.isRejected = function () { return this._state === 'rejected'; }; Ref.prototype.isPending = function () { return !this._value && (this._state !== 'resolved' || this._state !== 'rejected'); }; Ref.prototype.serialize = function () { return this[idProp]; }; var baseEventSetup = Ref.prototype._eventSetup; Ref.prototype._eventSetup = function () { Ref.store.addReference(this.unobservedId(), this); return baseEventSetup.apply(this, arguments); }; var baseTeardown = Ref.prototype._eventTeardown; Ref.prototype._eventTeardown = function () { Ref.store.deleteReference(this.unobservedId(), this); return baseTeardown.apply(this, arguments); }; constructorStore.requests.on('end', function () { for (var id in Ref._requestInstances) { Ref.store.deleteReference(id); } Ref._requestInstances = {}; }); return Ref; }; module.exports = connect.behavior('can/ref', function (baseConnection) { return { init: function () { baseConnection.init.apply(this, arguments); this.Map.Ref = makeRef(this); } }; }); }); /*can-connect@2.0.0-pre.12#can/super-map/super-map*/ define('can-connect/can/super-map/super-map', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/constructor/constructor', 'can-connect/can/map/map', 'can-connect/can/ref/ref', 'can-connect/constructor/store/store', 'can-connect/data/callbacks/callbacks', 'can-connect/data/callbacks-cache/callbacks-cache', 'can-connect/data/combine-requests/combine-requests', 'can-connect/data/localstorage-cache/localstorage-cache', 'can-connect/data/parse/parse', 'can-connect/data/url/url', 'can-connect/fall-through-cache/fall-through-cache', 'can-connect/real-time/real-time', 'can-connect/constructor/callbacks-once/callbacks-once', 'can-util/js/global/global' ], function (require, exports, module) { (function (global, require, exports, module) { var connect = require('can-connect'); var constructor = require('can-connect/constructor/constructor'); var canMap = require('can-connect/can/map/map'); var canRef = require('can-connect/can/ref/ref'); var constructorStore = require('can-connect/constructor/store/store'); var dataCallbacks = require('can-connect/data/callbacks/callbacks'); var callbacksCache = require('can-connect/data/callbacks-cache/callbacks-cache'); var combineRequests = require('can-connect/data/combine-requests/combine-requests'); var localCache = require('can-connect/data/localstorage-cache/localstorage-cache'); var dataParse = require('can-connect/data/parse/parse'); var dataUrl = require('can-connect/data/url/url'); var fallThroughCache = require('can-connect/fall-through-cache/fall-through-cache'); var realTime = require('can-connect/real-time/real-time'); var callbacksOnce = require('can-connect/constructor/callbacks-once/callbacks-once'); var GLOBAL = require('can-util/js/global/global'); var $ = GLOBAL().$; connect.superMap = function (options) { var behaviors = [ constructor, canMap, canRef, constructorStore, dataCallbacks, combineRequests, dataParse, dataUrl, realTime, callbacksOnce ]; if (typeof localStorage !== 'undefined') { if (!options.cacheConnection) { options.cacheConnection = connect([localCache], { name: options.name + 'Cache', idProp: options.idProp, algebra: options.algebra }); } behaviors.push(callbacksCache, fallThroughCache); } if ($ && $.ajax) { options.ajax = $.ajax; } return connect(behaviors, options); }; module.exports = connect.superMap; }(function () { return this; }(), require, exports, module)); }); /*can-connect@2.0.0-pre.12#can/tag/tag*/ define('can-connect/can/tag/tag', [ 'require', 'exports', 'module', 'can-stache-bindings', 'can-connect', 'can-observation', 'can-stache/src/expression', 'can-view-callbacks', 'can-observation-recorder', 'can-view-nodelist', 'can-event-queue/map/legacy/legacy', 'can-reflect', 'can-util/js/each/each', 'can-util/dom/mutate/mutate', 'can-util/dom/data/data', 'can-util/dom/events/removed/removed' ], function (require, exports, module) { require('can-stache-bindings'); var connect = require('can-connect'); var Observation = require('can-observation'); var expression = require('can-stache/src/expression'); var viewCallbacks = require('can-view-callbacks'); var ObservationRecorder = require('can-observation-recorder'); var nodeLists = require('can-view-nodelist'); var eventQueue = require('can-event-queue/map/legacy/legacy'); var canReflect = require('can-reflect'); var each = require('can-util/js/each/each'); var domMutate = require('can-util/dom/mutate/mutate'); var domData = require('can-util/dom/data/data'); require('can-util/dom/events/removed/removed'); var convertToValue = function (arg) { if (typeof arg === 'function') { return convertToValue(arg()); } else { return arg; } }; connect.tag = function (tagName, connection) { var removeBrackets = function (value, open, close) { open = open || '{'; close = close || '}'; if (value[0] === open && value[value.length - 1] === close) { return value.substr(1, value.length - 2); } return value; }; viewCallbacks.tag(tagName, function (el, tagData) { var getList = el.getAttribute('getList') || el.getAttribute('get-list'); var getInstance = el.getAttribute('get'); var attrValue = getList || getInstance; var method = getList ? 'getList' : 'get'; var attrInfo = expression.parse('tmp(' + removeBrackets(attrValue) + ')', { baseMethodType: 'Call' }); var addedToPageData = false; var addToPageData = ObservationRecorder.ignore(function (set, promise) { if (!addedToPageData) { var root = tagData.scope.peek('%root') || tagData.scope.peek('@root'); if (root && root.pageData) { if (method === 'get') { set = connection.id(set); } root.pageData(connection.name, set, promise); } } addedToPageData = true; }); var request = new Observation(function () { var hash = {}; if (typeof attrInfo.hash === 'object') { each(attrInfo.hash, function (val, key) { if (val && val.hasOwnProperty('get')) { hash[key] = tagData.scope.read(val.get, {}).value; } else { hash[key] = val; } }); } else if (typeof attrInfo.hash === 'function') { var getHash = attrInfo.hash(tagData.scope, tagData.options, {}); each(getHash(), function (val, key) { hash[key] = convertToValue(val); }); } else { hash = attrInfo.argExprs.length ? canReflect.getValue(attrInfo.argExprs[0].value(tagData.scope, tagData.options)) : {}; } var promise = connection[method](hash); addToPageData(hash, promise); return promise; }); domData.set.call(el, 'viewModel', request); var nodeList = nodeLists.register([], undefined, tagData.parentNodeList || true); var frag = tagData.subtemplate ? tagData.subtemplate(tagData.scope.add(request), tagData.options, nodeList) : document.createDocumentFragment(); domMutate.appendChild.call(el, frag); nodeLists.update(nodeList, el.childNodes); eventQueue.one.call(el, 'removed', function () { nodeLists.unregister(nodeList); }); }); }; module.exports = connect.tag; }); /*can-connect@2.0.0-pre.12#can/base-map/base-map*/ define('can-connect/can/base-map/base-map', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/constructor/constructor', 'can-connect/can/map/map', 'can-connect/can/ref/ref', 'can-connect/constructor/store/store', 'can-connect/data/callbacks/callbacks', 'can-connect/data/callbacks-cache/callbacks-cache', 'can-connect/data/parse/parse', 'can-connect/data/url/url', 'can-connect/real-time/real-time', 'can-connect/constructor/callbacks-once/callbacks-once', 'can-util/js/global/global' ], function (require, exports, module) { (function (global, require, exports, module) { var connect = require('can-connect'); var constructor = require('can-connect/constructor/constructor'); var canMap = require('can-connect/can/map/map'); var canRef = require('can-connect/can/ref/ref'); var constructorStore = require('can-connect/constructor/store/store'); var dataCallbacks = require('can-connect/data/callbacks/callbacks'); var callbacksCache = require('can-connect/data/callbacks-cache/callbacks-cache'); var dataParse = require('can-connect/data/parse/parse'); var dataUrl = require('can-connect/data/url/url'); var realTime = require('can-connect/real-time/real-time'); var callbacksOnce = require('can-connect/constructor/callbacks-once/callbacks-once'); var GLOBAL = require('can-util/js/global/global'); var $ = GLOBAL().$; connect.baseMap = function (options) { var behaviors = [ constructor, canMap, canRef, constructorStore, dataCallbacks, dataParse, dataUrl, realTime, callbacksOnce ]; if ($ && $.ajax) { options.ajax = $.ajax; } return connect(behaviors, options); }; module.exports = connect.baseMap; }(function () { return this; }(), require, exports, module)); }); /*can-connect@2.0.0-pre.12#all*/ define('can-connect/all', [ 'require', 'exports', 'module', 'can-connect', 'can-connect/cache-requests/cache-requests', 'can-connect/constructor/constructor', 'can-connect/constructor/callbacks-once/callbacks-once', 'can-connect/constructor/store/store', 'can-connect/data/callbacks/callbacks', 'can-connect/data/callbacks-cache/callbacks-cache', 'can-connect/data/combine-requests/combine-requests', 'can-connect/data/localstorage-cache/localstorage-cache', 'can-connect/data/memory-cache/memory-cache', 'can-connect/data/parse/parse', 'can-connect/data/url/url', 'can-connect/fall-through-cache/fall-through-cache', 'can-connect/real-time/real-time', 'can-connect/can/super-map/super-map', 'can-connect/can/tag/tag', 'can-connect/can/base-map/base-map' ], function (require, exports, module) { var connect = require('can-connect'); connect.cacheRequests = require('can-connect/cache-requests/cache-requests'); connect.constructor = require('can-connect/constructor/constructor'); connect.constructorCallbacksOnce = require('can-connect/constructor/callbacks-once/callbacks-once'); connect.constructorStore = require('can-connect/constructor/store/store'); connect.dataCallbacks = require('can-connect/data/callbacks/callbacks'); connect.dataCallbacksCache = require('can-connect/data/callbacks-cache/callbacks-cache'); connect.dataCombineRequests = require('can-connect/data/combine-requests/combine-requests'); connect.dataLocalStorageCache = require('can-connect/data/localstorage-cache/localstorage-cache'); connect.dataMemoryCache = require('can-connect/data/memory-cache/memory-cache'); connect.dataParse = require('can-connect/data/parse/parse'); connect.dataUrl = require('can-connect/data/url/url'); connect.fallThroughCache = require('can-connect/fall-through-cache/fall-through-cache'); connect.realTime = require('can-connect/real-time/real-time'); connect.superMap = require('can-connect/can/super-map/super-map'); connect.tag = require('can-connect/can/tag/tag'); connect.baseMap = require('can-connect/can/base-map/base-map'); module.exports = connect; }); /*can-define@2.0.0-pre.19#define-helpers/define-helpers*/ define('can-define/define-helpers/define-helpers', [ 'require', 'exports', 'module', 'can-define', 'can-reflect', 'can-queues' ], function (require, exports, module) { var define = require('can-define'); var canReflect = require('can-reflect'); var queues = require('can-queues'); var defineHelpers = { defineExpando: function (map, prop, value) { var constructorDefines = map._define.definitions; if (constructorDefines && constructorDefines[prop]) { return; } var instanceDefines = map._instanceDefinitions; if (!instanceDefines) { Object.defineProperty(map, '_instanceDefinitions', { configurable: true, enumerable: false, value: {} }); instanceDefines = map._instanceDefinitions; } if (!instanceDefines[prop]) { var defaultDefinition = map._define.defaultDefinition || { type: define.types.observable }; define.property(map, prop, defaultDefinition, {}, {}); map._data[prop] = defaultDefinition.type ? defaultDefinition.type(value) : define.types.observable(value); instanceDefines[prop] = defaultDefinition; queues.batch.start(); map.dispatch({ type: '__keys', target: map }); if (map._data[prop] !== undefined) { map.dispatch({ type: prop, target: map, patches: [{ type: 'set', key: prop, value: map._data[prop] }] }, [ map._data[prop], undefined ]); } queues.batch.stop(); return true; } }, reflectSerialize: function (unwrapped) { var constructorDefinitions = this._define.definitions; var defaultDefinition = this._define.defaultDefinition; this.each(function (val, name) { var propDef = constructorDefinitions[name]; if (propDef && typeof propDef.serialize === 'function') { val = propDef.serialize.call(this, val, name); } else if (defaultDefinition && typeof defaultDefinition.serialize === 'function') { val = defaultDefinition.serialize.call(this, val, name); } else { val = canReflect.serialize(val); } if (val !== undefined) { unwrapped[name] = val; } }, this); return unwrapped; }, reflectUnwrap: function (unwrapped) { this.forEach(function (value, key) { if (value !== undefined) { unwrapped[key] = canReflect.unwrap(value); } }); return unwrapped; } }; module.exports = defineHelpers; }); /*can-util@3.10.18#js/cid-set/cid-set*/ define('can-util/js/cid-set/cid-set', [ 'require', 'exports', 'module', 'can-cid/set/set' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; module.exports = require('can-cid/set/set'); }(function () { return this; }(), require, exports, module)); }); /*can-define@2.0.0-pre.19#ensure-meta*/ define('can-define/ensure-meta', [ 'require', 'exports', 'module', 'can-symbol', 'can-reflect' ], function (require, exports, module) { var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); module.exports = function ensureMeta(obj) { var metaSymbol = canSymbol.for('can.meta'); var meta = obj[metaSymbol]; if (!meta) { meta = {}; canReflect.setKeyValue(obj, metaSymbol, meta); } return meta; }; }); /*can-define@2.0.0-pre.19#map/map*/ define('can-define/map/map', [ 'require', 'exports', 'module', 'can-construct', 'can-define', 'can-define/define-helpers/define-helpers', 'can-observation-recorder', 'can-namespace', 'can-log', 'can-log/dev/dev', 'can-reflect', 'can-symbol', 'can-util/js/cid-set/cid-set', 'can-util/js/cid-map/cid-map', 'can-queues', 'can-define/ensure-meta', 'can-log/dev/dev', 'can-event-queue/type/type' ], function (require, exports, module) { var Construct = require('can-construct'); var define = require('can-define'); var defineHelpers = require('can-define/define-helpers/define-helpers'); var ObservationRecorder = require('can-observation-recorder'); var ns = require('can-namespace'); var canLog = require('can-log'); var canLogDev = require('can-log/dev/dev'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var CIDSet = require('can-util/js/cid-set/cid-set'); var CIDMap = require('can-util/js/cid-map/cid-map'); var queues = require('can-queues'); var ensureMeta = require('can-define/ensure-meta'); var dev = require('can-log/dev/dev'); var addTypeEvents = require('can-event-queue/type/type'); var keysForDefinition = function (definitions) { var keys = []; for (var prop in definitions) { var definition = definitions[prop]; if (typeof definition !== 'object' || ('serialize' in definition ? !!definition.serialize : !definition.get)) { keys.push(prop); } } return keys; }; function assign(source) { queues.batch.start(); canReflect.assignMap(this, source || {}); queues.batch.stop(); } function update(source) { queues.batch.start(); canReflect.updateMap(this, source || {}); queues.batch.stop(); } function assignDeep(source) { queues.batch.start(); canReflect.assignDeepMap(this, source || {}); queues.batch.stop(); } function updateDeep(source) { queues.batch.start(); canReflect.updateDeepMap(this, source || {}); queues.batch.stop(); } function setKeyValue(key, value) { var defined = defineHelpers.defineExpando(this, key, value); if (!defined) { this[key] = value; } } function getKeyValue(key) { var value = this[key]; if (value !== undefined || key in this || Object.isSealed(this)) { return value; } else { ObservationRecorder.add(this, key); return this[key]; } } var DefineMap = Construct.extend('DefineMap', { setup: function (base) { var key, prototype = this.prototype; if (DefineMap) { var result = define(prototype, prototype, base.prototype._define); define.makeDefineInstanceKey(this, result); addTypeEvents(this); for (key in DefineMap.prototype) { define.defineConfigurableAndNotEnumerable(prototype, key, prototype[key]); } this.prototype.setup = function (props) { define.setup.call(this, props || {}, this.constructor.seal); }; } else { for (key in prototype) { define.defineConfigurableAndNotEnumerable(prototype, key, prototype[key]); } } define.defineConfigurableAndNotEnumerable(prototype, 'constructor', this); } }, { setup: function (props, sealed) { if (!this._define) { Object.defineProperty(this, '_define', { enumerable: false, value: { definitions: {} } }); Object.defineProperty(this, '_data', { enumerable: false, value: {} }); } define.setup.call(this, props || {}, sealed === true); }, get: function (prop) { if (prop) { return getKeyValue.call(this, prop); } else { return canReflect.unwrap(this, CIDMap); } }, set: function (prop, value) { if (typeof prop === 'object') { canLogDev.warn('can-define/map/map.prototype.set is deprecated; please use can-define/map/map.prototype.assign or can-define/map/map.prototype.update instead'); if (value === true) { updateDeep.call(this, prop); } else { assignDeep.call(this, prop); } } else { setKeyValue.call(this, prop, value); } return this; }, assignDeep: function (prop) { assignDeep.call(this, prop); return this; }, updateDeep: function (prop) { updateDeep.call(this, prop); return this; }, assign: function (prop) { assign.call(this, prop); return this; }, update: function (prop) { update.call(this, prop); return this; }, serialize: function () { return canReflect.serialize(this, CIDMap); }, forEach: function () { var forEach = function (list, cb, thisarg) { return canReflect.eachKey(list, cb, thisarg); }, noObserve = ObservationRecorder.ignore(forEach); return function (cb, thisarg, observe) { return observe === false ? noObserve(this, cb, thisarg) : forEach(this, cb, thisarg); }; }(), '*': { type: define.types.observable }, log: function (key) { var instance = this; var quoteString = function quoteString(x) { return typeof x === 'string' ? JSON.stringify(x) : x; }; var meta = ensureMeta(instance); var allowed = meta.allowedLogKeysSet || new Set(); meta.allowedLogKeysSet = allowed; if (key) { allowed.add(key); } meta._log = function (event, data) { var type = event.type; if (type === '__keys' || key && !allowed.has(type)) { return; } dev.log(canReflect.getName(instance), '\n key ', quoteString(type), '\n is ', quoteString(data[0]), '\n was ', quoteString(data[1])); }; } }); canReflect.assignSymbols(DefineMap.prototype, { 'can.isMapLike': true, 'can.isListLike': false, 'can.isValueLike': false, 'can.getKeyValue': getKeyValue, 'can.setKeyValue': setKeyValue, 'can.deleteKeyValue': function (prop) { this.set(prop, undefined); return this; }, 'can.getOwnEnumerableKeys': function () { ObservationRecorder.add(this, '__keys'); return keysForDefinition(this._define.definitions).concat(keysForDefinition(this._instanceDefinitions)); }, 'can.assignDeep': assignDeep, 'can.updateDeep': updateDeep, 'can.unwrap': defineHelpers.reflectUnwrap, 'can.serialize': defineHelpers.reflectSerialize, 'can.keyHasDependencies': function (key) { return !!(this._computed && this._computed[key] && this._computed[key].compute); }, 'can.getKeyDependencies': function (key) { var ret; if (this._computed && this._computed[key] && this._computed[key].compute) { ret = {}; ret.valueDependencies = new CIDSet(); ret.valueDependencies.add(this._computed[key].compute); } return ret; }, 'can.getName': function () { return canReflect.getName(this.constructor) + '{}'; } }); canReflect.setKeyValue(DefineMap.prototype, canSymbol.iterator, function () { return new define.Iterator(this); }); for (var prop in define.eventsProto) { DefineMap[prop] = define.eventsProto[prop]; Object.defineProperty(DefineMap.prototype, prop, { enumerable: false, value: define.eventsProto[prop], writable: true }); } var eventsProtoSymbols = 'getOwnPropertySymbols' in Object ? Object.getOwnPropertySymbols(define.eventsProto) : [ canSymbol.for('can.onKeyValue'), canSymbol.for('can.offKeyValue') ]; eventsProtoSymbols.forEach(function (sym) { Object.defineProperty(DefineMap.prototype, sym, { enumerable: false, value: define.eventsProto[sym], writable: true }); }); define.DefineMap = DefineMap; Object.defineProperty(DefineMap.prototype, 'toObject', { enumerable: false, writable: true, value: function () { canLog.warn('Use DefineMap::get instead of DefineMap::toObject'); return this.get(); } }); Object.defineProperty(DefineMap.prototype, 'each', { enumerable: false, writable: true, value: DefineMap.prototype.forEach }); module.exports = ns.DefineMap = DefineMap; }); /*can-define@2.0.0-pre.19#list/list*/ define('can-define/list/list', [ 'require', 'exports', 'module', 'can-construct', 'can-define', 'can-queues', 'can-event-queue/type/type', 'can-observation-recorder', 'can-log', 'can-log/dev/dev', 'can-define/define-helpers/define-helpers', 'can-log/dev/dev', 'can-define/ensure-meta', 'can-util/js/assign/assign', 'can-util/js/diff/diff', 'can-util/js/each/each', 'can-util/js/make-array/make-array', 'can-namespace', 'can-reflect', 'can-symbol', 'can-util/js/cid-set/cid-set', 'can-util/js/cid-map/cid-map', 'can-util/js/single-reference/single-reference' ], function (require, exports, module) { var Construct = require('can-construct'); var define = require('can-define'); var make = define.make; var queues = require('can-queues'); var addTypeEvents = require('can-event-queue/type/type'); var ObservationRecorder = require('can-observation-recorder'); var canLog = require('can-log'); var canLogDev = require('can-log/dev/dev'); var defineHelpers = require('can-define/define-helpers/define-helpers'); var dev = require('can-log/dev/dev'); var ensureMeta = require('can-define/ensure-meta'); var assign = require('can-util/js/assign/assign'); var diff = require('can-util/js/diff/diff'); var each = require('can-util/js/each/each'); var makeArray = require('can-util/js/make-array/make-array'); var ns = require('can-namespace'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var CIDSet = require('can-util/js/cid-set/cid-set'); var CIDMap = require('can-util/js/cid-map/cid-map'); var singleReference = require('can-util/js/single-reference/single-reference'); var splice = [].splice; var runningNative = false; var identity = function (x) { return x; }; var localOnPatchesSymbol = 'can.onPatches'; var makeFilterCallback = function (props) { return function (item) { for (var prop in props) { if (item[prop] !== props[prop]) { return false; } } return true; }; }; var onKeyValue = define.eventsProto[canSymbol.for('can.onKeyValue')]; var offKeyValue = define.eventsProto[canSymbol.for('can.offKeyValue')]; var DefineList = Construct.extend('DefineList', { setup: function (base) { if (DefineList) { addTypeEvents(this); var prototype = this.prototype; var result = define(prototype, prototype, base.prototype._define); define.makeDefineInstanceKey(this, result); var itemsDefinition = result.definitions['#'] || result.defaultDefinition; if (itemsDefinition) { if (itemsDefinition.Type) { this.prototype.__type = make.set.Type('*', itemsDefinition.Type, identity); } else if (itemsDefinition.type) { this.prototype.__type = make.set.type('*', itemsDefinition.type, identity); } } } } }, { setup: function (items) { if (!this._define) { Object.defineProperty(this, '_define', { enumerable: false, value: { definitions: { length: { type: 'number' }, _length: { type: 'number' } } } }); Object.defineProperty(this, '_data', { enumerable: false, value: {} }); } define.setup.call(this, {}, false); Object.defineProperty(this, '_length', { enumerable: false, configurable: true, writable: true, value: 0 }); if (items) { this.splice.apply(this, [ 0, 0 ].concat(canReflect.toArray(items))); } }, __type: define.types.observable, _triggerChange: function (attr, how, newVal, oldVal) { var index = +attr; if (!isNaN(index)) { var itemsDefinition = this._define.definitions['#']; var patches; if (how === 'add') { if (itemsDefinition && typeof itemsDefinition.added === 'function') { ObservationRecorder.ignore(itemsDefinition.added).call(this, newVal, index); } queues.batch.start(); patches = [{ type: 'splice', insert: newVal, index: index, deleteCount: 0 }]; this.dispatch({ type: how, patches: patches, reasonLog: [ canReflect.getName(this), 'added', JSON.stringify(newVal), 'at', index ] }, [ newVal, index ]); this.dispatch(localOnPatchesSymbol, [patches]); queues.batch.stop(); } else if (how === 'remove') { if (itemsDefinition && typeof itemsDefinition.removed === 'function') { ObservationRecorder.ignore(itemsDefinition.removed).call(this, oldVal, index); } queues.batch.start(); patches = [{ type: 'splice', index: index, deleteCount: oldVal.length }]; this.dispatch({ type: how, patches: patches, reasonLog: [ canReflect.getName(this), 'remove', JSON.stringify(oldVal), 'at', index ] }, [ oldVal, index ]); this.dispatch(localOnPatchesSymbol, [patches]); queues.batch.stop(); } else { this.dispatch(how, [ newVal, index ]); } } else { this.dispatch({ type: '' + attr, target: this }, [ newVal, oldVal ]); } }, get: function (index) { if (arguments.length) { if (isNaN(index)) { ObservationRecorder.add(this, index); } else { ObservationRecorder.add(this, 'length'); } return this[index]; } else { return canReflect.unwrap(this, CIDMap); } }, set: function (prop, value) { if (typeof prop !== 'object') { prop = isNaN(+prop) || prop % 1 ? prop : +prop; if (typeof prop === 'number') { if (typeof prop === 'number' && prop > this._length - 1) { var newArr = new Array(prop + 1 - this._length); newArr[newArr.length - 1] = value; this.push.apply(this, newArr); return newArr; } this.splice(prop, 1, value); } else { var defined = defineHelpers.defineExpando(this, prop, value); if (!defined) { this[prop] = value; } } } else { canLogDev.warn('can-define/list/list.prototype.set is deprecated; please use can-define/list/list.prototype.assign or can-define/list/list.prototype.update instead'); if (canReflect.isListLike(prop)) { if (value) { this.replace(prop); } else { canReflect.assignList(this, prop); } } else { canReflect.assignMap(this, prop); } } return this; }, assign: function (prop) { if (canReflect.isListLike(prop)) { canReflect.assignList(this, prop); } else { canReflect.assignMap(this, prop); } return this; }, update: function (prop) { if (canReflect.isListLike(prop)) { canReflect.updateList(this, prop); } else { canReflect.updateMap(this, prop); } return this; }, assignDeep: function (prop) { if (canReflect.isListLike(prop)) { canReflect.assignDeepList(this, prop); } else { canReflect.assignDeepMap(this, prop); } return this; }, updateDeep: function (prop) { if (canReflect.isListLike(prop)) { canReflect.updateDeepList(this, prop); } else { canReflect.updateDeepMap(this, prop); } return this; }, _items: function () { var arr = []; this._each(function (item) { arr.push(item); }); return arr; }, _each: function (callback) { for (var i = 0, len = this._length; i < len; i++) { callback(this[i], i); } }, splice: function (index, howMany) { var args = makeArray(arguments), added = [], i, len, listIndex, allSame = args.length > 2, oldLength = this._length; index = index || 0; for (i = 0, len = args.length - 2; i < len; i++) { listIndex = i + 2; args[listIndex] = this.__type(args[listIndex], listIndex); added.push(args[listIndex]); if (this[i + index] !== args[listIndex]) { allSame = false; } } if (allSame && this._length <= added.length) { return added; } if (howMany === undefined) { howMany = args[1] = this._length - index; } runningNative = true; var removed = splice.apply(this, args); runningNative = false; queues.batch.start(); if (howMany > 0) { this._triggerChange('' + index, 'remove', undefined, removed); } if (args.length > 2) { this._triggerChange('' + index, 'add', added, removed); } this.dispatch('length', [ this._length, oldLength ]); queues.batch.stop(); return removed; }, serialize: function () { return canReflect.serialize(this, CIDMap); }, log: function (key) { var instance = this; var quoteString = function quoteString(x) { return typeof x === 'string' ? JSON.stringify(x) : x; }; var meta = ensureMeta(instance); var allowed = meta.allowedLogKeysSet || new Set(); meta.allowedLogKeysSet = allowed; if (key) { allowed.add(key); } meta._log = function (event, data) { var type = event.type; if (type === 'can.onPatches' || key && !allowed.has(type)) { return; } if (type === 'add' || type === 'remove') { dev.log(canReflect.getName(instance), '\n how ', quoteString(type), '\n what ', quoteString(data[0]), '\n index ', quoteString(data[1])); } else { dev.log(canReflect.getName(instance), '\n key ', quoteString(type), '\n is ', quoteString(data[0]), '\n was ', quoteString(data[1])); } }; } }); var getArgs = function (args) { return args[0] && Array.isArray(args[0]) ? args[0] : makeArray(args); }; each({ push: 'length', unshift: 0 }, function (where, name) { var orig = [][name]; DefineList.prototype[name] = function () { var args = [], len = where ? this._length : 0, i = arguments.length, res, val; while (i--) { val = arguments[i]; args[i] = this.__type(val, i); } runningNative = true; res = orig.apply(this, args); runningNative = false; if (!this.comparator || args.length) { queues.batch.start(); this._triggerChange('' + len, 'add', args, undefined); this.dispatch('length', [ this._length, len ]); queues.batch.stop(); } return res; }; }); each({ pop: 'length', shift: 0 }, function (where, name) { var orig = [][name]; DefineList.prototype[name] = function () { if (!this._length) { return undefined; } var args = getArgs(arguments), len = where && this._length ? this._length - 1 : 0, oldLength = this._length ? this._length : 0, res; runningNative = true; res = orig.apply(this, args); runningNative = false; queues.batch.start(); this._triggerChange('' + len, 'remove', undefined, [res]); this.dispatch('length', [ this._length, oldLength ]); queues.batch.stop(); return res; }; }); each({ 'map': 3, 'filter': 3, 'reduce': 4, 'reduceRight': 4, 'every': 3, 'some': 3 }, function a(fnLength, fnName) { DefineList.prototype[fnName] = function () { var self = this; var args = [].slice.call(arguments, 0); var callback = args[0]; var thisArg = args[fnLength - 1] || self; if (typeof callback === 'object') { callback = makeFilterCallback(callback); } args[0] = function () { var cbArgs = [].slice.call(arguments, 0); cbArgs[fnLength - 3] = self.get(cbArgs[fnLength - 2]); return callback.apply(thisArg, cbArgs); }; var ret = Array.prototype[fnName].apply(this, args); if (fnName === 'map') { return new DefineList(ret); } else if (fnName === 'filter') { return new self.constructor(ret); } else { return ret; } }; }); assign(DefineList.prototype, { indexOf: function (item, fromIndex) { for (var i = fromIndex || 0, len = this.length; i < len; i++) { if (this.get(i) === item) { return i; } } return -1; }, lastIndexOf: function (item, fromIndex) { fromIndex = typeof fromIndex === 'undefined' ? this.length - 1 : fromIndex; for (var i = fromIndex; i >= 0; i--) { if (this.get(i) === item) { return i; } } return -1; }, join: function () { ObservationRecorder.add(this, 'length'); return [].join.apply(this, arguments); }, reverse: function () { var list = [].reverse.call(this._items()); return this.replace(list); }, slice: function () { ObservationRecorder.add(this, 'length'); var temp = Array.prototype.slice.apply(this, arguments); return new this.constructor(temp); }, concat: function () { var args = []; each(arguments, function (arg) { if (canReflect.isListLike(arg)) { var arr = Array.isArray(arg) ? arg : makeArray(arg); arr.forEach(function (innerArg) { args.push(this.__type(innerArg)); }, this); } else { args.push(this.__type(arg)); } }, this); return new this.constructor(Array.prototype.concat.apply(makeArray(this), args)); }, forEach: function (cb, thisarg) { var item; for (var i = 0, len = this.length; i < len; i++) { item = this.get(i); if (cb.call(thisarg || item, item, i, this) === false) { break; } } return this; }, replace: function (newList) { var patches = diff(this, newList); queues.batch.start(); for (var i = 0, len = patches.length; i < len; i++) { this.splice.apply(this, [ patches[i].index, patches[i].deleteCount ].concat(patches[i].insert)); } queues.batch.stop(); return this; }, sort: function (compareFunction) { var removed = Array.prototype.slice.call(this); Array.prototype.sort.call(this, compareFunction); var added = Array.prototype.slice.call(this); queues.batch.start(); this.dispatch('remove', [ removed, 0 ]); this.dispatch('add', [ added, 0 ]); this.dispatch('length', [ this._length, this._length ]); queues.batch.stop(); return this; } }); for (var prop in define.eventsProto) { DefineList[prop] = define.eventsProto[prop]; Object.defineProperty(DefineList.prototype, prop, { enumerable: false, value: define.eventsProto[prop], writable: true }); } Object.defineProperty(DefineList.prototype, 'length', { get: function () { if (!this.__inSetup) { ObservationRecorder.add(this, 'length'); } return this._length; }, set: function (newVal) { if (runningNative) { this._length = newVal; return; } if (newVal == null || isNaN(+newVal) || newVal === this._length) { return; } if (newVal > this._length - 1) { var newArr = new Array(newVal - this._length); this.push.apply(this, newArr); } else { this.splice(newVal); } }, enumerable: true }); Object.defineProperty(DefineList.prototype, 'each', { enumerable: false, writable: true, value: DefineList.prototype.forEach }); DefineList.prototype.attr = function (prop, value) { canLog.warn('DefineMap::attr shouldn\'t be called'); if (arguments.length === 0) { return this.get(); } else if (prop && typeof prop === 'object') { return this.set.apply(this, arguments); } else if (arguments.length === 1) { return this.get(prop); } else { return this.set(prop, value); } }; DefineList.prototype.item = function (index, value) { if (arguments.length === 1) { return this.get(index); } else { return this.set(index, value); } }; DefineList.prototype.items = function () { canLog.warn('DefineList::get should should be used instead of DefineList::items'); return this.get(); }; canReflect.assignSymbols(DefineList.prototype, { 'can.isMoreListLikeThanMapLike': true, 'can.isMapLike': true, 'can.isListLike': true, 'can.isValueLike': false, 'can.getKeyValue': DefineList.prototype.get, 'can.setKeyValue': DefineList.prototype.set, 'can.onKeyValue': function (key, handler, queue) { var translationHandler; if (isNaN(key)) { return onKeyValue.apply(this, arguments); } else { translationHandler = function () { handler(this[key]); }; Object.defineProperty(translationHandler, 'name', { value: 'translationHandler(' + key + ')::' + canReflect.getName(this) + '.onKeyValue(\'length\',' + canReflect.getName(handler) + ')' }); singleReference.set(handler, this, translationHandler, key); return onKeyValue.call(this, 'length', translationHandler, queue); } }, 'can.offKeyValue': function (key, handler, queue) { var translationHandler; if (isNaN(key)) { return offKeyValue.apply(this, arguments); } else { translationHandler = singleReference.getAndDelete(handler, this, key); return offKeyValue.call(this, 'length', translationHandler, queue); } }, 'can.deleteKeyValue': function (prop) { prop = isNaN(+prop) || prop % 1 ? prop : +prop; if (typeof prop === 'number') { this.splice(prop, 1); } else if (prop === 'length' || prop === '_length') { return; } else { this.set(prop, undefined); } return this; }, 'can.assignDeep': function (source) { queues.batch.start(); canReflect.assignList(this, source); queues.batch.stop(); }, 'can.updateDeep': function (source) { queues.batch.start(); this.replace(source); queues.batch.stop(); }, 'can.keyHasDependencies': function (key) { return !!(this._computed && this._computed[key] && this._computed[key].compute); }, 'can.getKeyDependencies': function (key) { var ret; if (this._computed && this._computed[key] && this._computed[key].compute) { ret = {}; ret.valueDependencies = new CIDSet(); ret.valueDependencies.add(this._computed[key].compute); } return ret; }, 'can.splice': function (index, deleteCount, insert) { this.splice.apply(this, [ index, deleteCount ].concat(insert)); }, 'can.onPatches': function (handler, queue) { this[canSymbol.for('can.onKeyValue')](localOnPatchesSymbol, handler, queue); }, 'can.offPatches': function (handler, queue) { this[canSymbol.for('can.offKeyValue')](localOnPatchesSymbol, handler, queue); }, 'can.getName': function () { return canReflect.getName(this.constructor) + '[]'; } }); canReflect.setKeyValue(DefineList.prototype, canSymbol.iterator, function () { var index = -1; if (typeof this._length !== 'number') { this._length = 0; } return { next: function () { index++; return { value: this[index], done: index >= this._length }; }.bind(this) }; }); define.DefineList = DefineList; module.exports = ns.DefineList = DefineList; }); /*can-util@3.10.18#js/is-web-worker/is-web-worker*/ define('can-util/js/is-web-worker/is-web-worker', function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; module.exports = function () { return typeof WorkerGlobalScope !== 'undefined' && this instanceof WorkerGlobalScope; }; }(function () { return this; }(), require, exports, module)); }); /*can-util@3.10.18#js/is-browser-window/is-browser-window*/ define('can-util/js/is-browser-window/is-browser-window', [ 'require', 'exports', 'module', 'can-globals/is-browser-window/is-browser-window' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; module.exports = require('can-globals/is-browser-window/is-browser-window'); }(function () { return this; }(), require, exports, module)); }); /*can-simple-observable@2.0.0-pre.24#make-compute/make-compute*/ define('can-simple-observable/make-compute/make-compute', [ 'require', 'exports', 'module', 'can-reflect' ], function (require, exports, module) { var canReflect = require('can-reflect'); var Compute = function (newVal) { if (arguments.length) { return canReflect.setValue(this, newVal); } else { return canReflect.getValue(this); } }; var translationHelpers = new WeakMap(); module.exports = function (observable) { var compute = Compute.bind(observable); compute.on = compute.bind = compute.addEventListener = function (event, handler) { var translationHandler = translationHelpers.get(handler); if (!translationHandler) { translationHandler = function (newVal, oldVal) { handler.call(compute, { type: 'change' }, newVal, oldVal); }; Object.defineProperty(translationHandler, 'name', { value: 'translationHandler(' + event + ')::' + canReflect.getName(observable) + '.onValue(' + canReflect.getName(handler) + ')' }); translationHelpers.set(handler, translationHandler); } canReflect.onValue(observable, translationHandler); }; compute.off = compute.unbind = compute.removeEventListener = function (event, handler) { canReflect.offValue(observable, translationHelpers.get(handler)); }; canReflect.assignSymbols(compute, { 'can.getValue': function () { return canReflect.getValue(observable); }, 'can.setValue': function (newVal) { return canReflect.setValue(observable, newVal); }, 'can.onValue': function (handler, queue) { return canReflect.onValue(observable, handler, queue); }, 'can.offValue': function (handler, queue) { return canReflect.offValue(observable, handler, queue); }, 'can.valueHasDependencies': function () { return canReflect.valueHasDependencies(observable); }, 'can.getPriority': function () { return canReflect.getPriority(observable); }, 'can.setPriority': function (newPriority) { canReflect.setPriority(observable, newPriority); }, 'can.isValueLike': true, 'can.isFunctionLike': false }); compute.isComputed = true; return compute; }; }); /*can-util@3.10.18#js/diff-object/diff-object*/ define('can-util/js/diff-object/diff-object', [ 'require', 'exports', 'module', 'can-assign' ], function (require, exports, module) { 'use strict'; var assign = require('can-assign'); module.exports = exports = function (oldObject, newObject) { var oldObjectClone, patches = []; oldObjectClone = assign({}, oldObject); for (var newProp in newObject) { if (!oldObject || !oldObject.hasOwnProperty(newProp)) { patches.push({ property: newProp, type: 'add', value: newObject[newProp] }); } else if (newObject[newProp] !== oldObject[newProp]) { patches.push({ property: newProp, type: 'set', value: newObject[newProp] }); } delete oldObjectClone[newProp]; } for (var oldProp in oldObjectClone) { patches.push({ property: oldProp, type: 'remove' }); } return patches; }; }); /*can-route@4.0.0-pre.12#src/binding-proxy*/ define('can-route/src/binding-proxy', [ 'require', 'exports', 'module', 'can-util/js/make-array/make-array', 'can-symbol', 'can-simple-observable' ], function (require, exports, module) { var makeArray = require('can-util/js/make-array/make-array'); var canSymbol = require('can-symbol'); var SimpleObservable = require('can-simple-observable'); var defaultBinding = new SimpleObservable('hashchange'); var bindingProxy = { get defaultBinding() { return defaultBinding.get(); }, set defaultBinding(newVal) { defaultBinding.set(newVal); }, currentBinding: null, bindings: {}, call: function () { var args = makeArray(arguments), prop = args.shift(), binding = bindingProxy.bindings[bindingProxy.currentBinding || bindingProxy.defaultBinding], method = binding[prop.indexOf('can.') === 0 ? canSymbol.for(prop) : prop]; if (method.apply) { return method.apply(binding, args); } else { return method; } } }; module.exports = bindingProxy; }); /*can-route@4.0.0-pre.12#src/regexps*/ define('can-route/src/regexps', function (require, exports, module) { module.exports = { curlies: /\{\s*([\w.]+)\s*\}/g, colon: /\:([\w.]+)/g }; }); /*can-route@4.0.0-pre.12#src/register*/ define('can-route/src/register', [ 'require', 'exports', 'module', 'can-util/js/diff/diff', 'can-util/js/diff-object/diff-object', 'can-util/js/dev/dev', 'can-util/js/each/each', 'can-route/src/binding-proxy', 'can-route/src/regexps' ], function (require, exports, module) { var diff = require('can-util/js/diff/diff'); var diffObject = require('can-util/js/diff-object/diff-object'); var dev = require('can-util/js/dev/dev'); var each = require('can-util/js/each/each'); var bindingProxy = require('can-route/src/binding-proxy'); var regexps = require('can-route/src/regexps'); var removeBackslash = function (str) { return str.replace(/\\/g, ''); }; var wrapQuote = function (str) { return (str + '').replace(/([.?*+\^$\[\]\\(){}|\-])/g, '\\$1'); }; var RouteRegistry = { routes: {}, register: function registerRoute(url, defaults) { var root = bindingProxy.call('root'); if (root.lastIndexOf('/') === root.length - 1 && url.indexOf('/') === 0) { url = url.substr(1); } defaults = defaults || {}; var names = [], res, test = '', matcher, lastIndex, next, querySeparator = bindingProxy.call('querySeparator'), matchSlashes = bindingProxy.call('matchSlashes'); if (regexps.colon.test(url)) { matcher = regexps.colon; dev.warn('update route "' + url + '" to "' + url.replace(regexps.colon, function (name, key) { return '{' + key + '}'; }) + '"'); } else { matcher = regexps.curlies; } lastIndex = matcher.lastIndex = 0; while (res = matcher.exec(url)) { names.push(res[1]); test += removeBackslash(url.substring(lastIndex, matcher.lastIndex - res[0].length)); next = '\\' + (removeBackslash(url.substr(matcher.lastIndex, 1)) || querySeparator + (matchSlashes ? '' : '|/')); test += '([^' + next + ']' + (defaults[res[1]] ? '*' : '+') + ')'; lastIndex = matcher.lastIndex; } test += url.substr(lastIndex).replace('\\', ''); each(RouteRegistry.routes, function (r) { var existingKeys = r.names.concat(Object.keys(r.defaults)).sort(); var keys = names.concat(Object.keys(defaults)).sort(); var sameMapKeys = !diff(existingKeys, keys).length; var sameDefaultValues = !diffObject(r.defaults, defaults).length; var matchingRoutesWithoutTrailingSlash = r.route.replace(/\/$/, '') === url.replace(/\/$/, ''); if (sameMapKeys && sameDefaultValues && !matchingRoutesWithoutTrailingSlash) { dev.warn('two routes were registered with matching keys:\n' + '\t(1) route("' + r.route + '", ' + JSON.stringify(r.defaults) + ')\n' + '\t(2) route("' + url + '", ' + JSON.stringify(defaults) + ')\n' + '(1) will always be chosen since it was registered first'); } }); return RouteRegistry.routes[url] = { test: new RegExp('^' + test + '($|' + wrapQuote(querySeparator) + ')'), route: url, names: names, defaults: defaults, length: url.split('/').length }; } }; module.exports = RouteRegistry; }); /*can-deparam@1.0.3#can-deparam*/ define('can-deparam', [ 'require', 'exports', 'module', 'can-namespace' ], function (require, exports, module) { var namespace = require('can-namespace'); var digitTest = /^\d+$/, keyBreaker = /([^\[\]]+)|(\[\])/g, paramTest = /([^?#]*)(#.*)?$/, entityRegex = /%([^0-9a-f][0-9a-f]|[0-9a-f][^0-9a-f]|[^0-9a-f][^0-9a-f])/i, prep = function (str) { str = str.replace(/\+/g, ' '); try { return decodeURIComponent(str); } catch (e) { return decodeURIComponent(str.replace(entityRegex, function (match, hex) { return '%25' + hex; })); } }; module.exports = namespace.deparam = function (params) { var data = {}, pairs, lastPart; if (params && paramTest.test(params)) { pairs = params.split('&'); pairs.forEach(function (pair) { var parts = pair.split('='), key = prep(parts.shift()), value = prep(parts.join('=')), current = data; if (key) { parts = key.match(keyBreaker); for (var j = 0, l = parts.length - 1; j < l; j++) { if (!current[parts[j]]) { current[parts[j]] = digitTest.test(parts[j + 1]) || parts[j + 1] === '[]' ? [] : {}; } current = current[parts[j]]; } lastPart = parts.pop(); if (lastPart === '[]') { current.push(value); } else { current[lastPart] = value; } } }); } return data; }; }); /*can-route@4.0.0-pre.12#src/deparam*/ define('can-route/src/deparam', [ 'require', 'exports', 'module', 'can-deparam', 'can-util/js/each/each', 'can-util/js/deep-assign/deep-assign', 'can-route/src/binding-proxy', 'can-route/src/register' ], function (require, exports, module) { var deparam = require('can-deparam'); var each = require('can-util/js/each/each'); var deepAssign = require('can-util/js/deep-assign/deep-assign'); var bindingProxy = require('can-route/src/binding-proxy'); var register = require('can-route/src/register'); var decode = function (str) { try { return decodeURIComponent(str); } catch (ex) { return unescape(str); } }; module.exports = function canRoute_deparam(url) { var root = bindingProxy.call('root'); if (root.lastIndexOf('/') === root.length - 1 && url.indexOf('/') === 0) { url = url.substr(1); } var route = { length: -1 }, querySeparator = bindingProxy.call('querySeparator'), paramsMatcher = bindingProxy.call('paramsMatcher'); each(register.routes, function (temp, name) { if (temp.test.test(url) && temp.length > route.length) { route = temp; } }); if (route.length > -1) { var parts = url.match(route.test), start = parts.shift(), remainder = url.substr(start.length - (parts[parts.length - 1] === querySeparator ? 1 : 0)), obj = remainder && paramsMatcher.test(remainder) ? deparam(remainder.slice(1)) : {}; obj = deepAssign(true, {}, route.defaults, obj); each(parts, function (part, i) { if (part && part !== querySeparator) { obj[route.names[i]] = decode(part); } }); obj.route = route.route; return obj; } if (url.charAt(0) !== querySeparator) { url = querySeparator + url; } return paramsMatcher.test(url) ? deparam(url.slice(1)) : {}; }; }); /*can-route@4.0.0-pre.12#src/param*/ define('can-route/src/param', [ 'require', 'exports', 'module', 'can-util/js/each/each', 'can-util/js/assign/assign', 'can-util/js/is-empty-object/is-empty-object', 'can-param', 'can-route/src/register', 'can-route/src/regexps', 'can-route/src/binding-proxy' ], function (require, exports, module) { var each = require('can-util/js/each/each'); var assign = require('can-util/js/assign/assign'); var isEmptyObject = require('can-util/js/is-empty-object/is-empty-object'); var param = require('can-param'); var register = require('can-route/src/register'); var regexps = require('can-route/src/regexps'); var bindingProxy = require('can-route/src/binding-proxy'); var matchesData = function (route, data) { var count = 0, i = 0, defaults = {}; for (var name in route.defaults) { if (route.defaults[name] === data[name]) { defaults[name] = 1; count++; } } for (; i < route.names.length; i++) { if (!data.hasOwnProperty(route.names[i])) { return -1; } if (!defaults[route.names[i]]) { count++; } } return count; }; function getMatchedRoute(data) { var route, matches = 0, matchCount, routeName = data.route, propCount = 0; delete data.route; each(data, function () { propCount++; }); each(register.routes, function (temp, name) { matchCount = matchesData(temp, data); if (matchCount > matches) { route = temp; matches = matchCount; } if (matchCount >= propCount) { return false; } }); if (register.routes[routeName] && matchesData(register.routes[routeName], data) === matches) { route = register.routes[routeName]; } return route; } function paramFromRoute(route, data) { var cpy, res, after, matcher; if (route) { cpy = assign({}, data); matcher = regexps.colon.test(route.route) ? regexps.colon : regexps.curlies; res = route.route.replace(matcher, function (whole, name) { delete cpy[name]; return data[name] === route.defaults[name] ? '' : encodeURIComponent(data[name]); }).replace('\\', ''); each(route.defaults, function (val, name) { if (cpy[name] === val) { delete cpy[name]; } }); after = param(cpy); return res + (after ? bindingProxy.call('querySeparator') + after : ''); } return isEmptyObject(data) ? '' : bindingProxy.call('querySeparator') + param(data); } function canRoute_param(data) { return paramFromRoute(getMatchedRoute(data), data); } module.exports = canRoute_param; canRoute_param.paramFromRoute = paramFromRoute; canRoute_param.getMatchedRoute = getMatchedRoute; }); /*can-route@4.0.0-pre.12#src/url-helpers*/ define('can-route/src/url-helpers', [ 'require', 'exports', 'module', 'can-route/src/binding-proxy', 'can-route/src/deparam', 'can-route/src/param', 'can-util/js/assign/assign', 'can-util/js/each/each', 'can-util/js/string/string' ], function (require, exports, module) { var bindingProxy = require('can-route/src/binding-proxy'); var routeDeparam = require('can-route/src/deparam'); var routeParam = require('can-route/src/param'); var assign = require('can-util/js/assign/assign'); var each = require('can-util/js/each/each'); var string = require('can-util/js/string/string'); var makeProps = function (props) { var tags = []; each(props, function (val, name) { tags.push((name === 'className' ? 'class' : name) + '="' + (name === 'href' ? val : string.esc(val)) + '"'); }); return tags.join(' '); }; var matchCheck = function (source, matcher) { for (var prop in source) { var s = source[prop], m = matcher[prop]; if (s && m && typeof s === 'object' && typeof matcher === 'object') { return matchCheck(s, m); } if (s != m) { return false; } } return true; }; function canRoute_url(options, merge) { if (merge) { var baseOptions = routeDeparam(bindingProxy.call('can.getValue')); options = assign(assign({}, baseOptions), options); } return bindingProxy.call('root') + routeParam(options); } module.exports = { url: canRoute_url, link: function canRoute_link(name, options, props, merge) { return '<a ' + makeProps(assign({ href: canRoute_url(options, merge) }, props)) + '>' + name + '</a>'; }, current: function canRoute_current(options, subsetMatch) { if (subsetMatch) { var baseOptions = routeDeparam(bindingProxy.call('can.getValue')); return matchCheck(options, baseOptions); } else { return bindingProxy.call('can.getValue') === routeParam(options); } } }; }); /*can-globals@0.3.0#location/location*/ define('can-globals/location/location', [ 'require', 'exports', 'module', 'can-globals/global/global', 'can-globals/can-globals-instance' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; require('can-globals/global/global'); var globals = require('can-globals/can-globals-instance'); globals.define('location', function () { return globals.getKeyValue('global').location; }); module.exports = globals.makeExport('location'); }(function () { return this; }(), require, exports, module)); }); /*can-route@4.0.0-pre.12#src/hashchange*/ define('can-route/src/hashchange', [ 'require', 'exports', 'module', 'can-globals/location/location', 'can-reflect', 'can-util/dom/events/events', 'can-observation-recorder', 'can-queues', 'can-key-tree', 'can-simple-observable' ], function (require, exports, module) { (function (global, require, exports, module) { var paramsMatcher = /^(?:&[^=]+=[^&]*)+/; var LOCATION = require('can-globals/location/location'); var canReflect = require('can-reflect'); var domEvents = require('can-util/dom/events/events'); var ObservationRecorder = require('can-observation-recorder'); var queues = require('can-queues'); var KeyTree = require('can-key-tree'); var SimpleObservable = require('can-simple-observable'); function getHash() { var loc = LOCATION(); return loc.href.split(/#!?/)[1] || ''; } function HashchangeObservable() { var dispatchHandlers = this.dispatchHandlers.bind(this); var self = this; this.handlers = new KeyTree([ Object, Array ], { onFirst: function () { self.value = getHash(); domEvents.addEventListener.call(window, 'hashchange', dispatchHandlers); }, onEmpty: function () { domEvents.removeEventListener.call(window, 'hashchange', dispatchHandlers); } }); } HashchangeObservable.prototype = Object.create(SimpleObservable.prototype); HashchangeObservable.constructor = HashchangeObservable; canReflect.assign(HashchangeObservable.prototype, { paramsMatcher: paramsMatcher, querySeparator: '&', matchSlashes: false, root: '#!', dispatchHandlers: function () { var old = this.value; this.value = getHash(); if (old !== this.value) { queues.enqueueByQueue(this.handlers.getNode([]), this, [ this.value, old ], null, [ canReflect.getName(this), 'changed to', this.value, 'from', old ]); } }, get: function () { ObservationRecorder.add(this); return getHash(); }, set: function (path) { var loc = LOCATION(); if (loc.hash !== '#' + path) { loc.hash = '!' + path; } return path; } }); canReflect.assignSymbols(HashchangeObservable.prototype, { 'can.getValue': HashchangeObservable.prototype.get, 'can.setValue': HashchangeObservable.prototype.set, 'can.onValue': HashchangeObservable.prototype.on, 'can.offValue': HashchangeObservable.prototype.off, 'can.isMapLike': false, 'can.valueHasDependencies': function () { return true; }, 'can.getName': function () { return 'HashchangeObservable<' + this.value + '>'; } }); module.exports = new HashchangeObservable(); }(function () { return this; }(), require, exports, module)); }); /*can-route@4.0.0-pre.12#can-route*/ define('can-route', [ 'require', 'exports', 'module', 'can-queues', 'can-observation', 'can-namespace', 'can-util/js/each/each', 'can-util/js/is-function/is-function', 'can-util/js/is-web-worker/is-web-worker', 'can-util/js/is-browser-window/is-browser-window', 'can-util/js/assign/assign', 'can-util/js/dev/dev', 'can-reflect', 'can-symbol', 'can-simple-observable/make-compute/make-compute', 'can-simple-map', 'can-route/src/register', 'can-route/src/url-helpers', 'can-route/src/param', 'can-route/src/deparam', 'can-route/src/binding-proxy', 'can-route/src/hashchange' ], function (require, exports, module) { var queues = require('can-queues'); var Observation = require('can-observation'); var namespace = require('can-namespace'); var each = require('can-util/js/each/each'); var isFunction = require('can-util/js/is-function/is-function'); var isWebWorker = require('can-util/js/is-web-worker/is-web-worker'); var isBrowserWindow = require('can-util/js/is-browser-window/is-browser-window'); var assign = require('can-util/js/assign/assign'); var dev = require('can-util/js/dev/dev'); var canReflect = require('can-reflect'); var canSymbol = require('can-symbol'); var makeCompute = require('can-simple-observable/make-compute/make-compute'); var SimpleMap = require('can-simple-map'); var registerRoute = require('can-route/src/register'); var urlHelpers = require('can-route/src/url-helpers'); var routeParam = require('can-route/src/param'); var routeDeparam = require('can-route/src/deparam'); var bindingProxy = require('can-route/src/binding-proxy'); var hashchange = require('can-route/src/hashchange'); bindingProxy.bindings.hashchange = hashchange; bindingProxy.defaultBinding = 'hashchange'; function canRoute(url, defaults) { registerRoute.register(url, defaults); return canRoute; } var timer; var matchedObservable = new Observation(function canRoute_matchedRoute() { var url = bindingProxy.call('can.getValue'); return canRoute.deparam(url).route; }); function updateUrl(serializedData) { clearTimeout(timer); timer = setTimeout(function () { var serialized = canReflect.serialize(canRoute.data), route = routeParam.getMatchedRoute(serialized), path = routeParam.paramFromRoute(route, serialized); bindingProxy.call('can.setValue', path); }, 10); } Object.defineProperty(updateUrl, 'name', { value: 'can-route.updateUrl' }); function updateRouteData() { var hash = bindingProxy.call('can.getValue'); queues.batch.start(); var state = canRoute.deparam(hash); delete state.route; canReflect.update(canRoute.data, state); queues.batch.stop(); } Object.defineProperty(updateRouteData, 'name', { value: 'can-route.updateRouteData' }); Object.defineProperty(canRoute, 'routes', { get: function () { return registerRoute.routes; }, set: function (newVal) { return registerRoute.routes = newVal; } }); Object.defineProperty(canRoute, 'defaultBinding', { get: function () { return bindingProxy.defaultBinding; }, set: function (newVal) { bindingProxy.defaultBinding = newVal; } }); Object.defineProperty(canRoute, 'currentBinding', { get: function () { return bindingProxy.currentBinding; }, set: function (newVal) { bindingProxy.currentBinding = newVal; } }); assign(canRoute, { param: routeParam, deparam: routeDeparam, map: function (data) { dev.warn('Set route.data directly instead of calling route.map'); canRoute.data = data; }, ready: function (val) { dev.warn('Use can-route.start() instead of can-route.ready()'); canRoute.start(); }, start: function (val) { if (val !== true) { canRoute._setup(); if (isBrowserWindow() || isWebWorker()) { var hash = bindingProxy.call('can.getValue'); queues.batch.start(); var state = canRoute.deparam(hash); delete state.route; canReflect.assign(canRoute.data, state); queues.batch.stop(); } } return canRoute; }, url: urlHelpers.url, link: urlHelpers.link, current: urlHelpers.current, bindings: bindingProxy.bindings, _setup: function () { if (!canRoute.currentBinding) { bindingProxy.call('can.onValue', updateRouteData); canReflect.onValue(canRoute.serializedObservation, updateUrl, 'notify'); canRoute.currentBinding = canRoute.defaultBinding; } }, _teardown: function () { if (canRoute.currentBinding) { bindingProxy.call('can.offValue', updateRouteData); canReflect.offValue(canRoute.serializedObservation, updateUrl, 'notify'); canRoute.currentBinding = null; } clearTimeout(timer); }, matched: makeCompute(matchedObservable) }); var bindToCanRouteData = function (name, args) { if (!canRoute.data[name]) { return canRoute.data.addEventListener.apply(canRoute.data, args); } return canRoute.data[name].apply(canRoute.data, args); }; each([ 'addEventListener', 'removeEventListener', 'bind', 'unbind', 'on', 'off' ], function (name) { canRoute[name] = function (eventName, handler) { if (eventName === '__url') { return bindingProxy.call('can.onValue', handler); } return bindToCanRouteData(name, arguments); }; }); each([ 'delegate', 'undelegate', 'removeAttr', 'compute', '_get', '___get', 'each' ], function (name) { canRoute[name] = function () { return bindToCanRouteData(name, arguments); }; }); var routeData; var setRouteData = function (data) { routeData = data; return routeData; }; var serializedObservation; var serializedCompute; Object.defineProperty(canRoute, 'serializedObservation', { get: function () { if (!serializedObservation) { serializedObservation = new Observation(function canRoute_data_serialized() { return canReflect.serialize(canRoute.data); }); } return serializedObservation; } }); Object.defineProperty(canRoute, 'serializedCompute', { get: function () { if (!serializedCompute) { serializedCompute = makeCompute(canRoute.serializedObservation); } return serializedCompute; } }); var stringify = function (obj) { if (obj && typeof obj === 'object') { if (obj && typeof obj === 'object' && 'serialize' in obj) { obj = obj.serialize(); } else { obj = isFunction(obj.slice) ? obj.slice() : assign({}, obj); } each(obj, function (val, prop) { obj[prop] = stringify(val); }); } else if (obj !== undefined && obj !== null && isFunction(obj.toString)) { obj = obj.toString(); } return obj; }; var stringCoercingMapDecorator = function (map) { var sym = canSymbol.for('can.route.stringCoercingMapDecorator'); if (!map.attr[sym]) { var attrSuper = map.attr; map.attr = function (prop, val) { var serializable = this.define === undefined || this.define[prop] === undefined || !!this.define[prop].serialize, args; if (serializable) { args = stringify(Array.apply(null, arguments)); } else { args = arguments; } return attrSuper.apply(this, args); }; canReflect.setKeyValue(map.attr, sym, true); } return map; }; Object.defineProperty(canRoute, 'data', { get: function () { if (routeData) { return routeData; } else { return setRouteData(stringCoercingMapDecorator(new SimpleMap())); } }, set: function (data) { if (canReflect.isConstructorLike(data)) { data = new data(); } if ('attr' in data) { setRouteData(stringCoercingMapDecorator(data)); } else { setRouteData(data); } } }); canRoute.attr = function (prop, value) { console.warn('can-route: can-route.attr is deprecated. Use methods on can-route.data instead.'); if ('attr' in canRoute.data) { return canRoute.data.attr.apply(canRoute.data, arguments); } else { if (arguments.length > 1) { canReflect.setKeyValue(canRoute.data, prop, value); return canRoute.data; } else if (typeof prop === 'object') { canReflect.assignDeep(canRoute.data, prop); return canRoute.data; } else if (arguments.length === 1) { return canReflect.getKeyValue(canRoute.data, prop); } else { return canReflect.unwrap(canRoute.data); } } }; canReflect.setKeyValue(canRoute, canSymbol.for('can.isFunctionLike'), false); module.exports = namespace.route = canRoute; }); /*can-view-target@3.1.6#can-view-target*/ define('can-view-target', [ 'require', 'exports', 'module', 'can-util/dom/child-nodes/child-nodes', 'can-util/dom/attr/attr', 'can-util/js/each/each', 'can-util/js/make-array/make-array', 'can-globals/document/document', 'can-util/dom/mutate/mutate', 'can-namespace', 'can-globals/mutation-observer/mutation-observer' ], function (require, exports, module) { (function (global, require, exports, module) { var childNodes = require('can-util/dom/child-nodes/child-nodes'); var domAttr = require('can-util/dom/attr/attr'); var each = require('can-util/js/each/each'); var makeArray = require('can-util/js/make-array/make-array'); var getDocument = require('can-globals/document/document'); var domMutate = require('can-util/dom/mutate/mutate'); var namespace = require('can-namespace'); var MUTATION_OBSERVER = require('can-globals/mutation-observer/mutation-observer'); var processNodes = function (nodes, paths, location, document) { var frag = document.createDocumentFragment(); for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; frag.appendChild(processNode(node, paths, location.concat(i), document)); } return frag; }, keepsTextNodes = typeof document !== 'undefined' && function () { var testFrag = document.createDocumentFragment(); var div = document.createElement('div'); div.appendChild(document.createTextNode('')); div.appendChild(document.createTextNode('')); testFrag.appendChild(div); var cloned = testFrag.cloneNode(true); return childNodes(cloned.firstChild).length === 2; }(), clonesWork = typeof document !== 'undefined' && function () { var el = document.createElement('a'); el.innerHTML = '<xyz></xyz>'; var clone = el.cloneNode(true); var works = clone.innerHTML === '<xyz></xyz>'; var MO, observer; if (works) { el = document.createDocumentFragment(); el.appendChild(document.createTextNode('foo-bar')); MO = MUTATION_OBSERVER(); if (MO) { observer = new MO(function () { }); observer.observe(document.documentElement, { childList: true, subtree: true }); clone = el.cloneNode(true); observer.disconnect(); } else { clone = el.cloneNode(true); } return clone.childNodes.length === 1; } return works; }(), namespacesWork = typeof document !== 'undefined' && !!document.createElementNS; var cloneNode = clonesWork ? function (el) { return el.cloneNode(true); } : function (node) { var document = node.ownerDocument; var copy; if (node.nodeType === 1) { if (node.namespaceURI !== 'http://www.w3.org/1999/xhtml' && namespacesWork && document.createElementNS) { copy = document.createElementNS(node.namespaceURI, node.nodeName); } else { copy = document.createElement(node.nodeName); } } else if (node.nodeType === 3) { copy = document.createTextNode(node.nodeValue); } else if (node.nodeType === 8) { copy = document.createComment(node.nodeValue); } else if (node.nodeType === 11) { copy = document.createDocumentFragment(); } if (node.attributes) { var attributes = makeArray(node.attributes); each(attributes, function (node) { if (node && node.specified) { domAttr.setAttribute(copy, node.nodeName || node.name, node.nodeValue || node.value); } }); } if (node && node.firstChild) { var child = node.firstChild; while (child) { copy.appendChild(cloneNode(child)); child = child.nextSibling; } } return copy; }; function processNode(node, paths, location, document) { var callback, loc = location, nodeType = typeof node, el, p, i, len; var getCallback = function () { if (!callback) { callback = { path: location, callbacks: [] }; paths.push(callback); loc = []; } return callback; }; if (nodeType === 'object') { if (node.tag) { if (namespacesWork && node.namespace) { el = document.createElementNS(node.namespace, node.tag); } else { el = document.createElement(node.tag); } if (node.attrs) { for (var attrName in node.attrs) { var value = node.attrs[attrName]; if (typeof value === 'function') { getCallback().callbacks.push({ callback: value }); } else { domAttr.setAttribute(el, attrName, value); } } } if (node.attributes) { for (i = 0, len = node.attributes.length; i < len; i++) { getCallback().callbacks.push({ callback: node.attributes[i] }); } } if (node.children && node.children.length) { if (callback) { p = callback.paths = []; } else { p = paths; } el.appendChild(processNodes(node.children, p, loc, document)); } } else if (node.comment) { el = document.createComment(node.comment); if (node.callbacks) { for (i = 0, len = node.attributes.length; i < len; i++) { getCallback().callbacks.push({ callback: node.callbacks[i] }); } } } } else if (nodeType === 'string') { el = document.createTextNode(node); } else if (nodeType === 'function') { if (keepsTextNodes) { el = document.createTextNode(''); getCallback().callbacks.push({ callback: node }); } else { el = document.createComment('~'); getCallback().callbacks.push({ callback: function () { var el = document.createTextNode(''); domMutate.replaceChild.call(this.parentNode, el, this); return node.apply(el, arguments); } }); } } return el; } function getCallbacks(el, pathData, elementCallbacks) { var path = pathData.path, callbacks = pathData.callbacks, paths = pathData.paths, child = el, pathLength = path ? path.length : 0, pathsLength = paths ? paths.length : 0; for (var i = 0; i < pathLength; i++) { child = child.childNodes.item(path[i]); } for (i = 0; i < pathsLength; i++) { getCallbacks(child, paths[i], elementCallbacks); } elementCallbacks.push({ element: child, callbacks: callbacks }); } function hydrateCallbacks(callbacks, args) { var len = callbacks.length, callbacksLength, callbackElement, callbackData; for (var i = 0; i < len; i++) { callbackData = callbacks[i]; callbacksLength = callbackData.callbacks.length; callbackElement = callbackData.element; for (var c = 0; c < callbacksLength; c++) { callbackData.callbacks[c].callback.apply(callbackElement, args); } } } function makeTarget(nodes, doc) { var paths = []; var frag = processNodes(nodes, paths, [], doc || getDocument()); return { paths: paths, clone: frag, hydrate: function () { var cloned = cloneNode(this.clone); var args = makeArray(arguments); var callbacks = []; for (var i = 0; i < paths.length; i++) { getCallbacks(cloned, paths[i], callbacks); } hydrateCallbacks(callbacks, args); return cloned; } }; } makeTarget.keepsTextNodes = keepsTextNodes; makeTarget.cloneNode = cloneNode; namespace.view = namespace.view || {}; module.exports = namespace.view.target = makeTarget; }(function () { return this; }(), require, exports, module)); }); /*can-stache@4.0.0-pre.26#src/mustache_core*/ define('can-stache/src/mustache_core', [ 'require', 'exports', 'module', 'can-view-live', 'can-view-nodelist', 'can-observation', 'can-observation-recorder', 'can-stache/src/utils', 'can-stache/src/expression', 'can-util/dom/frag/frag', 'can-util/dom/attr/attr', 'can-symbol', 'can-reflect', 'can-log/dev/dev' ], function (require, exports, module) { var live = require('can-view-live'); var nodeLists = require('can-view-nodelist'); var Observation = require('can-observation'); var ObservationRecorder = require('can-observation-recorder'); var utils = require('can-stache/src/utils'); var expression = require('can-stache/src/expression'); var frag = require('can-util/dom/frag/frag'); var attr = require('can-util/dom/attr/attr'); var canSymbol = require('can-symbol'); var canReflect = require('can-reflect'); var dev = require('can-log/dev/dev'); var mustacheLineBreakRegExp = /(?:(^|\r?\n)(\s*)(\{\{([\s\S]*)\}\}\}?)([^\S\n\r]*)($|\r?\n))|(\{\{([\s\S]*)\}\}\}?)/g, mustacheWhitespaceRegExp = /(\s*)(\{\{\{?)(-?)([\s\S]*?)(-?)(\}\}\}?)(\s*)/g, k = function () { }; var core = { expression: expression, makeEvaluator: function (scope, nodeList, mode, exprData, truthyRenderer, falseyRenderer, stringOnly) { if (mode === '^') { var temp = truthyRenderer; truthyRenderer = falseyRenderer; falseyRenderer = temp; } var value, helperOptionArg; if (exprData instanceof expression.Call) { helperOptionArg = { context: scope.peek('.'), scope: scope, nodeList: nodeList, exprData: exprData }; utils.convertToScopes(helperOptionArg, scope, nodeList, truthyRenderer, falseyRenderer, stringOnly); value = exprData.value(scope, helperOptionArg); if (exprData.isHelper) { return value; } } else if (exprData instanceof expression.Bracket) { value = exprData.value(scope); if (exprData.isHelper) { return value; } } else if (exprData instanceof expression.Lookup) { value = exprData.value(scope); if (exprData.isHelper) { return value; } } else if (exprData instanceof expression.Helper && exprData.methodExpr instanceof expression.Bracket) { value = exprData.methodExpr.value(scope); if (exprData.isHelper) { return value; } } else { var readOptions = { isArgument: true, args: [ scope.peek('.'), scope ], asCompute: true }; var helperAndValue = exprData.helperAndValue(scope, readOptions, nodeList, truthyRenderer, falseyRenderer, stringOnly); var helper = helperAndValue.helper; value = helperAndValue.value; if (helper) { return exprData.evaluator(helper, scope, readOptions, nodeList, truthyRenderer, falseyRenderer, stringOnly); } } if (!mode) { return value; } else if (mode === '#' || mode === '^') { helperOptionArg = {}; utils.convertToScopes(helperOptionArg, scope, nodeList, truthyRenderer, falseyRenderer, stringOnly); return function () { var finalValue = canReflect.getValue(value); if (typeof finalValue === 'function') { return finalValue; } else if (typeof finalValue !== 'string' && utils.isArrayLike(finalValue)) { var isObserveList = canReflect.isObservableLike(finalValue) && canReflect.isListLike(finalValue); if (isObserveList ? finalValue.attr('length') : finalValue.length) { if (stringOnly) { return utils.getItemsStringContent(finalValue, isObserveList, helperOptionArg); } else { return frag(utils.getItemsFragContent(finalValue, helperOptionArg, scope)); } } else { return helperOptionArg.inverse(scope); } } else { return finalValue ? helperOptionArg.fn(finalValue || scope) : helperOptionArg.inverse(scope); } }; } else { } }, makeLiveBindingPartialRenderer: function (expressionString, state, lineNo) { expressionString = expressionString.trim(); var exprData, partialName = expressionString.split(/\s+/).shift(); if (partialName !== expressionString) { exprData = core.expression.parse(expressionString); } return function (scope, parentSectionNodeList) { scope.set('scope.lineNumber', lineNo); var nodeList = [this]; nodeList.expression = '>' + partialName; nodeLists.register(nodeList, null, parentSectionNodeList || true, state.directlyNested); var partialFrag = new Observation(function () { var localPartialName = partialName; if (exprData && exprData.argExprs.length === 1) { var newContext = canReflect.getValue(exprData.argExprs[0].value(scope)); if (typeof newContext === 'undefined') { dev.warn('The context (' + exprData.argExprs[0].key + ') you passed into the' + 'partial (' + partialName + ') is not defined in the scope!'); } else { scope = scope.add(newContext); } } var partial = canReflect.getKeyValue(scope.templateContext.partials, localPartialName); var renderer; if (partial) { renderer = function () { return partial.render ? partial.render(scope, nodeList) : partial(scope); }; } else { var scopePartialName = scope.read(localPartialName, { isArgument: true }).value; if (scopePartialName === null || !scopePartialName && localPartialName[0] === '*') { return frag(''); } if (scopePartialName) { localPartialName = scopePartialName; } renderer = function () { if (typeof localPartialName === 'function') { return localPartialName(scope, {}, nodeList); } else { return core.getTemplateById(localPartialName)(scope, {}, nodeList); } }; } var res = ObservationRecorder.ignore(renderer)(); return frag(res); }); canReflect.setPriority(partialFrag, nodeList.nesting); live.html(this, partialFrag, this.parentNode, nodeList); }; }, makeStringBranchRenderer: function (mode, expressionString, lineNo) { var exprData = core.expression.parse(expressionString), fullExpression = mode + expressionString; if (!(exprData instanceof expression.Helper) && !(exprData instanceof expression.Call)) { exprData = new expression.Helper(exprData, [], {}); } var branchRenderer = function branchRenderer(scope, truthyRenderer, falseyRenderer) { scope.set('scope.lineNumber', lineNo); var evaluator = scope.__cache[fullExpression]; if (mode || !evaluator) { evaluator = makeEvaluator(scope, null, mode, exprData, truthyRenderer, falseyRenderer, true); if (!mode) { scope.__cache[fullExpression] = evaluator; } } var gotObservableValue = evaluator[canSymbol.for('can.onValue')], res; if (gotObservableValue) { res = canReflect.getValue(evaluator); } else { res = evaluator(); } return res == null ? '' : '' + res; }; branchRenderer.exprData = exprData; return branchRenderer; }, makeLiveBindingBranchRenderer: function (mode, expressionString, state, lineNo) { var exprData = core.expression.parse(expressionString); if (!(exprData instanceof expression.Helper) && !(exprData instanceof expression.Call) && !(exprData instanceof expression.Bracket) && !(exprData instanceof expression.Lookup)) { exprData = new expression.Helper(exprData, [], {}); } var branchRenderer = function branchRenderer(scope, parentSectionNodeList, truthyRenderer, falseyRenderer) { scope.set('scope.lineNumber', lineNo); var nodeList = [this]; nodeList.expression = expressionString; nodeLists.register(nodeList, null, parentSectionNodeList || true, state.directlyNested); var evaluator = makeEvaluator(scope, nodeList, mode, exprData, truthyRenderer, falseyRenderer, state.tag); var gotObservableValue = evaluator[canSymbol.for('can.onValue')]; var observable; if (gotObservableValue) { observable = evaluator; } else { Object.defineProperty(evaluator, 'name', { value: '{{' + expressionString + '}}' }); observable = new Observation(evaluator, null, { isObservable: false }); } if (canReflect.setPriority(observable, nodeList.nesting) === false) { throw new Error('can-stache unable to set priority on observable'); } canReflect.onValue(observable, k); var value = canReflect.getValue(observable); if (typeof value === 'function') { ObservationRecorder.ignore(value)(this); } else if (canReflect.valueHasDependencies(observable)) { if (state.attr) { live.attr(this, state.attr, observable); } else if (state.tag) { live.attrs(this, observable); } else if (state.text && typeof value !== 'object') { live.text(this, observable, this.parentNode, nodeList); } else { live.html(this, observable, this.parentNode, nodeList); } } else { if (state.attr) { attr.set(this, state.attr, value); } else if (state.tag) { live.attrs(this, value); } else if (state.text && typeof value === 'string') { this.nodeValue = value; } else if (value != null) { nodeLists.replace([this], frag(value, this.ownerDocument)); } } canReflect.offValue(observable, k); }; branchRenderer.exprData = exprData; return branchRenderer; }, splitModeFromExpression: function (expression, state, lineNo) { expression = expression.trim(); var mode = expression.charAt(0); if ('#/{&^>!<'.indexOf(mode) >= 0) { expression = expression.substr(1).trim(); } else { mode = null; } if (mode === '{' && state.node) { mode = null; } return { mode: mode, expression: expression }; }, cleanLineEndings: function (template) { return template.replace(mustacheLineBreakRegExp, function (whole, returnBefore, spaceBefore, special, expression, spaceAfter, returnAfter, spaceLessSpecial, spaceLessExpression, matchIndex) { spaceAfter = spaceAfter || ''; returnBefore = returnBefore || ''; spaceBefore = spaceBefore || ''; var modeAndExpression = splitModeFromExpression(expression || spaceLessExpression, {}); if (spaceLessSpecial || '>{'.indexOf(modeAndExpression.mode) >= 0) { return whole; } else if ('^#!/'.indexOf(modeAndExpression.mode) >= 0) { spaceBefore = returnBefore + spaceBefore && ' '; return spaceBefore + special + (matchIndex !== 0 && returnAfter.length ? returnBefore + '\n' : ''); } else { return spaceBefore + special + spaceAfter + (spaceBefore.length || matchIndex !== 0 ? returnBefore + '\n' : ''); } }); }, cleanWhitespaceControl: function (template) { return template.replace(mustacheWhitespaceRegExp, function (whole, spaceBefore, bracketBefore, controlBefore, expression, controlAfter, bracketAfter, spaceAfter, matchIndex) { if (controlBefore === '-') { spaceBefore = ''; } if (controlAfter === '-') { spaceAfter = ''; } return spaceBefore + bracketBefore + expression + bracketAfter + spaceAfter; }); }, getTemplateById: function () { } }; var makeEvaluator = core.makeEvaluator, splitModeFromExpression = core.splitModeFromExpression; module.exports = core; }); /*can-stache@4.0.0-pre.26#src/html_section*/ define('can-stache/src/html_section', [ 'require', 'exports', 'module', 'can-view-target', 'can-view-scope', 'can-observation', 'can-observation-recorder', 'can-reflect', 'can-stache/src/utils', 'can-stache/src/mustache_core', 'can-globals/document/document', 'can-assign', 'can-util/js/last/last' ], function (require, exports, module) { (function (global, require, exports, module) { var target = require('can-view-target'); var Scope = require('can-view-scope'); var Observation = require('can-observation'); var ObservationRecorder = require('can-observation-recorder'); var canReflect = require('can-reflect'); var utils = require('can-stache/src/utils'); var mustacheCore = require('can-stache/src/mustache_core'); var getDocument = require('can-globals/document/document'); var assign = require('can-assign'); var last = require('can-util/js/last/last'); var decodeHTML = typeof document !== 'undefined' && function () { var el = getDocument().createElement('div'); return function (html) { if (html.indexOf('&') === -1) { return html.replace(/\r\n/g, '\n'); } el.innerHTML = html; return el.childNodes.length === 0 ? '' : el.childNodes.item(0).nodeValue; }; }(); var HTMLSectionBuilder = function (filename) { if (filename) { this.filename = filename; } this.stack = [new HTMLSection()]; }; HTMLSectionBuilder.scopify = function (renderer) { return ObservationRecorder.ignore(function (scope, options, nodeList) { if (!(scope instanceof Scope)) { scope = new Scope(scope || {}); } if (nodeList === undefined && canReflect.isListLike(options)) { nodeList = options; options = undefined; } if (options && !options.helpers && !options.partials && !options.tags) { options = { helpers: options }; } var templateContext = scope.templateContext; canReflect.eachKey(options, function (optionValues, optionKey) { var container = templateContext[optionKey]; if (container) { canReflect.eachKey(optionValues, function (optionValue, optionValueKey) { canReflect.setKeyValue(container, optionValueKey, optionValue); }); } }); return renderer(scope, nodeList); }); }; assign(HTMLSectionBuilder.prototype, utils.mixins); assign(HTMLSectionBuilder.prototype, { startSubSection: function (process) { var newSection = new HTMLSection(process); this.stack.push(newSection); return newSection; }, endSubSectionAndReturnRenderer: function () { if (this.last().isEmpty()) { this.stack.pop(); return null; } else { var htmlSection = this.endSection(); return htmlSection.compiled.hydrate.bind(htmlSection.compiled); } }, startSection: function (process) { var newSection = new HTMLSection(process); this.last().add(newSection.targetCallback); this.stack.push(newSection); }, endSection: function () { this.last().compile(); return this.stack.pop(); }, inverse: function () { this.last().inverse(); }, compile: function () { var compiled = this.stack.pop().compile(); return ObservationRecorder.ignore(function (scope, nodeList) { if (!(scope instanceof Scope)) { scope = new Scope(scope || {}); } return compiled.hydrate(scope, nodeList); }); }, push: function (chars) { this.last().push(chars); }, pop: function () { return this.last().pop(); }, removeCurrentNode: function () { this.last().removeCurrentNode(); } }); var HTMLSection = function (process) { this.data = 'targetData'; this.targetData = []; this.targetStack = []; var self = this; this.targetCallback = function (scope, sectionNode) { process.call(this, scope, sectionNode, self.compiled.hydrate.bind(self.compiled), self.inverseCompiled && self.inverseCompiled.hydrate.bind(self.inverseCompiled)); }; }; assign(HTMLSection.prototype, { inverse: function () { this.inverseData = []; this.data = 'inverseData'; }, push: function (data) { this.add(data); this.targetStack.push(data); }, pop: function () { return this.targetStack.pop(); }, add: function (data) { if (typeof data === 'string') { data = decodeHTML(data); } if (this.targetStack.length) { last(this.targetStack).children.push(data); } else { this[this.data].push(data); } }, compile: function () { this.compiled = target(this.targetData, getDocument()); if (this.inverseData) { this.inverseCompiled = target(this.inverseData, getDocument()); delete this.inverseData; } this.targetStack = this.targetData = null; return this.compiled; }, removeCurrentNode: function () { var children = this.children(); return children.pop(); }, children: function () { if (this.targetStack.length) { return last(this.targetStack).children; } else { return this[this.data]; } }, isEmpty: function () { return !this.targetData.length; } }); HTMLSectionBuilder.HTMLSection = HTMLSection; module.exports = HTMLSectionBuilder; }(function () { return this; }(), require, exports, module)); }); /*can-stache@4.0.0-pre.26#src/text_section*/ define('can-stache/src/text_section', [ 'require', 'exports', 'module', 'can-view-live', 'can-stache/src/utils', 'can-util/dom/attr/attr', 'can-assign', 'can-reflect', 'can-observation' ], function (require, exports, module) { var live = require('can-view-live'); var utils = require('can-stache/src/utils'); var attr = require('can-util/dom/attr/attr'); var assign = require('can-assign'); var canReflect = require('can-reflect'); var Observation = require('can-observation'); var noop = function () { }; var TextSectionBuilder = function () { this.stack = [new TextSection()]; }; assign(TextSectionBuilder.prototype, utils.mixins); assign(TextSectionBuilder.prototype, { startSection: function (process) { var subSection = new TextSection(); this.last().add({ process: process, truthy: subSection }); this.stack.push(subSection); }, endSection: function () { this.stack.pop(); }, inverse: function () { this.stack.pop(); var falseySection = new TextSection(); this.last().last().falsey = falseySection; this.stack.push(falseySection); }, compile: function (state) { var renderer = this.stack[0].compile(); Object.defineProperty(renderer, 'name', { value: 'textSectionRenderer<' + state.tag + '.' + state.attr + '>' }); return function (scope) { function textSectionRender() { return renderer(scope); } Object.defineProperty(textSectionRender, 'name', { value: 'textSectionRender<' + state.tag + '.' + state.attr + '>' }); var observation = new Observation(textSectionRender, null, { isObservable: false }); canReflect.onValue(observation, noop); var value = canReflect.getValue(observation); if (canReflect.valueHasDependencies(observation)) { if (state.textContentOnly) { live.text(this, observation); } else if (state.attr) { live.attr(this, state.attr, observation); } else { live.attrs(this, observation, scope); } canReflect.offValue(observation, noop); } else { if (state.textContentOnly) { this.nodeValue = value; } else if (state.attr) { attr.set(this, state.attr, value); } else { live.attrs(this, value); } } }; } }); var passTruthyFalsey = function (process, truthy, falsey) { return function (scope) { return process.call(this, scope, truthy, falsey); }; }; var TextSection = function () { this.values = []; }; assign(TextSection.prototype, { add: function (data) { this.values.push(data); }, last: function () { return this.values[this.values.length - 1]; }, compile: function () { var values = this.values, len = values.length; for (var i = 0; i < len; i++) { var value = this.values[i]; if (typeof value === 'object') { values[i] = passTruthyFalsey(value.process, value.truthy && value.truthy.compile(), value.falsey && value.falsey.compile()); } } return function (scope) { var txt = '', value; for (var i = 0; i < len; i++) { value = values[i]; txt += typeof value === 'string' ? value : value.call(this, scope); } return txt; }; } }); module.exports = TextSectionBuilder; }); /*can-stache@4.0.0-pre.26#helpers/converter*/ define('can-stache/helpers/converter', [ 'require', 'exports', 'module', 'can-stache/helpers/core', 'can-stache/src/set-identifier', 'can-reflect' ], function (require, exports, module) { var helpers = require('can-stache/helpers/core'); var SetIdentifier = require('can-stache/src/set-identifier'); var canReflect = require('can-reflect'); helpers.registerConverter = function (name, getterSetter) { getterSetter = getterSetter || {}; helpers.registerHelper(name, function (newVal, source) { var args = canReflect.toArray(arguments); if (newVal instanceof SetIdentifier) { return typeof getterSetter.set === 'function' ? getterSetter.set.apply(this, [newVal.value].concat(args.slice(1))) : source(newVal.value); } else { return typeof getterSetter.get === 'function' ? getterSetter.get.apply(this, args) : args[0]; } }); }; module.exports = helpers; }); /*can-stache@4.0.0-pre.26#src/intermediate_and_imports*/ define('can-stache/src/intermediate_and_imports', [ 'require', 'exports', 'module', 'can-stache/src/mustache_core', 'can-view-parser' ], function (require, exports, module) { var mustacheCore = require('can-stache/src/mustache_core'); var parser = require('can-view-parser'); module.exports = function (filename, source) { if (arguments.length === 1) { source = arguments[0]; filename = undefined; } var template = source; template = mustacheCore.cleanWhitespaceControl(template); template = mustacheCore.cleanLineEndings(template); var imports = [], dynamicImports = [], ases = {}, inImport = false, inFrom = false, inAs = false, isUnary = false, importIsDynamic = false, currentAs = '', currentFrom = ''; function processImport() { if (currentAs) { ases[currentAs] = currentFrom; currentAs = ''; } if (importIsDynamic) { dynamicImports.push(currentFrom); } else { imports.push(currentFrom); } } var intermediate = parser(template, { filename: filename, start: function (tagName, unary) { if (tagName === 'can-import') { isUnary = unary; importIsDynamic = false; inImport = true; } else if (tagName === 'can-dynamic-import') { isUnary = unary; importIsDynamic = true; inImport = true; } else if (inImport) { importIsDynamic = true; inImport = false; } }, attrStart: function (attrName) { if (attrName === 'from') { inFrom = true; } else if (attrName === 'as' || attrName === 'export-as') { inAs = true; } }, attrEnd: function (attrName) { if (attrName === 'from') { inFrom = false; } else if (attrName === 'as' || attrName === 'export-as') { inAs = false; } }, attrValue: function (value) { if (inFrom && inImport) { currentFrom = value; } else if (inAs && inImport) { currentAs = value; } }, end: function (tagName) { if ((tagName === 'can-import' || tagName === 'can-dymamic-import') && isUnary) { processImport(); } }, close: function (tagName) { if (tagName === 'can-import' || tagName === 'can-dymamic-import') { processImport(); } }, chars: function (text) { if (text.trim().length > 0) { importIsDynamic = true; } }, special: function (text) { importIsDynamic = true; } }, true); return { intermediate: intermediate, imports: imports, dynamicImports: dynamicImports, ases: ases, exports: ases }; }; }); /*can-util@3.10.18#js/import/import*/ define('can-util/js/import/import', [ 'require', 'exports', 'module', 'can-util/js/is-function/is-function', 'can-globals/global/global' ], function (require, exports, module) { (function (global, require, exports, module) { 'use strict'; var isFunction = require('can-util/js/is-function/is-function'); var global = require('can-globals/global/global')(); module.exports = function (moduleName, parentName) { return new Promise(function (resolve, reject) { try { if (typeof global.System === 'object' && isFunction(global.System['import'])) { global.System['import'](moduleName, { name: parentName }).then(resolve, reject); } else if (global.define && global.define.amd) { global.require([moduleName], function (value) { resolve(value); }); } else if (global.require) { resolve(global.require(moduleName)); } else { resolve(); } } catch (err) { reject(err); } }); }; }(function () { return this; }(), require, exports, module)); }); /*can-stache@4.0.0-pre.26#can-stache*/ define('can-stache', [ 'require', 'exports', 'module', 'can-view-parser', 'can-view-callbacks', 'can-stache/src/html_section', 'can-stache/src/text_section', 'can-stache/src/mustache_core', 'can-stache/helpers/core', 'can-stache/helpers/converter', 'can-stache/src/intermediate_and_imports', 'can-stache/src/utils', 'can-attribute-encoder', 'can-log/dev/dev', 'can-namespace', 'can-globals/document/document', 'can-assign', 'can-util/js/last/last', 'can-util/js/import/import', 'can-reflect', 'can-view-target', 'can-view-nodelist' ], function (require, exports, module) { (function (global, require, exports, module) { var parser = require('can-view-parser'); var viewCallbacks = require('can-view-callbacks'); var HTMLSectionBuilder = require('can-stache/src/html_section'); var TextSectionBuilder = require('can-stache/src/text_section'); var mustacheCore = require('can-stache/src/mustache_core'); var mustacheHelpers = require('can-stache/helpers/core'); require('can-stache/helpers/converter'); var getIntermediateAndImports = require('can-stache/src/intermediate_and_imports'); var makeRendererConvertScopes = require('can-stache/src/utils').makeRendererConvertScopes; var attributeEncoder = require('can-attribute-encoder'); var dev = require('can-log/dev/dev'); var namespace = require('can-namespace'); var DOCUMENT = require('can-globals/document/document'); var assign = require('can-assign'); var last = require('can-util/js/last/last'); var importer = require('can-util/js/import/import'); var canReflect = require('can-reflect'); require('can-view-target'); require('can-view-nodelist'); if (!viewCallbacks.tag('content')) { viewCallbacks.tag('content', function (el, tagData) { return tagData.scope; }); } var wrappedAttrPattern = /[{(].*[)}]/; var colonWrappedAttrPattern = /^on:|(:to|:from|:bind)$|.*:to:on:.*/; var svgNamespace = 'http://www.w3.org/2000/svg'; var namespaces = { 'svg': svgNamespace, 'g': svgNamespace }, textContentOnlyTag = { style: true, script: true }; function stache(filename, template) { if (arguments.length === 1) { template = arguments[0]; filename = undefined; } var inlinePartials = {}; if (typeof template === 'string') { template = mustacheCore.cleanWhitespaceControl(template); template = mustacheCore.cleanLineEndings(template); } var section = new HTMLSectionBuilder(filename), state = { node: null, attr: null, sectionElementStack: [], text: false, namespaceStack: [], textContentOnly: null }, makeRendererAndUpdateSection = function (section, mode, stache, lineNo) { if (mode === '>') { section.add(mustacheCore.makeLiveBindingPartialRenderer(stache, copyState(), lineNo)); } else if (mode === '/') { var createdSection = section.last(); if (createdSection.startedWith === '<') { inlinePartials[stache] = section.endSubSectionAndReturnRenderer(); section.removeCurrentNode(); } else { section.endSection(); } if (section instanceof HTMLSectionBuilder) { var last = state.sectionElementStack[state.sectionElementStack.length - 1]; if (last.tag && last.type === 'section' && stache !== '' && stache !== last.tag) { if (filename) { dev.warn(filename + ':' + lineNo + ': unexpected closing tag {{/' + stache + '}} expected {{/' + last.tag + '}}'); } else { dev.warn(lineNo + ': unexpected closing tag {{/' + stache + '}} expected {{/' + last.tag + '}}'); } } state.sectionElementStack.pop(); } } else if (mode === 'else') { section.inverse(); } else { var makeRenderer = section instanceof HTMLSectionBuilder ? mustacheCore.makeLiveBindingBranchRenderer : mustacheCore.makeStringBranchRenderer; if (mode === '{' || mode === '&') { section.add(makeRenderer(null, stache, copyState(), lineNo)); } else if (mode === '#' || mode === '^' || mode === '<') { var renderer = makeRenderer(mode, stache, copyState(), lineNo); section.startSection(renderer); section.last().startedWith = mode; if (section instanceof HTMLSectionBuilder) { var tag = typeof renderer.exprData.closingTag === 'function' ? renderer.exprData.closingTag() : ''; state.sectionElementStack.push({ type: 'section', tag: tag }); } } else { section.add(makeRenderer(null, stache, copyState({ text: true }), lineNo)); } } }, copyState = function (overwrites) { var lastElement = state.sectionElementStack[state.sectionElementStack.length - 1]; var cur = { tag: state.node && state.node.tag, attr: state.attr && state.attr.name, directlyNested: state.sectionElementStack.length ? lastElement.type === 'section' || lastElement.type === 'custom' : true, textContentOnly: !!state.textContentOnly }; return overwrites ? assign(cur, overwrites) : cur; }, addAttributesCallback = function (node, callback) { if (!node.attributes) { node.attributes = []; } node.attributes.unshift(callback); }; parser(template, { filename: filename, start: function (tagName, unary, lineNo) { var matchedNamespace = namespaces[tagName]; if (matchedNamespace && !unary) { state.namespaceStack.push(matchedNamespace); } state.node = { tag: tagName, children: [], namespace: matchedNamespace || last(state.namespaceStack) }; }, end: function (tagName, unary, lineNo) { var isCustomTag = viewCallbacks.tag(tagName); if (unary) { section.add(state.node); if (isCustomTag) { addAttributesCallback(state.node, function (scope, parentNodeList) { scope.set('scope.lineNumber', lineNo); viewCallbacks.tagHandler(this, tagName, { scope: scope, subtemplate: null, templateType: 'stache', parentNodeList: parentNodeList }); }); } } else { section.push(state.node); state.sectionElementStack.push({ type: isCustomTag ? 'custom' : null, tag: isCustomTag ? null : tagName, templates: {} }); if (isCustomTag) { section.startSubSection(); } else if (textContentOnlyTag[tagName]) { state.textContentOnly = new TextSectionBuilder(); } } state.node = null; }, close: function (tagName, lineNo) { var matchedNamespace = namespaces[tagName]; if (matchedNamespace) { state.namespaceStack.pop(); } var isCustomTag = viewCallbacks.tag(tagName), renderer; if (isCustomTag) { renderer = section.endSubSectionAndReturnRenderer(); } if (textContentOnlyTag[tagName]) { section.last().add(state.textContentOnly.compile(copyState())); state.textContentOnly = null; } var oldNode = section.pop(); if (isCustomTag) { if (tagName === 'can-template') { var parent = state.sectionElementStack[state.sectionElementStack.length - 2]; parent.templates[oldNode.attrs.name] = makeRendererConvertScopes(renderer); section.removeCurrentNode(); } else { var current = state.sectionElementStack[state.sectionElementStack.length - 1]; addAttributesCallback(oldNode, function (scope, parentNodeList) { scope.set('scope.lineNumber', lineNo); viewCallbacks.tagHandler(this, tagName, { scope: scope, subtemplate: renderer ? makeRendererConvertScopes(renderer) : renderer, templateType: 'stache', parentNodeList: parentNodeList, templates: current.templates }); }); } } state.sectionElementStack.pop(); }, attrStart: function (attrName, lineNo) { if (state.node.section) { state.node.section.add(attrName + '="'); } else { state.attr = { name: attrName, value: '' }; } }, attrEnd: function (attrName, lineNo) { if (state.node.section) { state.node.section.add('" '); } else { if (!state.node.attrs) { state.node.attrs = {}; } state.node.attrs[state.attr.name] = state.attr.section ? state.attr.section.compile(copyState()) : state.attr.value; var attrCallback = viewCallbacks.attr(attrName); var decodedAttrName = attributeEncoder.decode(attrName); var weirdAttribute = !!wrappedAttrPattern.test(decodedAttrName) || !!colonWrappedAttrPattern.test(decodedAttrName); if (weirdAttribute && !attrCallback) { dev.warn('unknown attribute binding ' + decodedAttrName + '. Is can-stache-bindings imported?'); } if (attrCallback) { if (!state.node.attributes) { state.node.attributes = []; } state.node.attributes.push(function (scope, nodeList) { scope.set('scope.lineNumber', lineNo); attrCallback(this, { attributeName: attrName, scope: scope, nodeList: nodeList }); }); } state.attr = null; } }, attrValue: function (value, lineNo) { var section = state.node.section || state.attr.section; if (section) { section.add(value); } else { state.attr.value += value; } }, chars: function (text, lineNo) { (state.textContentOnly || section).add(text); }, special: function (text, lineNo) { var firstAndText = mustacheCore.splitModeFromExpression(text, state, lineNo), mode = firstAndText.mode, expression = firstAndText.expression; if (expression === 'else') { var inverseSection; if (state.attr && state.attr.section) { inverseSection = state.attr.section; } else if (state.node && state.node.section) { inverseSection = state.node.section; } else { inverseSection = state.textContentOnly || section; } inverseSection.inverse(); return; } if (mode === '!') { return; } if (state.node && state.node.section) { makeRendererAndUpdateSection(state.node.section, mode, expression, lineNo); if (state.node.section.subSectionDepth() === 0) { state.node.attributes.push(state.node.section.compile(copyState())); delete state.node.section; } } else if (state.attr) { if (!state.attr.section) { state.attr.section = new TextSectionBuilder(); if (state.attr.value) { state.attr.section.add(state.attr.value); } } makeRendererAndUpdateSection(state.attr.section, mode, expression, lineNo); } else if (state.node) { if (!state.node.attributes) { state.node.attributes = []; } if (!mode) { state.node.attributes.push(mustacheCore.makeLiveBindingBranchRenderer(null, expression, copyState(), lineNo)); } else if (mode === '#' || mode === '^') { if (!state.node.section) { state.node.section = new TextSectionBuilder(); } makeRendererAndUpdateSection(state.node.section, mode, expression, lineNo); } else { throw new Error(mode + ' is currently not supported within a tag.'); } } else { makeRendererAndUpdateSection(state.textContentOnly || section, mode, expression, lineNo); } }, comment: function (text) { section.add({ comment: text }); }, done: function (lineNo) { } }); var renderer = section.compile(); var scopifiedRenderer = HTMLSectionBuilder.scopify(function (scope, nodeList) { var templateContext = scope.templateContext; canReflect.eachKey(inlinePartials, function (partial, partialName) { canReflect.setKeyValue(templateContext.partials, partialName, partial); }); canReflect.setKeyValue(templateContext, 'view', scopifiedRenderer); canReflect.setKeyValue(templateContext, 'filename', section.filename); return renderer.apply(this, arguments); }); return scopifiedRenderer; } assign(stache, mustacheHelpers); stache.safeString = function (text) { return { toString: function () { return text; } }; }; stache.async = function (source) { var iAi = getIntermediateAndImports(source); var importPromises = iAi.imports.map(function (moduleName) { return importer(moduleName); }); return Promise.all(importPromises).then(function () { return stache(iAi.intermediate); }); }; var templates = {}; stache.from = mustacheCore.getTemplateById = function (id) { if (!templates[id]) { var el = DOCUMENT().getElementById(id); templates[id] = stache('#' + id, el.innerHTML); } return templates[id]; }; stache.registerPartial = function (id, partial) { templates[id] = typeof partial === 'string' ? stache(partial) : partial; }; module.exports = namespace.stache = stache; }(function () { return this; }(), require, exports, module)); }); /*can-stache-route-helpers@0.1.0#can-stache-route-helpers*/ define('can-stache-route-helpers', [ 'require', 'exports', 'module', 'can-stache/helpers/core', 'can-route', 'can-stache/src/expression', 'can-util/js/each/each' ], function (require, exports, module) { var helpers = require('can-stache/helpers/core'); var route = require('can-route'); var stacheExpression = require('can-stache/src/expression'); var each = require('can-util/js/each/each'); var looksLikeOptions = helpers.looksLikeOptions; var calculateArgs = function () { var finalParams, finalMerge, optionsArg; each(arguments, function (arg) { if (typeof arg === 'boolean') { finalMerge = arg; } else if (arg && typeof arg === 'object') { if (!looksLikeOptions(arg)) { finalParams = helpers.resolveHash(arg); } else { optionsArg = arg; } } }); if (!finalParams && optionsArg) { finalParams = helpers.resolveHash(optionsArg.hash); } return { finalParams: finalParams || {}, finalMerge: finalMerge, optionsArg: optionsArg }; }; helpers.registerHelper('routeUrl', function () { var args = calculateArgs.apply(this, arguments); return route.url(args.finalParams, typeof args.finalMerge === 'boolean' ? args.finalMerge : undefined); }); var routeCurrent = function () { var args = calculateArgs.apply(this, arguments); var result = route.current(args.finalParams, typeof args.finalMerge === 'boolean' ? args.finalMerge : undefined); if (args.optionsArg && !(args.optionsArg instanceof stacheExpression.Call)) { if (result) { return args.optionsArg.fn(); } else { return args.optionsArg.inverse(); } } else { return result; } }; routeCurrent.callAsMethod = true; helpers.registerHelper('routeCurrent', routeCurrent); }); /*can@4.0.0-pre.5#can*/ define('can', [ 'require', 'exports', 'module', 'can-util/namespace', 'can-component', 'can-connect/all', 'can-define/map/map', 'can-define/list/list', 'can-route', 'can-set', 'can-stache', 'can-stache-route-helpers', 'can-stache-bindings' ], function (require, exports, module) { (function (global, require, exports, module) { var can = require('can-util/namespace'); require('can-component'); require('can-connect/all'); require('can-define/map/map'); require('can-define/list/list'); require('can-route'); require('can-set'); require('can-stache'); require('can-stache-route-helpers'); require('can-stache-bindings'); module.exports = can; }(function () { return this; }(), require, exports, module)); }); /*[global-shim-end]*/ (function(global) { // jshint ignore:line global._define = global.define; global.define = global.define.orig; } )(typeof self == "object" && self.Object == Object ? self : window);
Libraries/Lists/MetroListView.js
hoastoolshop/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule MetroListView * @flow * @format */ 'use strict'; const ListView = require('ListView'); const React = require('React'); const RefreshControl = require('RefreshControl'); const ScrollView = require('ScrollView'); const invariant = require('fbjs/lib/invariant'); type Item = any; type NormalProps = { FooterComponent?: React.ComponentType<*>, renderItem: (info: Object) => ?React.Element<any>, /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment * suppresses an error when upgrading Flow's support for React. To see the * error delete this comment and run Flow. */ renderSectionHeader?: ({section: Object}) => ?React.Element<any>, SeparatorComponent?: ?React.ComponentType<*>, // not supported yet // Provide either `items` or `sections` items?: ?Array<Item>, // By default, an Item is assumed to be {key: string} // $FlowFixMe - Something is a little off with the type Array<Item> sections?: ?Array<{key: string, data: Array<Item>}>, /** * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make * sure to also set the `refreshing` prop correctly. */ onRefresh?: ?Function, /** * Set this true while waiting for new data from a refresh. */ refreshing?: boolean, /** * If true, renders items next to each other horizontally instead of stacked vertically. */ horizontal?: ?boolean, }; type DefaultProps = { keyExtractor: (item: Item, index: number) => string, }; type Props = NormalProps & DefaultProps; /** * This is just a wrapper around the legacy ListView that matches the new API of FlatList, but with * some section support tacked on. It is recommended to just use FlatList directly, this component * is mostly for debugging and performance comparison. */ class MetroListView extends React.Component<Props, $FlowFixMeState> { scrollToEnd(params?: ?{animated?: ?boolean}) { throw new Error('scrollToEnd not supported in legacy ListView.'); } scrollToIndex(params: { animated?: ?boolean, index: number, viewPosition?: number, }) { throw new Error('scrollToIndex not supported in legacy ListView.'); } scrollToItem(params: { animated?: ?boolean, item: Item, viewPosition?: number, }) { throw new Error('scrollToItem not supported in legacy ListView.'); } scrollToLocation(params: { animated?: ?boolean, itemIndex: number, sectionIndex: number, viewOffset?: number, viewPosition?: number, }) { throw new Error('scrollToLocation not supported in legacy ListView.'); } scrollToOffset(params: {animated?: ?boolean, offset: number}) { const {animated, offset} = params; this._listRef.scrollTo( this.props.horizontal ? {x: offset, animated} : {y: offset, animated}, ); } getListRef() { return this._listRef; } setNativeProps(props: Object) { if (this._listRef) { this._listRef.setNativeProps(props); } } static defaultProps: DefaultProps = { keyExtractor: (item, index) => item.key || String(index), renderScrollComponent: (props: Props) => { if (props.onRefresh) { return ( <ScrollView {...props} refreshControl={ /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) * This comment suppresses an error when upgrading Flow's support * for React. To see the error delete this comment and run Flow. */ <RefreshControl refreshing={props.refreshing} onRefresh={props.onRefresh} /> } /> ); } else { return <ScrollView {...props} />; } }, }; state = this._computeState(this.props, { ds: new ListView.DataSource({ rowHasChanged: (itemA, itemB) => true, sectionHeaderHasChanged: () => true, getSectionHeaderData: (dataBlob, sectionID) => this.state.sectionHeaderData[sectionID], }), sectionHeaderData: {}, }); UNSAFE_componentWillReceiveProps(newProps: Props) { this.setState(state => this._computeState(newProps, state)); } render() { return ( <ListView {...this.props} dataSource={this.state.ds} ref={this._captureRef} renderRow={this._renderRow} renderFooter={this.props.FooterComponent && this._renderFooter} renderSectionHeader={this.props.sections && this._renderSectionHeader} renderSeparator={this.props.SeparatorComponent && this._renderSeparator} /> ); } _listRef: ListView; _captureRef = ref => { this._listRef = ref; }; _computeState(props: Props, state) { const sectionHeaderData = {}; if (props.sections) { invariant(!props.items, 'Cannot have both sections and items props.'); const sections = {}; props.sections.forEach((sectionIn, ii) => { const sectionID = 's' + ii; sections[sectionID] = sectionIn.data; sectionHeaderData[sectionID] = sectionIn; }); return { ds: state.ds.cloneWithRowsAndSections(sections), sectionHeaderData, }; } else { invariant(!props.sections, 'Cannot have both sections and items props.'); return { ds: state.ds.cloneWithRows(props.items), sectionHeaderData, }; } } /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment * suppresses an error when upgrading Flow's support for React. To see the * error delete this comment and run Flow. */ _renderFooter = () => <this.props.FooterComponent key="$footer" />; _renderRow = (item, sectionID, rowID, highlightRow) => { return this.props.renderItem({item, index: rowID}); }; _renderSectionHeader = (section, sectionID) => { const {renderSectionHeader} = this.props; invariant( renderSectionHeader, 'Must provide renderSectionHeader with sections prop', ); return renderSectionHeader({section}); }; _renderSeparator = (sID, rID) => ( /* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment * suppresses an error when upgrading Flow's support for React. To see the * error delete this comment and run Flow. */ <this.props.SeparatorComponent key={sID + rID} /> ); } module.exports = MetroListView;
1_TEMPLATE/madmin/themeforest-7996710-madmin-responsive-multistyle-admin-template/code/style3/vendors/iCheck/demo/js/jquery.js
amir-samad-hanga/event
/*! * jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")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(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.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=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.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,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.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,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=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,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.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(e,t){return e.which==null&&(e.which=t.charCode!=null?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,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.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]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.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,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.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)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.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){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(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 lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={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,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.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=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[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","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
ajax/libs/oboe.js/1.10.3/oboe-browser.js
jonathantneal/cdnjs
// This file is the concatenation of many js files. // See https://github.com/jimhigson/oboe.js for the raw source (function (window, Object, Array, Error, undefined ) { // v1.10.2-2-g5f426d0 /* Copyright (c) 2013, Jim Higson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. */ /** * Partially complete a function. * * var add3 = partialComplete( function add(a,b){return a+b}, 3 ); * * add3(4) // gives 7 * * function wrap(left, right, cen){return left + " " + cen + " " + right;} * * var pirateGreeting = partialComplete( wrap , "I'm", ", a mighty pirate!" ); * * pirateGreeting("Guybrush Threepwood"); * // gives "I'm Guybrush Threepwood, a mighty pirate!" */ var partialComplete = varArgs(function( fn, args ) { // this isn't the shortest way to write this but it does // avoid creating a new array each time to pass to fn.apply, // otherwise could just call boundArgs.concat(callArgs) var numBoundArgs = args.length; return varArgs(function( callArgs ) { for (var i = 0; i < callArgs.length; i++) { args[numBoundArgs + i] = callArgs[i]; } args.length = numBoundArgs + callArgs.length; return fn.apply(this, args); }); }), /** * Compose zero or more functions: * * compose(f1, f2, f3)(x) = f1(f2(f3(x)))) * * The last (inner-most) function may take more than one parameter: * * compose(f1, f2, f3)(x,y) = f1(f2(f3(x,y)))) */ compose = varArgs(function(fns) { var fnsList = arrayAsList(fns); function next(params, curFn) { return [apply(params, curFn)]; } return varArgs(function(startParams){ return foldR(next, startParams, fnsList)[0]; }); }); /** * A more optimised version of compose that takes exactly two functions * @param f1 * @param f2 */ function compose2(f1, f2){ return function(){ return f1.call(this,f2.apply(this,arguments)); } } /** * Generic form for a function to get a property from an object * * var o = { * foo:'bar' * } * * var getFoo = attr('foo') * * fetFoo(o) // returns 'bar' * * @param {String} key the property name */ function attr(key) { return new Function('o', 'return o["' + key + '"]' ); } /** * Call a list of functions with the same args until one returns a * truthy result. Similar to the || operator. * * So: * lazyUnion([f1,f2,f3 ... fn])( p1, p2 ... pn ) * * Is equivalent to: * apply([p1, p2 ... pn], f1) || * apply([p1, p2 ... pn], f2) || * apply([p1, p2 ... pn], f3) ... apply(fn, [p1, p2 ... pn]) * * @returns the first return value that is given that is truthy. */ lazyUnion = varArgs(function(fns) { return varArgs(function(params){ var maybeValue; for (var i = 0; i < len(fns); i++) { maybeValue = apply(params, fns[i]); if( maybeValue ) { return maybeValue; } } }); }); /** * This file declares various pieces of functional programming. * * This isn't a general purpose functional library, to keep things small it * has just the parts useful for Oboe.js. */ /** * Call a single function with the given arguments array. * Basically, a functional-style version of the OO-style Function#apply for * when we don't care about the context ('this') of the call. * * The order of arguments allows partial completion of the arguments array */ function apply(args, fn) { return fn.apply(undefined, args); } /** * Define variable argument functions but cut out all that tedious messing about * with the arguments object. Delivers the variable-length part of the arguments * list as an array. * * Eg: * * var myFunction = varArgs( * function( fixedArgument, otherFixedArgument, variableNumberOfArguments ){ * console.log( variableNumberOfArguments ); * } * ) * * myFunction('a', 'b', 1, 2, 3); // logs [1,2,3] * * var myOtherFunction = varArgs(function( variableNumberOfArguments ){ * console.log( variableNumberOfArguments ); * }) * * myFunction(1, 2, 3); // logs [1,2,3] * */ function varArgs(fn){ var numberOfFixedArguments = fn.length -1, slice = Array.prototype.slice; if( numberOfFixedArguments == 0 ) { // an optimised case for when there are no fixed args: return function(){ return fn.call(this, slice.call(arguments)); } } else if( numberOfFixedArguments == 1 ) { // an optimised case for when there are is one fixed args: return function(){ return fn.call(this, arguments[0], slice.call(arguments, 1)); } } // general case // we know how many arguments fn will always take. Create a // fixed-size array to hold that many, to be re-used on // every call to the returned function var argsHolder = Array(fn.length); return function(){ for (var i = 0; i < numberOfFixedArguments; i++) { argsHolder[i] = arguments[i]; } argsHolder[numberOfFixedArguments] = slice.call(arguments, numberOfFixedArguments); return fn.apply( this, argsHolder); } } /** * Swap the order of parameters to a binary function * * A bit like this flip: http://zvon.org/other/haskell/Outputprelude/flip_f.html */ function flip(fn){ return function(a, b){ return fn(b,a); } } /** * Create a function which is the intersection of two other functions. * * Like the && operator, if the first is truthy, the second is never called, * otherwise the return value from the second is returned. */ function lazyIntersection(fn1, fn2) { return function (param) { return fn1(param) && fn2(param); }; } /** * A function which does nothing */ function noop(){} /** * A function which is always happy */ function always(){return true} /** * Create a function which always returns the same * value * * var return3 = functor(3); * * return3() // gives 3 * return3() // still gives 3 * return3() // will always give 3 */ function functor(val){ return function(){ return val; } } /** * This file defines some loosely associated syntactic sugar for * Javascript programming */ /** * Returns true if the given candidate is of type T */ function isOfType(T, maybeSomething){ return maybeSomething && maybeSomething.constructor === T; } var len = attr('length'), isString = partialComplete(isOfType, String); /** * I don't like saying this: * * foo !=== undefined * * because of the double-negative. I find this: * * defined(foo) * * easier to read. */ function defined( value ) { return value !== undefined; } /** * Returns true if object o has a key named like every property in * the properties array. Will give false if any are missing, or if o * is not an object. */ function hasAllProperties(fieldList, o) { return (o instanceof Object) && all(function (field) { return (field in o); }, fieldList); } /** * Like cons in Lisp */ function cons(x, xs) { /* Internally lists are linked 2-element Javascript arrays. So that lists are all immutable we Object.freeze in newer Javascript runtimes. In older engines freeze should have been polyfilled as the identity function. */ return Object.freeze([x,xs]); } /** * The empty list */ var emptyList = null, /** * Get the head of a list. * * Ie, head(cons(a,b)) = a */ head = attr(0), /** * Get the tail of a list. * * Ie, head(cons(a,b)) = a */ tail = attr(1); /** * Converts an array to a list * * asList([a,b,c]) * * is equivalent to: * * cons(a, cons(b, cons(c, emptyList))) **/ function arrayAsList(inputArray){ return reverseList( inputArray.reduce( flip(cons), emptyList ) ); } /** * A varargs version of arrayAsList. Works a bit like list * in LISP. * * list(a,b,c) * * is equivalent to: * * cons(a, cons(b, cons(c, emptyList))) */ var list = varArgs(arrayAsList); /** * Convert a list back to a js native array */ function listAsArray(list){ return foldR( function(arraySoFar, listItem){ arraySoFar.unshift(listItem); return arraySoFar; }, [], list ); } /** * Map a function over a list */ function map(fn, list) { return list ? cons(fn(head(list)), map(fn,tail(list))) : emptyList ; } /** * foldR implementation. Reduce a list down to a single value. * * @pram {Function} fn (rightEval, curVal) -> result */ function foldR(fn, startValue, list) { return list ? fn(foldR(fn, startValue, tail(list)), head(list)) : startValue ; } /** * foldR implementation. Reduce a list down to a single value. * * @pram {Function} fn (rightEval, curVal) -> result */ function foldR1(fn, list) { return tail(list) ? fn(foldR1(fn, tail(list)), head(list)) : head(list) ; } /** * Return a list like the one given but with the first instance equal * to item removed */ function without(list, test, removedFn) { return withoutInner(list, removedFn || noop); function withoutInner(subList, removedFn) { return subList ? ( test(head(subList)) ? (removedFn(head(subList)), tail(subList)) : cons(head(subList), withoutInner(tail(subList), removedFn)) ) : emptyList ; } } /** * Returns true if the given function holds for every item in * the list, false otherwise */ function all(fn, list) { return !list || ( fn(head(list)) && all(fn, tail(list)) ); } /** * Call every function in a list of functions with the same arguments * * This doesn't make any sense if we're doing pure functional because * it doesn't return anything. Hence, this is only really useful if the * functions being called have side-effects. */ function applyEach(fnList, arguments) { if( fnList ) { head(fnList).apply(null, arguments); applyEach(tail(fnList), arguments); } } /** * Reverse the order of a list */ function reverseList(list){ // js re-implementation of 3rd solution from: // http://www.haskell.org/haskellwiki/99_questions/Solutions/5 function reverseInner( list, reversedAlready ) { if( !list ) { return reversedAlready; } return reverseInner(tail(list), cons(head(list), reversedAlready)) } return reverseInner(list, emptyList); } function first(test, list) { return list && (test(head(list)) ? head(list) : first(test,tail(list))); } /* This is a slightly hacked-up browser only version of clarinet with some features removed to help keep Oboe under the 5k micro-library limit For the original go here: https://github.com/dscape/clarinet */ var clarinet = (function () { var clarinet = {} , fastlist = Array ; clarinet.parser = function () { return new CParser();}; clarinet.CParser = CParser; clarinet.MAX_BUFFER_LENGTH = 64 * 1024; clarinet.EVENTS = [ "value" , "string" , "key" , "openobject" , "closeobject" , "openarray" , "closearray" , "error" , "end" , "ready" ]; var buffers = [ "textNode", "numberNode" ] , _n = 0 ; var BEGIN = _n++; var VALUE = _n++; // general stuff var OPEN_OBJECT = _n++; // { var CLOSE_OBJECT = _n++; // } var OPEN_ARRAY = _n++; // [ var CLOSE_ARRAY = _n++; // ] var STRING = _n++; // "" var OPEN_KEY = _n++; // , "a" var CLOSE_KEY = _n++; // : var TRUE = _n++; // r var TRUE2 = _n++; // u var TRUE3 = _n++; // e var FALSE = _n++; // a var FALSE2 = _n++; // l var FALSE3 = _n++; // s var FALSE4 = _n++; // e var NULL = _n++; // u var NULL2 = _n++; // l var NULL3 = _n++; // l var NUMBER_DECIMAL_POINT = _n++; // . var NUMBER_DIGIT = _n; // [0-9] if (!Object.create) { Object.create = function (o) { function f () { this["__proto__"] = o; } f.prototype = o; return new f; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function (o) { return o["__proto__"]; }; } if (!Object.keys) { Object.keys = function (o) { var a = []; for (var i in o) if (o.hasOwnProperty(i)) a.push(i); return a; }; } function checkBufferLength (parser) { var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10) , maxActual = 0 ; for (var i = 0, l = buffers.length; i < l; i ++) { var len = parser[buffers[i]].length; if (len > maxAllowed) { switch (buffers[i]) { case "text": closeText(parser); break; default: error(parser, "Max buffer length exceeded: "+ buffers[i]); } } maxActual = Math.max(maxActual, len); } parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual) + parser.position; } function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i ++) { parser[buffers[i]] = ""; } } var stringTokenPattern = /[\\"\n]/g; function CParser () { if (!(this instanceof CParser)) return new CParser (); var parser = this; clearBuffers(parser); parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH; parser.q = parser.c = parser.p = ""; parser.closed = parser.closedRoot = parser.sawRoot = false; parser.tag = parser.error = null; parser.state = BEGIN; parser.stack = new fastlist(); // mostly just for error reporting parser.position = parser.column = 0; parser.line = 1; parser.slashed = false; parser.unicodeI = 0; parser.unicodeS = null; emit(parser, "onready"); } CParser.prototype = { end : function () { end(this); } , write : write , close : function () { return this.write(null); } }; function emit(parser, event, data) { if (parser[event]) parser[event](data); } function emitNode(parser, event, data) { closeValue(parser); emit(parser, event, data); } function closeValue(parser, event) { if (parser.textNode) { emit(parser, (event ? event : "onvalue"), parser.textNode); } parser.textNode = ""; } function closeNumber(parser) { if (parser.numberNode) emit(parser, "onvalue", parseFloat(parser.numberNode)); parser.numberNode = ""; } function error (parser, er) { closeValue(parser); er += "\nLine: "+parser.line+ "\nColumn: "+parser.column+ "\nChar: "+parser.c; er = new Error(er); parser.error = er; emit(parser, "onerror", er); return parser; } function end(parser) { if (parser.state !== VALUE) error(parser, "Unexpected end"); closeValue(parser); parser.c = ""; parser.closed = true; emit(parser, "onend"); CParser.call(parser); return parser; } function write (chunk) { var parser = this; // this used to throw the error but inside Oboe we will have already // gotten the error when it was emitted. The important thing is to // not continue with the parse. if (this.error) return; if (parser.closed) return error(parser, "Cannot write after close. Assign an onready handler."); if (chunk === null) return end(parser); var i = 0, c = chunk[0], p = parser.p; while (c) { p = c; parser.c = c = chunk.charAt(i++); // if chunk doesnt have next, like streaming char by char // this way we need to check if previous is really previous // if not we need to reset to what the parser says is the previous // from buffer if(p !== c ) parser.p = p; else p = parser.p; if(!c) break; parser.position ++; if (c === "\n") { parser.line ++; parser.column = 0; } else parser.column ++; switch (parser.state) { case BEGIN: if (c === "{") parser.state = OPEN_OBJECT; else if (c === "[") parser.state = OPEN_ARRAY; else if (c !== '\r' && c !== '\n' && c !== ' ' && c !== '\t') error(parser, "Non-whitespace before {[."); continue; case OPEN_KEY: case OPEN_OBJECT: if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; if(parser.state === OPEN_KEY) parser.stack.push(CLOSE_KEY); else { if(c === '}') { emit(parser, 'onopenobject'); emit(parser, 'oncloseobject'); parser.state = parser.stack.pop() || VALUE; continue; } else parser.stack.push(CLOSE_OBJECT); } if(c === '"') parser.state = STRING; else error(parser, "Malformed object key should start with \""); continue; case CLOSE_KEY: case CLOSE_OBJECT: if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; if(c===':') { if(parser.state === CLOSE_OBJECT) { parser.stack.push(CLOSE_OBJECT); closeValue(parser, 'onopenobject'); } else closeValue(parser, 'onkey'); parser.state = VALUE; } else if (c==='}') { emitNode(parser, 'oncloseobject'); parser.state = parser.stack.pop() || VALUE; } else if(c===',') { if(parser.state === CLOSE_OBJECT) parser.stack.push(CLOSE_OBJECT); closeValue(parser); parser.state = OPEN_KEY; } else error(parser, 'Bad object'); continue; case OPEN_ARRAY: // after an array there always a value case VALUE: if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; if(parser.state===OPEN_ARRAY) { emit(parser, 'onopenarray'); parser.state = VALUE; if(c === ']') { emit(parser, 'onclosearray'); parser.state = parser.stack.pop() || VALUE; continue; } else { parser.stack.push(CLOSE_ARRAY); } } if(c === '"') parser.state = STRING; else if(c === '{') parser.state = OPEN_OBJECT; else if(c === '[') parser.state = OPEN_ARRAY; else if(c === 't') parser.state = TRUE; else if(c === 'f') parser.state = FALSE; else if(c === 'n') parser.state = NULL; else if(c === '-') { // keep and continue parser.numberNode += c; } else if(c==='0') { parser.numberNode += c; parser.state = NUMBER_DIGIT; } else if('123456789'.indexOf(c) !== -1) { parser.numberNode += c; parser.state = NUMBER_DIGIT; } else error(parser, "Bad value"); continue; case CLOSE_ARRAY: if(c===',') { parser.stack.push(CLOSE_ARRAY); closeValue(parser, 'onvalue'); parser.state = VALUE; } else if (c===']') { emitNode(parser, 'onclosearray'); parser.state = parser.stack.pop() || VALUE; } else if (c === '\r' || c === '\n' || c === ' ' || c === '\t') continue; else error(parser, 'Bad array'); continue; case STRING: // thanks thejh, this is an about 50% performance improvement. var starti = i-1 , slashed = parser.slashed , unicodeI = parser.unicodeI ; STRING_BIGLOOP: while (true) { // zero means "no unicode active". 1-4 mean "parse some more". end after 4. while (unicodeI > 0) { parser.unicodeS += c; c = chunk.charAt(i++); if (unicodeI === 4) { // TODO this might be slow? well, probably not used too often anyway parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16)); unicodeI = 0; starti = i-1; } else { unicodeI++; } // we can just break here: no stuff we skipped that still has to be sliced out or so if (!c) break STRING_BIGLOOP; } if (c === '"' && !slashed) { parser.state = parser.stack.pop() || VALUE; parser.textNode += chunk.substring(starti, i-1); if(!parser.textNode) { emit(parser, "onvalue", ""); } break; } if (c === '\\' && !slashed) { slashed = true; parser.textNode += chunk.substring(starti, i-1); c = chunk.charAt(i++); if (!c) break; } if (slashed) { slashed = false; if (c === 'n') { parser.textNode += '\n'; } else if (c === 'r') { parser.textNode += '\r'; } else if (c === 't') { parser.textNode += '\t'; } else if (c === 'f') { parser.textNode += '\f'; } else if (c === 'b') { parser.textNode += '\b'; } else if (c === 'u') { // \uxxxx. meh! unicodeI = 1; parser.unicodeS = ''; } else { parser.textNode += c; } c = chunk.charAt(i++); starti = i-1; if (!c) break; else continue; } stringTokenPattern.lastIndex = i; var reResult = stringTokenPattern.exec(chunk); if (reResult === null) { i = chunk.length+1; parser.textNode += chunk.substring(starti, i-1); break; } i = reResult.index+1; c = chunk.charAt(reResult.index); if (!c) { parser.textNode += chunk.substring(starti, i-1); break; } } parser.slashed = slashed; parser.unicodeI = unicodeI; continue; case TRUE: if (c==='') continue; // strange buffers if (c==='r') parser.state = TRUE2; else error(parser, 'Invalid true started with t'+ c); continue; case TRUE2: if (c==='') continue; if (c==='u') parser.state = TRUE3; else error(parser, 'Invalid true started with tr'+ c); continue; case TRUE3: if (c==='') continue; if(c==='e') { emit(parser, "onvalue", true); parser.state = parser.stack.pop() || VALUE; } else error(parser, 'Invalid true started with tru'+ c); continue; case FALSE: if (c==='') continue; if (c==='a') parser.state = FALSE2; else error(parser, 'Invalid false started with f'+ c); continue; case FALSE2: if (c==='') continue; if (c==='l') parser.state = FALSE3; else error(parser, 'Invalid false started with fa'+ c); continue; case FALSE3: if (c==='') continue; if (c==='s') parser.state = FALSE4; else error(parser, 'Invalid false started with fal'+ c); continue; case FALSE4: if (c==='') continue; if (c==='e') { emit(parser, "onvalue", false); parser.state = parser.stack.pop() || VALUE; } else error(parser, 'Invalid false started with fals'+ c); continue; case NULL: if (c==='') continue; if (c==='u') parser.state = NULL2; else error(parser, 'Invalid null started with n'+ c); continue; case NULL2: if (c==='') continue; if (c==='l') parser.state = NULL3; else error(parser, 'Invalid null started with nu'+ c); continue; case NULL3: if (c==='') continue; if(c==='l') { emit(parser, "onvalue", null); parser.state = parser.stack.pop() || VALUE; } else error(parser, 'Invalid null started with nul'+ c); continue; case NUMBER_DECIMAL_POINT: if(c==='.') { parser.numberNode += c; parser.state = NUMBER_DIGIT; } else error(parser, 'Leading zero not followed by .'); continue; case NUMBER_DIGIT: if('0123456789'.indexOf(c) !== -1) parser.numberNode += c; else if (c==='.') { if(parser.numberNode.indexOf('.')!==-1) error(parser, 'Invalid number has two dots'); parser.numberNode += c; } else if (c==='e' || c==='E') { if(parser.numberNode.indexOf('e')!==-1 || parser.numberNode.indexOf('E')!==-1 ) error(parser, 'Invalid number has two exponential'); parser.numberNode += c; } else if (c==="+" || c==="-") { if(!(p==='e' || p==='E')) error(parser, 'Invalid symbol in number'); parser.numberNode += c; } else { closeNumber(parser); i--; // go back one parser.state = parser.stack.pop() || VALUE; } continue; default: error(parser, "Unknown state: " + parser.state); } } if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser); return parser; } return clarinet; })(); /** * A bridge used to assign stateless functions to listen to clarinet. * * As well as the parameter from clarinet, each callback will also be passed * the result of the last callback. * * This may also be used to clear all listeners by assigning zero handlers: * * clarinetListenerAdaptor( clarinet, {} ) */ function clarinetListenerAdaptor(clarinetParser, handlers){ var state; clarinet.EVENTS.forEach(function(eventName){ var handlerFunction = handlers[eventName]; clarinetParser['on'+eventName] = handlerFunction && function(param) { state = handlerFunction( state, param); }; }); } // based on gist https://gist.github.com/monsur/706839 /** * XmlHttpRequest's getAllResponseHeaders() method returns a string of response * headers according to the format described here: * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method * This method parses that string into a user-friendly key/value pair object. */ function parseResponseHeaders(headerStr) { var headers = {}; headerStr && headerStr.split('\u000d\u000a') .forEach(function(headerPair){ // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. var index = headerPair.indexOf('\u003a\u0020'); headers[headerPair.substring(0, index)] = headerPair.substring(index + 2); }); return headers; } function httpTransport(){ return new XMLHttpRequest(); } /** * A wrapper around the browser XmlHttpRequest object that raises an * event whenever a new part of the response is available. * * In older browsers progressive reading is impossible so all the * content is given in a single call. For newer ones several events * should be raised, allowing progressive interpretation of the response. * * @param {Function} oboeBus an event bus local to this Oboe instance * @param {XMLHttpRequest} xhr the xhr to use as the transport. Under normal * operation, will have been created using httpTransport() above * but for tests a stub can be provided instead. * @param {String} method one of 'GET' 'POST' 'PUT' 'PATCH' 'DELETE' * @param {String} url the url to make a request to * @param {String|Object} data some content to be sent with the request. * Only valid if method is POST or PUT. * @param {Object} [headers] the http request headers to send */ function streamingHttp(oboeBus, xhr, method, url, data, headers) { var emitStreamData = oboeBus(STREAM_DATA).emit, emitFail = oboeBus(FAIL_EVENT).emit, numberOfCharsAlreadyGivenToCallback = 0; // When an ABORTING message is put on the event bus abort // the ajax request oboeBus( ABORTING ).on( function(){ // if we keep the onreadystatechange while aborting the XHR gives // a callback like a successful call so first remove this listener // by assigning null: xhr.onreadystatechange = null; xhr.abort(); }); /** Given a value from the user to send as the request body, return in * a form that is suitable to sending over the wire. Returns either a * string, or null. */ function validatedRequestBody( body ) { if( !body ) return null; return isString(body)? body: JSON.stringify(body); } /** * Handle input from the underlying xhr: either a state change, * the progress event or the request being complete. */ function handleProgress() { var textSoFar = xhr.responseText, newText = textSoFar.substr(numberOfCharsAlreadyGivenToCallback); /* Raise the event for new text. On older browsers, the new text is the whole response. On newer/better ones, the fragment part that we got since last progress. */ if( newText ) { emitStreamData( newText ); } numberOfCharsAlreadyGivenToCallback = len(textSoFar); } if('onprogress' in xhr){ // detect browser support for progressive delivery xhr.onprogress = handleProgress; } xhr.onreadystatechange = function() { switch( xhr.readyState ) { case 2: oboeBus( HTTP_START ).emit( xhr.status, parseResponseHeaders(xhr.getAllResponseHeaders()) ); return; case 4: // is this a 2xx http code? var sucessful = String(xhr.status)[0] == 2; if( sucessful ) { // In Chrome 29 (not 28) no onprogress is emitted when a response // is complete before the onload. We need to always do handleInput // in case we get the load but have not had a final progress event. // This looks like a bug and may change in future but let's take // the safest approach and assume we might not have received a // progress event for each part of the response handleProgress(); oboeBus(STREAM_END).emit(); } else { emitFail( errorReport( xhr.status, xhr.responseText )); } } }; try{ xhr.open(method, url, true); for( var headerName in headers ){ xhr.setRequestHeader(headerName, headers[headerName]); } xhr.send(validatedRequestBody(data)); } catch( e ) { // To keep a consistent interface with Node, we can't emit an event here. // Node's streaming http adaptor receives the error as an asynchronous // event rather than as an exception. If we emitted now, the Oboe user // has had no chance to add a .fail listener so there is no way // the event could be useful. For both these reasons defer the // firing to the next JS frame. window.setTimeout( partialComplete(emitFail, errorReport(undefined, undefined, e)) , 0 ); } } var jsonPathSyntax = (function() { var /** * Export a regular expression as a simple function by exposing just * the Regex#exec. This allows regex tests to be used under the same * interface as differently implemented tests, or for a user of the * tests to not concern themselves with their implementation as regular * expressions. * * This could also be expressed point-free as: * Function.prototype.bind.bind(RegExp.prototype.exec), * * But that's far too confusing! (and not even smaller once minified * and gzipped) */ regexDescriptor = function regexDescriptor(regex) { return regex.exec.bind(regex); } /** * Join several regular expressions and express as a function. * This allows the token patterns to reuse component regular expressions * instead of being expressed in full using huge and confusing regular * expressions. */ , jsonPathClause = varArgs(function( componentRegexes ) { // The regular expressions all start with ^ because we // only want to find matches at the start of the // JSONPath fragment we are inspecting componentRegexes.unshift(/^/); return regexDescriptor( RegExp( componentRegexes.map(attr('source')).join('') ) ); }) , possiblyCapturing = /(\$?)/ , namedNode = /([\w-_]+|\*)/ , namePlaceholder = /()/ , nodeInArrayNotation = /\["([^"]+)"\]/ , numberedNodeInArrayNotation = /\[(\d+|\*)\]/ , fieldList = /{([\w ]*?)}/ , optionalFieldList = /(?:{([\w ]*?)})?/ // foo or * , jsonPathNamedNodeInObjectNotation = jsonPathClause( possiblyCapturing, namedNode, optionalFieldList ) // ["foo"] , jsonPathNamedNodeInArrayNotation = jsonPathClause( possiblyCapturing, nodeInArrayNotation, optionalFieldList ) // [2] or [*] , jsonPathNumberedNodeInArrayNotation = jsonPathClause( possiblyCapturing, numberedNodeInArrayNotation, optionalFieldList ) // {a b c} , jsonPathPureDuckTyping = jsonPathClause( possiblyCapturing, namePlaceholder, fieldList ) // .. , jsonPathDoubleDot = jsonPathClause(/\.\./) // . , jsonPathDot = jsonPathClause(/\./) // ! , jsonPathBang = jsonPathClause( possiblyCapturing, /!/ ) // nada! , emptyString = jsonPathClause(/$/) ; /* We export only a single function. When called, this function injects into another function the descriptors from above. */ return function (fn){ return fn( lazyUnion( jsonPathNamedNodeInObjectNotation , jsonPathNamedNodeInArrayNotation , jsonPathNumberedNodeInArrayNotation , jsonPathPureDuckTyping ) , jsonPathDoubleDot , jsonPathDot , jsonPathBang , emptyString ); }; }()); /** * Get a new key->node mapping * * @param {String|Number} key * @param {Object|Array|String|Number|null} node a value found in the json */ function namedNode(key, node) { return {key:key, node:node}; } /** get the key of a namedNode */ var keyOf = attr('key'); /** get the node from a namedNode */ var nodeOf = attr('node'); /** * This file provides various listeners which can be used to build up * a changing ascent based on the callbacks provided by Clarinet. It listens * to the low-level events from Clarinet and emits higher-level ones. * * The building up is stateless so to track a JSON file * clarinetListenerAdaptor.js is required to store the ascent state * between calls. */ /** * A special value to use in the path list to represent the path 'to' a root * object (which doesn't really have any path). This prevents the need for * special-casing detection of the root object and allows it to be treated * like any other object. We might think of this as being similar to the * 'unnamed root' domain ".", eg if I go to * http://en.wikipedia.org./wiki/En/Main_page the dot after 'org' deliminates * the unnamed root of the DNS. * * This is kept as an object to take advantage that in Javascript's OO objects * are guaranteed to be distinct, therefore no other object can possibly clash * with this one. Strings, numbers etc provide no such guarantee. **/ var ROOT_PATH = {}; /** * Create a new set of handlers for clarinet's events, bound to the emit * function given. */ function incrementalContentBuilder( oboeBus ) { var emitNodeFound = oboeBus(NODE_FOUND).emit, emitRootFound = oboeBus(ROOT_FOUND).emit, emitPathFound = oboeBus(PATH_FOUND).emit; function arrayIndicesAreKeys( possiblyInconsistentAscent, newDeepestNode) { /* for values in arrays we aren't pre-warned of the coming paths (Clarinet gives no call to onkey like it does for values in objects) so if we are in an array we need to create this path ourselves. The key will be len(parentNode) because array keys are always sequential numbers. */ var parentNode = nodeOf( head( possiblyInconsistentAscent)); return isOfType( Array, parentNode) ? pathFound( possiblyInconsistentAscent, len(parentNode), newDeepestNode ) : // nothing needed, return unchanged possiblyInconsistentAscent ; } function nodeFound( ascent, newDeepestNode ) { if( !ascent ) { // we discovered the root node, emitRootFound( newDeepestNode); return pathFound( ascent, ROOT_PATH, newDeepestNode); } // we discovered a non-root node var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), ancestorBranches = tail( arrayConsistentAscent), previouslyUnmappedName = keyOf( head( arrayConsistentAscent)); appendBuiltContent( ancestorBranches, previouslyUnmappedName, newDeepestNode ); return cons( namedNode( previouslyUnmappedName, newDeepestNode ), ancestorBranches ); } /** * Add a new value to the object we are building up to represent the * parsed JSON */ function appendBuiltContent( ancestorBranches, key, node ){ nodeOf( head( ancestorBranches))[key] = node; } /** * For when we find a new key in the json. * * @param {String|Number|Object} newDeepestName the key. If we are in an * array will be a number, otherwise a string. May take the special * value ROOT_PATH if the root node has just been found * * @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode] * usually this won't be known so can be undefined. Can't use null * to represent unknown because null is a valid value in JSON **/ function pathFound(ascent, newDeepestName, maybeNewDeepestNode) { if( ascent ) { // if not root // If we have the key but (unless adding to an array) no known value // yet. Put that key in the output but against no defined value: appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode ); } var ascentWithNewPath = cons( namedNode( newDeepestName, maybeNewDeepestNode), ascent ); emitPathFound( ascentWithNewPath); return ascentWithNewPath; } /** * For when the current node ends */ function nodeFinished( ascent ) { emitNodeFound( ascent); // pop the complete node and its path off the list: return tail( ascent); } return { openobject : function (ascent, firstKey) { var ascentAfterNodeFound = nodeFound(ascent, {}); /* It is a perculiarity of Clarinet that for non-empty objects it gives the first key with the openobject event instead of in a subsequent key event. firstKey could be the empty string in a JSON object like {'':'foo'} which is technically valid. So can't check with !firstKey, have to see if has any defined value. */ return defined(firstKey) ? /* We know the first key of the newly parsed object. Notify that path has been found but don't put firstKey permanently onto pathList yet because we haven't identified what is at that key yet. Give null as the value because we haven't seen that far into the json yet */ pathFound(ascentAfterNodeFound, firstKey) : ascentAfterNodeFound ; }, openarray: function (ascent) { return nodeFound(ascent, []); }, // called by Clarinet when keys are found in objects key: pathFound, /* Emitted by Clarinet when primitive values are found, ie Strings, Numbers, and null. Because these are always leaves in the JSON, we find and finish the node in one step, expressed as functional composition: */ value: compose2( nodeFinished, nodeFound ), // we make no distinction in how we handle object and arrays closing. // For both, interpret as the end of the current node. closeobject: nodeFinished, closearray: nodeFinished }; } /** * The jsonPath evaluator compiler used for Oboe.js. * * One function is exposed. This function takes a String JSONPath spec and * returns a function to test candidate ascents for matches. * * String jsonPath -> (List ascent) -> Boolean|Object * * This file is coded in a pure functional style. That is, no function has * side effects, every function evaluates to the same value for the same * arguments and no variables are reassigned. */ // the call to jsonPathSyntax injects the token syntaxes that are needed // inside the compiler var jsonPathCompiler = jsonPathSyntax(function (pathNodeSyntax, doubleDotSyntax, dotSyntax, bangSyntax, emptySyntax ) { var CAPTURING_INDEX = 1; var NAME_INDEX = 2; var FIELD_LIST_INDEX = 3; var headKey = compose2(keyOf, head), headNode = compose2(nodeOf, head); /** * Create an evaluator function for a named path node, expressed in the * JSONPath like: * foo * ["bar"] * [2] */ function nameClause(previousExpr, detection ) { var name = detection[NAME_INDEX], matchesName = ( !name || name == '*' ) ? always : function(ascent){return headKey(ascent) == name}; return lazyIntersection(matchesName, previousExpr); } /** * Create an evaluator function for a a duck-typed node, expressed like: * * {spin, taste, colour} * .particle{spin, taste, colour} * *{spin, taste, colour} */ function duckTypeClause(previousExpr, detection) { var fieldListStr = detection[FIELD_LIST_INDEX]; if (!fieldListStr) return previousExpr; // don't wrap at all, return given expr as-is var hasAllrequiredFields = partialComplete( hasAllProperties, arrayAsList(fieldListStr.split(/\W+/)) ), isMatch = compose2( hasAllrequiredFields, headNode ); return lazyIntersection(isMatch, previousExpr); } /** * Expression for $, returns the evaluator function */ function capture( previousExpr, detection ) { // extract meaning from the detection var capturing = !!detection[CAPTURING_INDEX]; if (!capturing) return previousExpr; // don't wrap at all, return given expr as-is return lazyIntersection(previousExpr, head); } /** * Create an evaluator function that moves onto the next item on the * lists. This function is the place where the logic to move up a * level in the ascent exists. * * Eg, for JSONPath ".foo" we need skip1(nameClause(always, [,'foo'])) */ function skip1(previousExpr) { if( previousExpr == always ) { /* If there is no previous expression this consume command is at the start of the jsonPath. Since JSONPath specifies what we'd like to find but not necessarily everything leading down to it, when running out of JSONPath to check against we default to true */ return always; } /** return true if the ascent we have contains only the JSON root, * false otherwise */ function notAtRoot(ascent){ return headKey(ascent) != ROOT_PATH; } return lazyIntersection( /* If we're already at the root but there are more expressions to satisfy, can't consume any more. No match. This check is why none of the other exprs have to be able to handle empty lists; skip1 is the only evaluator that moves onto the next token and it refuses to do so once it reaches the last item in the list. */ notAtRoot, /* We are not at the root of the ascent yet. Move to the next level of the ascent by handing only the tail to the previous expression */ compose2(previousExpr, tail) ); } /** * Create an evaluator function for the .. (double dot) token. Consumes * zero or more levels of the ascent, the fewest that are required to find * a match when given to previousExpr. */ function skipMany(previousExpr) { if( previousExpr == always ) { /* If there is no previous expression this consume command is at the start of the jsonPath. Since JSONPath specifies what we'd like to find but not necessarily everything leading down to it, when running out of JSONPath to check against we default to true */ return always; } var // In JSONPath .. is equivalent to !.. so if .. reaches the root // the match has succeeded. Ie, we might write ..foo or !..foo // and both should match identically. terminalCaseWhenArrivingAtRoot = rootExpr(), terminalCaseWhenPreviousExpressionIsSatisfied = previousExpr, recursiveCase = skip1(skipManyInner), cases = lazyUnion( terminalCaseWhenArrivingAtRoot , terminalCaseWhenPreviousExpressionIsSatisfied , recursiveCase ); function skipManyInner(ascent) { if( !ascent ) { // have gone past the start, not a match: return false; } return cases(ascent); } return skipManyInner; } /** * Generate an evaluator for ! - matches only the root element of the json * and ignores any previous expressions since nothing may precede !. */ function rootExpr() { return function(ascent){ return headKey(ascent) == ROOT_PATH; }; } /** * Generate a statement wrapper to sit around the outermost * clause evaluator. * * Handles the case where the capturing is implicit because the JSONPath * did not contain a '$' by returning the last node. */ function statementExpr(lastClause) { return function(ascent) { // kick off the evaluation by passing through to the last clause var exprMatch = lastClause(ascent); return exprMatch === true ? head(ascent) : exprMatch; }; } /** * For when a token has been found in the JSONPath input. * Compiles the parser for that token and returns in combination with the * parser already generated. * * @param {Function} exprs a list of the clause evaluator generators for * the token that was found * @param {Function} parserGeneratedSoFar the parser already found * @param {Array} detection the match given by the regex engine when * the feature was found */ function expressionsReader( exprs, parserGeneratedSoFar, detection ) { // if exprs is zero-length foldR will pass back the // parserGeneratedSoFar as-is so we don't need to treat // this as a special case return foldR( function( parserGeneratedSoFar, expr ){ return expr(parserGeneratedSoFar, detection); }, parserGeneratedSoFar, exprs ); } /** * If jsonPath matches the given detector function, creates a function which * evaluates against every clause in the clauseEvaluatorGenerators. The * created function is propagated to the onSuccess function, along with * the remaining unparsed JSONPath substring. * * The intended use is to create a clauseMatcher by filling in * the first two arguments, thus providing a function that knows * some syntax to match and what kind of generator to create if it * finds it. The parameter list once completed is: * * (jsonPath, parserGeneratedSoFar, onSuccess) * * onSuccess may be compileJsonPathToFunction, to recursively continue * parsing after finding a match or returnFoundParser to stop here. */ function generateClauseReaderIfTokenFound ( tokenDetector, clauseEvaluatorGenerators, jsonPath, parserGeneratedSoFar, onSuccess) { var detected = tokenDetector(jsonPath); if(detected) { var compiledParser = expressionsReader( clauseEvaluatorGenerators, parserGeneratedSoFar, detected ), remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); return onSuccess(remainingUnparsedJsonPath, compiledParser); } } /** * Partially completes generateClauseReaderIfTokenFound above. */ function clauseMatcher(tokenDetector, exprs) { return partialComplete( generateClauseReaderIfTokenFound, tokenDetector, exprs ); } /** * clauseForJsonPath is a function which attempts to match against * several clause matchers in order until one matches. If non match the * jsonPath expression is invalid and an error is thrown. * * The parameter list is the same as a single clauseMatcher: * * (jsonPath, parserGeneratedSoFar, onSuccess) */ var clauseForJsonPath = lazyUnion( clauseMatcher(pathNodeSyntax , list( capture, duckTypeClause, nameClause, skip1 )) , clauseMatcher(doubleDotSyntax , list( skipMany)) // dot is a separator only (like whitespace in other languages) but // rather than make it a special case, use an empty list of // expressions when this token is found , clauseMatcher(dotSyntax , list() ) , clauseMatcher(bangSyntax , list( capture, rootExpr)) , clauseMatcher(emptySyntax , list( statementExpr)) , function (jsonPath) { throw Error('"' + jsonPath + '" could not be tokenised') } ); /** * One of two possible values for the onSuccess argument of * generateClauseReaderIfTokenFound. * * When this function is used, generateClauseReaderIfTokenFound simply * returns the compiledParser that it made, regardless of if there is * any remaining jsonPath to be compiled. */ function returnFoundParser(_remainingJsonPath, compiledParser){ return compiledParser } /** * Recursively compile a JSONPath expression. * * This function serves as one of two possible values for the onSuccess * argument of generateClauseReaderIfTokenFound, meaning continue to * recursively compile. Otherwise, returnFoundParser is given and * compilation terminates. */ function compileJsonPathToFunction( uncompiledJsonPath, parserGeneratedSoFar ) { /** * On finding a match, if there is remaining text to be compiled * we want to either continue parsing using a recursive call to * compileJsonPathToFunction. Otherwise, we want to stop and return * the parser that we have found so far. */ var onFind = uncompiledJsonPath ? compileJsonPathToFunction : returnFoundParser; return clauseForJsonPath( uncompiledJsonPath, parserGeneratedSoFar, onFind ); } /** * This is the function that we expose to the rest of the library. */ return function(jsonPath){ try { // Kick off the recursive parsing of the jsonPath return compileJsonPathToFunction(jsonPath, always); } catch( e ) { throw Error( 'Could not compile "' + jsonPath + '" because ' + e.message ); } } }); /** * A pub/sub which is responsible for a single event type. A * multi-event type event bus is created by pubSub by collecting * several of these. * * @param {String} eventType * the name of the events managed by this singleEventPubSub * @param {singleEventPubSub} [newListener] * place to notify of new listeners * @param {singleEventPubSub} [removeListener] * place to notify of when listeners are removed */ function singleEventPubSub(eventType, newListener, removeListener){ /** we are optimised for emitting events over firing them. * As well as the tuple list which stores event ids and * listeners there is a list with just the listeners which * can be iterated more quickly when we are emitting */ var listenerTupleList, listenerList; function hasId(id){ return function(tuple) { return tuple.id == id; }; } return { /** * @param {Function} listener * @param {*} listenerId * an id that this listener can later by removed by. * Can be of any type, to be compared to other ids using == */ on:function( listener, listenerId ) { var tuple = { listener: listener , id: listenerId || listener // when no id is given use the // listener function as the id }; if( newListener ) { newListener.emit(eventType, listener, tuple.id); } listenerTupleList = cons( tuple, listenerTupleList ); listenerList = cons( listener, listenerList ); return this; // chaining }, emit:function () { applyEach( listenerList, arguments ); }, un: function( listenerId ) { var removed; listenerTupleList = without( listenerTupleList, hasId(listenerId), function(tuple){ removed = tuple; } ); if( removed ) { listenerList = without( listenerList, function(listener){ return listener == removed.listener; }); if( removeListener ) { removeListener.emit(eventType, removed.listener, removed.id); } } }, listeners: function(){ // differs from Node EventEmitter: returns list, not array return listenerList; }, hasListener: function(listenerId){ var test = listenerId? hasId(listenerId) : always; return defined(first( test, listenerTupleList)); } }; } /** * pubSub is a curried interface for listening to and emitting * events. * * If we get a bus: * * var bus = pubSub(); * * We can listen to event 'foo' like: * * bus('foo').on(myCallback) * * And emit event foo like: * * bus('foo').emit() * * or, with a parameter: * * bus('foo').emit('bar') * * All functions can be cached and don't need to be * bound. Ie: * * var fooEmitter = bus('foo').emit * fooEmitter('bar'); // emit an event * fooEmitter('baz'); // emit another * * There's also an uncurried[1] shortcut for .emit and .on: * * bus.on('foo', callback) * bus.emit('foo', 'bar') * * [1]: http://zvon.org/other/haskell/Outputprelude/uncurry_f.html */ function pubSub(){ var singles = {}, newListener = newSingle('newListener'), removeListener = newSingle('removeListener'); function newSingle(eventName) { return singles[eventName] = singleEventPubSub( eventName, newListener, removeListener ); } /** pubSub instances are functions */ function pubSubInstance( eventName ){ return singles[eventName] || newSingle( eventName ); } // add convenience EventEmitter-style uncurried form of 'emit' and 'on' ['emit', 'on', 'un'].forEach(function(methodName){ pubSubInstance[methodName] = varArgs(function(eventName, parameters){ apply( parameters, pubSubInstance( eventName )[methodName]); }); }) return pubSubInstance; } /** * This file declares some constants to use as names for event types. */ var // the events which are never exported are kept as // the smallest possible representation, in numbers: _S = 1, // fired whenever a node is found in the JSON: NODE_FOUND = _S++, // fired whenever a path is found in the JSON: PATH_FOUND = _S++, FAIL_EVENT = 'fail', ROOT_FOUND = _S++, HTTP_START = 'start', STREAM_DATA = 'content', STREAM_END = _S++, ABORTING = _S++; function errorReport(statusCode, body, error) { try{ var jsonBody = JSON.parse(body); }catch(e){} return { statusCode:statusCode, body:body, jsonBody:jsonBody, thrown:error }; } function patternAdapter(oboeBus, jsonPathCompiler) { var predicateEventMap = { node:oboeBus(NODE_FOUND) , path:oboeBus(PATH_FOUND) }; function emitMatchingNode(emitMatch, node, ascent) { /* We're now calling to the outside world where Lisp-style lists will not be familiar. Convert to standard arrays. Also, reverse the order because it is more common to list paths "root to leaf" than "leaf to root" */ var descent = reverseList(ascent); emitMatch( node, // To make a path, strip off the last item which is the special // ROOT_PATH token for the 'path' to the root node listAsArray(tail(map(keyOf,descent))), // path listAsArray(map(nodeOf, descent)) // ancestors ); } function addUnderlyingListener( fullEventName, predicateEvent, compiledJsonPath ){ var emitMatch = oboeBus(fullEventName).emit; predicateEvent.on( function (ascent) { var maybeMatchingMapping = compiledJsonPath(ascent); /* Possible values for maybeMatchingMapping are now: false: we did not match an object/array/string/number/null: we matched and have the node that matched. Because nulls are valid json values this can be null. undefined: we matched but don't have the matching node yet. ie, we know there is an upcoming node that matches but we can't say anything else about it. */ if (maybeMatchingMapping !== false) { emitMatchingNode( emitMatch, nodeOf(maybeMatchingMapping), ascent ); } }, fullEventName); oboeBus('removeListener').on( function(removedEventName){ // if the match even listener is later removed, clean up by removing // the underlying listener if nothing else is using that pattern: if( removedEventName == fullEventName ) { if( !oboeBus(removedEventName).listeners( )) { predicateEvent.un( fullEventName ); } } }); } oboeBus('newListener').on( function(fullEventName){ var match = /(node|path):(.*)/.exec(fullEventName); if( match ) { var predicateEvent = predicateEventMap[match[1]]; if( !predicateEvent.hasListener( fullEventName) ) { addUnderlyingListener( fullEventName, predicateEvent, jsonPathCompiler( match[2] ) ); } } }) } /** * The instance API is the thing that is returned when oboe() is called. * it allows: * * - listeners for various events to be added and removed * - the http response header/headers to be read */ function instanceApi(oboeBus){ var oboeApi, fullyQualifiedNamePattern = /^(node|path):./, rootNodeFinishedEvent = oboeBus('node:!'), /** * Add any kind of listener that the instance api exposes */ addListener = varArgs(function( eventId, parameters ){ if( oboeApi[eventId] ) { // for events added as .on(event, callback), if there is a // .event() equivalent with special behaviour , pass through // to that: apply(parameters, oboeApi[eventId]); } else { // we have a standard Node.js EventEmitter 2-argument call. // The first parameter is the listener. var event = oboeBus(eventId), listener = parameters[0]; if( fullyQualifiedNamePattern.test(eventId) ) { // allow fully-qualified node/path listeners // to be added addForgettableCallback(event, listener); } else { // the event has no special handling, pass through // directly onto the event bus: event.on( listener); } } return oboeApi; // chaining }), /** * Remove any kind of listener that the instance api exposes */ removeListener = function( eventId, p2, p3 ){ if( eventId == 'done' ) { rootNodeFinishedEvent.un(p2); } else if( eventId == 'node' || eventId == 'path' ) { // allow removal of node and path oboeBus.un(eventId + ':' + p2, p3); } else { // we have a standard Node.js EventEmitter 2-argument call. // The second parameter is the listener. This may be a call // to remove a fully-qualified node/path listener but requires // no special handling var listener = p2; oboeBus(eventId).un(listener); } return oboeApi; // chaining }; /** * Add a callback, wrapped in a try/catch so as to not break the * execution of Oboe if an exception is thrown (fail events are * fired instead) * * The callback is used as the listener id so that it can later be * removed using .un(callback) */ function addProtectedCallback(eventName, callback) { oboeBus(eventName).on(protectedCallback(callback), callback); return oboeApi; // chaining } /** * Add a callback where, if .forget() is called during the callback's * execution, the callback will be de-registered */ function addForgettableCallback(event, callback) { var safeCallback = protectedCallback(callback); event.on( function() { var discard = false; oboeApi.forget = function(){ discard = true; }; apply( arguments, safeCallback ); delete oboeApi.forget; if( discard ) { event.un(callback); } }, callback) return oboeApi; // chaining } function protectedCallback( callback ) { return function() { try{ callback.apply(oboeApi, arguments); }catch(e) { // An error occured during the callback, publish it on the event bus oboeBus(FAIL_EVENT).emit( errorReport(undefined, undefined, e)); } } } /** * Return the fully qualified event for when a pattern matches * either a node or a path * * @param type {String} either 'node' or 'path' */ function fullyQualifiedPatternMatchEvent(type, pattern) { return oboeBus(type + ':' + pattern); } /** * Add several listeners at a time, from a map */ function addListenersMap(eventId, listenerMap) { for( var pattern in listenerMap ) { addForgettableCallback( fullyQualifiedPatternMatchEvent(eventId, pattern), listenerMap[pattern] ); } } /** * implementation behind .onPath() and .onNode() */ function addNodeOrPathListenerApi( eventId, jsonPathOrListenerMap, callback ){ if( isString(jsonPathOrListenerMap) ) { addForgettableCallback( fullyQualifiedPatternMatchEvent(eventId, jsonPathOrListenerMap), callback ); } else { addListenersMap(eventId, jsonPathOrListenerMap); } return oboeApi; // chaining } // some interface methods are only filled in after we recieve // values and are noops before that: oboeBus(ROOT_FOUND).on( function(root) { oboeApi.root = functor(root); }); /** * When content starts make the headers readable through the * instance API */ oboeBus(HTTP_START).on( function(_statusCode, headers) { oboeApi.header = function(name) { return name ? headers[name] : headers ; } }); /** * Construct and return the public API of the Oboe instance to be * returned to the calling application */ return oboeApi = { on : addListener, addListener : addListener, removeListener : removeListener, emit : oboeBus.emit, node : partialComplete(addNodeOrPathListenerApi, 'node'), path : partialComplete(addNodeOrPathListenerApi, 'path'), done : partialComplete(addForgettableCallback, rootNodeFinishedEvent), start : partialComplete(addProtectedCallback, HTTP_START ), // fail doesn't use protectedCallback because // could lead to non-terminating loops fail : oboeBus(FAIL_EVENT).on, // public api calling abort fires the ABORTING event abort : oboeBus(ABORTING).emit, // initially return nothing for header and root header : noop, root : noop }; } /** * This file implements a light-touch central controller for an instance * of Oboe which provides the methods used for interacting with the instance * from the calling app. */ function instanceController( oboeBus, clarinetParser, contentBuilderHandlers) { oboeBus(STREAM_DATA).on( clarinetParser.write.bind(clarinetParser)); /* At the end of the http content close the clarinet parser. This will provide an error if the total content provided was not valid json, ie if not all arrays, objects and Strings closed properly */ oboeBus(STREAM_END).on( clarinetParser.close.bind(clarinetParser)); /* If we abort this Oboe's request stop listening to the clarinet parser. This prevents more tokens being found after we abort in the case where we aborted during processing of an already filled buffer. */ oboeBus(ABORTING).on( function() { clarinetListenerAdaptor(clarinetParser, {}); }); clarinetListenerAdaptor(clarinetParser, contentBuilderHandlers); // react to errors by putting them on the event bus clarinetParser.onerror = function(e) { oboeBus(FAIL_EVENT).emit( errorReport(undefined, undefined, e) ); // note: don't close clarinet here because if it was not expecting // end of the json it will throw an error }; } /** * This file sits just behind the API which is used to attain a new * Oboe instance. It creates the new components that are required * and introduces them to each other. */ function wire (httpMethodName, contentSource, body, headers){ var oboeBus = pubSub(); // Wire the input stream in if we are given a content source. // This will usually be the case. If not, the instance created // will have to be passed content from an external source. if( contentSource ) { streamingHttp( oboeBus, httpTransport(), httpMethodName, contentSource, body, headers ); } instanceController( oboeBus, clarinet.parser(), incrementalContentBuilder(oboeBus) ); patternAdapter(oboeBus, jsonPathCompiler); return new instanceApi(oboeBus); } // export public API function oboe(arg1, arg2) { if( arg1 ) { if (arg1.url) { // method signature is: // oboe({method:m, url:u, body:b, headers:{...}}) return wire( (arg1.method || 'GET'), url(arg1.url, arg1.cached), arg1.body, arg1.headers ); } else { // simple version for GETs. Signature is: // oboe( url ) // return wire( 'GET', arg1, // url arg2 // body. Deprecated, use {url:u, body:b} instead ); } } else { // wire up a no-AJAX Oboe. Will have to have content // fed in externally and fed in using .emit. return wire(); } function url(baseUrl, cached) { if( cached === false ) { if( baseUrl.indexOf('?') == -1 ) { baseUrl += '?'; } else { baseUrl += '&'; } baseUrl += '_=' + new Date().getTime(); } return baseUrl; } } ;if ( typeof define === "function" && define.amd ) {define( "oboe", [], function () { return oboe; } );} else {window.oboe = oboe;}})(window, Object, Array, Error);
src/mention/test-pages/async.js
catalinmiron/react-tinymce-mention
import React from 'react'; import axios from 'axios'; import Editor from './components/Editor'; import Mention from '../Mention'; import CustomList from './components/CustomList'; React.render( <div> <Editor /> <Mention showDebugger={true} delimiter={'@'} asyncDataSource={(query) => { return new Promise(resolve => { axios.get(`/public/api/complex.json?q=${query}`) .then(response => { setTimeout(() => { resolve(transformDataSource(response.data)); }, 500); }); }); }} customListRenderer={({ highlightIndex, matchedSources, clickFn, fetching }) => { return ( <CustomList fetching={fetching} highlightIndex={highlightIndex} matchedSources={matchedSources} onClick={clickFn} /> ); }} /> </div> , document.getElementById('root')); function transformDataSource(dataSource) { const complexDataSource = dataSource.map(result => { const { fullName } = result; return { searchKey: fullName, displayLabel: fullName }; }); return complexDataSource; }
src/DonutChart.js
MrCheater/habrahabr-universal-component
import React from 'react'; export default class DonutChart extends React.Component { render() { const { radius, holeSize, text, value, total, backgroundColor, valueColor } = this.props; const r = radius * (1 - (1 - holeSize)/2); const width = radius * (1 - holeSize); const circumference = 2 * Math.PI * r; const strokeDasharray = ((value * circumference) / total) + ' ' + circumference; const transform = 'rotate(-90 ' + radius + ',' + radius + ')'; const fontSize = r * holeSize * 0.6; return ( <div style = {{ textAlign: 'center', fontFamily: 'sans-serif' }}> <svg width = {radius * 2 + 'px'} height = {radius * 2 + 'px'} > <circle r = {r + 'px'} cx = {radius + 'px'} cy = {radius + 'px'} transform = {transform} strokeWidth = {width} stroke = {backgroundColor} fill = 'none' /> <circle r = {r + 'px'} cx = {radius + 'px'} cy = {radius + 'px'} transform = {transform} strokeWidth = {width} strokeDasharray = {strokeDasharray} fill = 'none' stroke = {valueColor} /> <text x = {radius + 'px'} y = {radius + 'px' } dy = {fontSize/3 + 'px'} textAnchor = 'middle' fill = {valueColor} fontSize = {fontSize + 'px'} > {~~(value * 1000 / total) / 10}% </text> </svg> <div style = {{ marginTop: '10px' }}> {text} </div> </div> ); } } DonutChart.defaultProps = { holeSize : 0.8, radius : 65, backgroundColor : '#d1d8e7', valueColor : '#49649f' }; DonutChart.propTypes = { radius : React.PropTypes.number.isRequired, holeSize : React.PropTypes.number.isRequired, //0...1 text : React.PropTypes.string.isRequired, value : React.PropTypes.number.isRequired, total : React.PropTypes.number.isRequired, backgroundColor : React.PropTypes.string.isRequired, valueColor : React.PropTypes.string.isRequired };
src/index.js
niyue/react-github
import React from 'react'; import App from './App'; React.render(<App />, document.getElementById('root'));
react/exercises/part_02/src/Contact.js
jsperts/workshop_unterlagen
import React from 'react'; function ContactDetails({ email, type }) { return ( <div className="row"> <div className="col-xs-6">Email: {email}</div> <div className="col-xs-6">Type: {type}</div> </div> ); } function ContactControls() { return ( <div> <div className="row"> <div className="col-xs-12"> <span className="glyphicon glyphicon-remove" /> <span className="glyphicon glyphicon-edit" /> </div> </div> <div className="row"> <div className="col-xs-12"> <span className="glyphicon glyphicon-chevron-down" /> </div> </div> </div> ); } function Contact({ name, tel, type, email }) { return ( <li className="list-group-item"> <div className="row"> <div className="col-xs-6"> <div>Name: {name}</div> <div>Tel.: {tel}</div> </div> <div className="col-xs-6 text-right"> <ContactControls /> </div> </div> <ContactDetails email={email} type={type} /> </li> ); } export default Contact;
src/components/MultiSelect/MultiSelect.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import cx from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import Downshift from 'downshift'; import isEqual from 'lodash.isequal'; import { settings } from 'carbon-components'; import WarningFilled16 from '@carbon/icons-react/lib/warning--filled/16'; import ListBox from '../ListBox'; import Checkbox from '../Checkbox'; import Selection from '../../internal/Selection'; import { sortingPropTypes } from './MultiSelectPropTypes'; import { defaultItemToString } from './tools/itemToString'; import { defaultSortItems, defaultCompareItems } from './tools/sorting'; const { prefix } = settings; const noop = () => undefined; export default class MultiSelect extends React.Component { static propTypes = { ...sortingPropTypes, /** * Disable the control */ disabled: PropTypes.bool, /** * Specify a custom `id` */ id: PropTypes.string.isRequired, /** * We try to stay as generic as possible here to allow individuals to pass * in a collection of whatever kind of data structure they prefer */ items: PropTypes.array.isRequired, /** * Allow users to pass in arbitrary items from their collection that are * pre-selected */ initialSelectedItems: PropTypes.array, /** * Helper function passed to downshift that allows the library to render a * given item to a string label. By default, it extracts the `label` field * from a given item to serve as the item label in the list. */ itemToString: PropTypes.func, /** * Generic `label` that will be used as the textual representation of what * this field is for */ label: PropTypes.node.isRequired, /** * Specify the locale of the control. Used for the default `compareItems` * used for sorting the list of items in the control. */ locale: PropTypes.string, /** * `onChange` is a utility for this controlled component to communicate to a * consuming component what kind of internal state changes are occuring. */ onChange: PropTypes.func, /** * Specify 'inline' to create an inline multi-select. */ type: PropTypes.oneOf(['default', 'inline']), /** * Specify title to show title on hover */ useTitleInItem: PropTypes.bool, /** * `true` to use the light version. */ light: PropTypes.bool, /** * Is the current selection invalid? */ invalid: PropTypes.bool, /** * If invalid, what is the error? */ invalidText: PropTypes.string, /** * Initialize the component with an open(`true`)/closed(`false`) menu. */ open: PropTypes.bool, /** * Callback function for translating ListBoxMenuIcon SVG title */ translateWithId: PropTypes.func, /** * Specify feedback (mode) of the selection. * `top`: selected item jumps to top * `fixed`: selected item stays at it's position * `top-after-reopen`: selected item jump to top after reopen dropdown */ selectionFeedback: PropTypes.oneOf(['top', 'fixed', 'top-after-reopen']), }; static getDerivedStateFromProps({ open }, state) { /** * programmatically control this `open` prop */ const { prevOpen } = state; return prevOpen === open ? null : { isOpen: open, prevOpen: open, }; } static defaultProps = { compareItems: defaultCompareItems, disabled: false, locale: 'en', itemToString: defaultItemToString, initialSelectedItems: [], sortItems: defaultSortItems, type: 'default', light: false, title: false, open: false, selectionFeedback: 'top-after-reopen', }; constructor(props) { super(props); this.state = { highlightedIndex: null, isOpen: props.open, topItems: [], }; } handleOnChange = changes => { if (this.props.onChange) { this.props.onChange(changes); } }; handleOnOuterClick = () => { this.setState({ isOpen: false, }); }; handleOnStateChange = (changes, downshift) => { if (changes.isOpen && !this.state.isOpen) { this.setState({ topItems: downshift.selectedItem }); } const { type } = changes; switch (type) { case Downshift.stateChangeTypes.keyDownArrowDown: case Downshift.stateChangeTypes.keyDownArrowUp: case Downshift.stateChangeTypes.itemMouseEnter: this.setState({ highlightedIndex: changes.highlightedIndex }); break; case Downshift.stateChangeTypes.keyDownEscape: case Downshift.stateChangeTypes.mouseUp: this.setState({ isOpen: false }); break; // Opt-in to some cases where we should be toggling the menu based on // a given key press or mouse handler // Reference: https://github.com/paypal/downshift/issues/206 case Downshift.stateChangeTypes.clickButton: case Downshift.stateChangeTypes.keyDownSpaceButton: this.setState(() => { let nextIsOpen = changes.isOpen || false; if (changes.isOpen === false) { // If Downshift is trying to close the menu, but we know the input // is the active element in the document, then keep the menu open if (this.inputNode === document.activeElement) { nextIsOpen = true; } } return { isOpen: nextIsOpen, }; }); break; } }; render() { const { highlightedIndex, isOpen } = this.state; const { ariaLabel, className: containerClassName, id, items, itemToString, titleText, helperText, label, type, disabled, initialSelectedItems, sortItems, compareItems, light, invalid, invalidText, useTitleInItem, translateWithId, } = this.props; const inline = type === 'inline'; const wrapperClasses = cx( `${prefix}--multi-select__wrapper`, `${prefix}--list-box__wrapper`, { [`${prefix}--multi-select__wrapper--inline`]: inline, [`${prefix}--list-box__wrapper--inline`]: inline, [`${prefix}--multi-select__wrapper--inline--invalid`]: inline && invalid, [`${prefix}--list-box__wrapper--inline--invalid`]: inline && invalid, } ); const titleClasses = cx(`${prefix}--label`, { [`${prefix}--label--disabled`]: disabled, }); const title = titleText ? ( <label htmlFor={id} className={titleClasses}> {titleText} </label> ) : null; const helperClasses = cx(`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: disabled, }); const helper = helperText ? ( <div className={helperClasses}>{helperText}</div> ) : null; const input = ( <Selection disabled={disabled} onChange={this.handleOnChange} initialSelectedItems={initialSelectedItems} render={({ selectedItems, onItemChange, clearSelection }) => ( <Downshift highlightedIndex={highlightedIndex} isOpen={isOpen} itemToString={itemToString} onChange={onItemChange} onStateChange={this.handleOnStateChange} onOuterClick={this.handleOnOuterClick} selectedItem={selectedItems} render={({ getRootProps, selectedItem, isOpen, itemToString, highlightedIndex, getItemProps, getButtonProps, }) => { const className = cx( `${prefix}--multi-select`, containerClassName, { [`${prefix}--multi-select--invalid`]: invalid, [`${prefix}--multi-select--inline`]: inline, [`${prefix}--multi-select--selected`]: selectedItem.length > 0, } ); return ( <ListBox id={id} type={type} className={className} disabled={disabled} light={light} invalid={invalid} invalidText={invalidText} isOpen={isOpen} {...getRootProps({ refKey: 'innerRef' })}> {invalid && ( <WarningFilled16 className={`${prefix}--list-box__invalid-icon`} /> )} <ListBox.Field id={id} tabIndex="0" {...getButtonProps({ disabled })}> {selectedItem.length > 0 && ( <ListBox.Selection clearSelection={!disabled ? clearSelection : noop} selectionCount={selectedItem.length} /> )} <span className={`${prefix}--list-box__label`}> {label} </span> <ListBox.MenuIcon isOpen={isOpen} translateWithId={translateWithId} /> </ListBox.Field> {isOpen && ( <ListBox.Menu aria-label={ariaLabel} id={id}> {sortItems(items, { selectedItems: { top: selectedItems, fixed: [], 'top-after-reopen': this.state.topItems, }[this.props.selectionFeedback], itemToString, compareItems, locale: 'en', }).map((item, index) => { const itemProps = getItemProps({ item }); const itemText = itemToString(item); const isChecked = selectedItem.filter(selected => isEqual(selected, item) ).length > 0; return ( <ListBox.MenuItem key={itemProps.id} isActive={isChecked} isHighlighted={highlightedIndex === index} {...itemProps}> <Checkbox id={`${itemProps.id}__checkbox`} title={useTitleInItem ? itemText : null} name={itemText} checked={isChecked} disabled={disabled} readOnly={true} tabIndex="-1" labelText={itemText} /> </ListBox.MenuItem> ); })} </ListBox.Menu> )} </ListBox> ); }} /> )} /> ); return ( <div className={wrapperClasses}> {title} {!inline && helper} {input} </div> ); } }
ajax/libs/react-slick/0.3.0/react-slick.min.js
chrisdavies/cdnjs
var Slider=function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){t.exports=n(1)},function(t,e,n){var r=n(2),i=n(3),o=n(7),s=n(5),a=(n(4),n(6)),u=r.createClass({displayName:"Slider",mixins:[a],getInitialState:function(){return{breakpoint:null}},componentDidMount:function(){{var t=o.sortBy(o.pluck(this.props.responsive,"breakpoint"));this.props}t.forEach(function(e,n){var r;r=s(0===n?{minWidth:0,maxWidth:e}:{minWidth:t[n-1],maxWidth:e}),this.media(r,function(){this.setState({breakpoint:e})}.bind(this))}.bind(this));var e=s({minWidth:t.slice(-1)[0]});this.media(e,function(){this.setState({breakpoint:null})}.bind(this))},render:function(){var t,e;return this.state.breakpoint?(e=o.filter(this.props.responsive,{breakpoint:this.state.breakpoint}),t=o.assign({},this.props,e[0].settings)):t=this.props,r.createElement(i,r.__spread({},t))}});t.exports=u},function(t){t.exports=React},function(t,e,n){var r=n(2),i=n(12),o=n(13),s=n(8),a=n(9),u=n(10),l=n(11),c=n(7),f=r.createClass({displayName:"Slider",mixins:[s,a],getInitialState:function(){return u},getDefaultProps:function(){return l},componentDidMount:function(){this.initialize(this.props)},componentWillReceiveProps:function(t){this.initialize(t)},renderDots:function(){var t,e,n=[];if(this.props.dots===!0&&this.state.slideCount>this.props.slidesToShow){for(var i=0;i<=this.getDotCount();i+=1)t={"slick-active":this.state.currentSlide===i*this.props.slidesToScroll},e={message:"index",index:i},n.push(r.createElement("li",{key:i,className:o(t)},r.createElement("button",{onClick:this.changeSlide.bind(this,e)},i)));return r.createElement("ul",{className:this.props.dotsClass,style:{display:"block"}},n)}return null},renderSlides:function(){var t,e=[],n=[],o=[],s=r.Children.count(this.props.children);return r.Children.forEach(this.props.children,function(r,a){e.push(i(r,{key:a,"data-index":a,className:this.getSlideClasses(a),style:c.assign({},this.getSlideStyle(),r.props.style)})),this.props.infinite===!0&&(infiniteCount=this.props.centerMode===!0?this.props.slidesToShow+1:this.props.slidesToShow,a>=s-infiniteCount&&(t=-(s-a),n.push(i(r,{key:t,"data-index":t,className:this.getSlideClasses(t),style:c.assign({},this.getSlideStyle(),r.props.style)}))),a<infiniteCount&&(t=s+a,o.push(i(r,{key:t,"data-index":t,className:this.getSlideClasses(t),style:c.assign({},this.getSlideStyle(),r.props.style)}))))}.bind(this)),n.concat(e,o)},renderTrack:function(){return r.createElement("div",{ref:"track",className:"slick-track",style:this.state.trackStyle},this.renderSlides())},renderArrows:function(){var t={"slick-prev":!0},e={"slick-next":!0},n=this.changeSlide.bind(this,{message:"previous"}),i=this.changeSlide.bind(this,{message:"next"});this.props.infinite===!1&&(0===this.state.currentSlide&&(t["slick-disabled"]=!0,n=null),this.state.currentSlide>=this.state.slideCount-this.props.slidesToShow&&(e["slick-disabled"]=!0,i=null));var s=r.createElement("button",{key:0,ref:"previous",type:"button","data-role":"none",className:o(t),style:{display:"block"},onClick:n}," Previous"),a=r.createElement("button",{key:1,ref:"next",type:"button","data-role":"none",className:o(e),style:{display:"block"},onClick:i},"Next");return[s,a]},render:function(){return r.createElement("div",{className:"slick-initialized slick-slider "+this.props.className},r.createElement("div",{ref:"list",className:"slick-list",style:this.getListStyle(),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},this.renderTrack()),this.renderArrows(),this.renderDots())}});t.exports=f},function(t){"use strict";function e(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}t.exports=Object.assign||function(t){for(var n,r,i=e(t),o=1;o<arguments.length;o++){n=arguments[o],r=Object.keys(Object(n));for(var s=0;s<r.length;s++)i[r[s]]=n[r[s]]}return i}},function(t,e,n){var r=n(16),i=function(t){var e=/[height|width]$/;return e.test(t)},o=function(t){var e="",n=Object.keys(t);return n.forEach(function(o,s){var a=t[o];o=r(o),i(o)&&"number"==typeof a&&(a+="px"),e+=a===!0?o:a===!1?"not "+o:"("+o+": "+a+")",s<n.length-1&&(e+=" and ")}),e},s=function(t){var e="";return"string"==typeof t?t:t instanceof Array?(t.forEach(function(n,r){e+=o(n),r<t.length-1&&(e+=", ")}),e):o(t)};t.exports=s},function(t,e,n){var r=n(18),i=n(15),o={media:function(t,e){t=i(t),"function"==typeof e&&(e={match:e}),r.register(t,e),this._responsiveMediaHandlers||(this._responsiveMediaHandlers=[]),this._responsiveMediaHandlers.push({query:t,handler:e})},componentWillUnmount:function(){this._responsiveMediaHandlers.forEach(function(t){r.unregister(t.query,t.handler)})}};t.exports=o},function(t,e,n){var r;(function(t,i){(function(){function o(t,e,n){for(var r=(n||0)-1,i=t?t.length:0;++r<i;)if(t[r]===e)return r;return-1}function s(t,e){var n=typeof e;if(t=t.cache,"boolean"==n||null==e)return t[e]?0:-1;"number"!=n&&"string"!=n&&(n="object");var r="number"==n?e:C+e;return t=(t=t[n])&&t[r],"object"==n?t&&o(t,e)>-1?0:-1:t?0:-1}function a(t){var e=this.cache,n=typeof t;if("boolean"==n||null==t)e[t]=!0;else{"number"!=n&&"string"!=n&&(n="object");var r="number"==n?t:C+t,i=e[n]||(e[n]={});"object"==n?(i[r]||(i[r]=[])).push(t):i[r]=!0}}function u(t){return t.charCodeAt(0)}function l(t,e){for(var n=t.criteria,r=e.criteria,i=-1,o=n.length;++i<o;){var s=n[i],a=r[i];if(s!==a){if(s>a||"undefined"==typeof s)return 1;if(a>s||"undefined"==typeof a)return-1}}return t.index-e.index}function c(t){var e=-1,n=t.length,r=t[0],i=t[n/2|0],o=t[n-1];if(r&&"object"==typeof r&&i&&"object"==typeof i&&o&&"object"==typeof o)return!1;var s=h();s["false"]=s["null"]=s["true"]=s.undefined=!1;var u=h();for(u.array=t,u.cache=s,u.push=a;++e<n;)u.push(t[e]);return u}function f(t){return"\\"+ie[t]}function p(){return w.pop()||[]}function h(){return S.pop()||{array:null,cache:null,criteria:null,"false":!1,index:0,"null":!1,number:null,object:null,push:null,string:null,"true":!1,undefined:!1,value:null}}function d(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function g(t){t.length=0,w.length<j&&w.push(t)}function v(t){var e=t.cache;e&&v(e),t.array=t.cache=t.criteria=t.object=t.number=t.string=t.value=null,S.length<j&&S.push(t)}function y(t,e,n){e||(e=0),"undefined"==typeof n&&(n=t?t.length:0);for(var r=-1,i=n-e||0,o=Array(0>i?0:i);++r<i;)o[r]=t[e+r];return o}function m(t){function e(t){return t&&"object"==typeof t&&!fi(t)&&Yr.call(t,"__wrapped__")?t:new n(t)}function n(t,e){this.__chain__=!!e,this.__wrapped__=t}function r(t){function e(){if(r){var t=y(r);Ur.apply(t,arguments)}if(this instanceof e){var o=a(n.prototype),s=n.apply(o,t||arguments);return Ie(s)?s:o}return n.apply(i,t||arguments)}var n=t[0],r=t[2],i=t[4];return ci(e,t),e}function i(t,e,n,r,o){if(n){var s=n(t);if("undefined"!=typeof s)return s}var a=Ie(t);if(!a)return t;var u=Ir.call(t);if(!Q[u]||!ui.nodeClass&&d(t))return t;var l=si[u];switch(u){case U:case $:return new l(+t);case K:case J:return new l(t);case G:return s=l(t.source,L.exec(t)),s.lastIndex=t.lastIndex,s}var c=fi(t);if(e){var f=!r;r||(r=p()),o||(o=p());for(var h=r.length;h--;)if(r[h]==t)return o[h];s=c?l(t.length):{}}else s=c?y(t):_i({},t);return c&&(Yr.call(t,"index")&&(s.index=t.index),Yr.call(t,"input")&&(s.input=t.input)),e?(r.push(t),o.push(s),(c?Si:Ci)(t,function(t,a){s[a]=i(t,e,n,r,o)}),f&&(g(r),g(o)),s):s}function a(t){return Ie(t)?Gr(t):{}}function w(t,e,n){if("function"!=typeof t)return or;if("undefined"==typeof e||!("prototype"in t))return t;var r=t.__bindData__;if("undefined"==typeof r&&(ui.funcNames&&(r=!t.name),r=r||!ui.funcDecomp,!r)){var i=Xr.call(t);ui.funcNames||(r=!A.test(i)),r||(r=H.test(i),ci(t,r))}if(r===!1||r!==!0&&1&r[1])return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)};case 4:return function(n,r,i,o){return t.call(e,n,r,i,o)}}return Xn(t,e)}function S(t){function e(){var t=l?s:this;if(i){var d=y(i);Ur.apply(d,arguments)}if((o||f)&&(d||(d=y(arguments)),o&&Ur.apply(d,o),f&&d.length<u))return r|=16,S([n,p?r:-4&r,d,null,s,u]);if(d||(d=arguments),c&&(n=t[h]),this instanceof e){t=a(n.prototype);var g=n.apply(t,d);return Ie(g)?g:t}return n.apply(t,d)}var n=t[0],r=t[1],i=t[2],o=t[3],s=t[4],u=t[5],l=1&r,c=2&r,f=4&r,p=8&r,h=n;return ci(e,t),e}function j(t,e){var n=-1,r=ge(),i=t?t.length:0,a=i>=E&&r===o,u=[];if(a){var l=c(e);l?(r=s,e=l):a=!1}for(;++n<i;){var f=t[n];r(e,f)<0&&u.push(f)}return a&&v(e),u}function ie(t,e,n,r){for(var i=(r||0)-1,o=t?t.length:0,s=[];++i<o;){var a=t[i];if(a&&"object"==typeof a&&"number"==typeof a.length&&(fi(a)||be(a))){e||(a=ie(a,e,n));var u=-1,l=a.length,c=s.length;for(s.length+=l;++u<l;)s[c++]=a[u]}else n||s.push(a)}return s}function se(t,e,n,r,i,o){if(n){var s=n(t,e);if("undefined"!=typeof s)return!!s}if(t===e)return 0!==t||1/t==1/e;var a=typeof t,u=typeof e;if(!(t!==t||t&&re[a]||e&&re[u]))return!1;if(null==t||null==e)return t===e;var l=Ir.call(t),c=Ir.call(e);if(l==B&&(l=Z),c==B&&(c=Z),l!=c)return!1;switch(l){case U:case $:return+t==+e;case K:return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case G:case J:return t==Pr(e)}var f=l==Y;if(!f){var h=Yr.call(t,"__wrapped__"),v=Yr.call(e,"__wrapped__");if(h||v)return se(h?t.__wrapped__:t,v?e.__wrapped__:e,n,r,i,o);if(l!=Z||!ui.nodeClass&&(d(t)||d(e)))return!1;var y=!ui.argsObject&&be(t)?Tr:t.constructor,m=!ui.argsObject&&be(e)?Tr:e.constructor;if(y!=m&&!(De(y)&&y instanceof y&&De(m)&&m instanceof m)&&"constructor"in t&&"constructor"in e)return!1}var b=!i;i||(i=p()),o||(o=p());for(var w=i.length;w--;)if(i[w]==t)return o[w]==e;var S=0;if(s=!0,i.push(t),o.push(e),f){if(w=t.length,S=e.length,s=S==w,s||r)for(;S--;){var _=w,x=e[S];if(r)for(;_--&&!(s=se(t[_],x,n,r,i,o)););else if(!(s=se(t[S],x,n,r,i,o)))break}}else ki(e,function(e,a,u){return Yr.call(u,a)?(S++,s=Yr.call(t,a)&&se(t[a],e,n,r,i,o)):void 0}),s&&!r&&ki(t,function(t,e,n){return Yr.call(n,e)?s=--S>-1:void 0});return i.pop(),o.pop(),b&&(g(i),g(o)),s}function ae(t,e,n,r,i){(fi(e)?rn:Ci)(e,function(e,o){var s,a,u=e,l=t[o];if(e&&((a=fi(e))||Ei(e))){for(var c=r.length;c--;)if(s=r[c]==e){l=i[c];break}if(!s){var f;n&&(u=n(l,e),(f="undefined"!=typeof u)&&(l=u)),f||(l=a?fi(l)?l:[]:Ei(l)?l:{}),r.push(e),i.push(l),f||ae(l,e,n,r,i)}}else n&&(u=n(l,e),"undefined"==typeof u&&(u=e)),"undefined"!=typeof u&&(l=u);t[o]=l})}function ue(t,e){return t+zr(oi()*(e-t+1))}function ce(t,e,n){var r=-1,i=ge(),a=t?t.length:0,u=[],l=!e&&a>=E&&i===o,f=n||l?p():u;if(l){var h=c(f);i=s,f=h}for(;++r<a;){var d=t[r],y=n?n(d,r,t):d;(e?!r||f[f.length-1]!==y:i(f,y)<0)&&((n||l)&&f.push(y),u.push(d))}return l?(g(f.array),v(f)):n&&g(f),u}function fe(t){return function(n,r,i){var o={};if(r=e.createCallback(r,i,3),fi(n))for(var s=-1,a=n.length;++s<a;){var u=n[s];t(o,u,r(u,s,n),n)}else Si(n,function(e,n,i){t(o,e,r(e,n,i),i)});return o}}function pe(t,e,n,i,o,s){var a=1&e,u=2&e,l=4&e,c=16&e,f=32&e;if(!u&&!De(t))throw new Mr;c&&!n.length&&(e&=-17,c=n=!1),f&&!i.length&&(e&=-33,f=i=!1);var p=t&&t.__bindData__;if(p&&p!==!0)return p=y(p),p[2]&&(p[2]=y(p[2])),p[3]&&(p[3]=y(p[3])),!a||1&p[1]||(p[4]=o),!a&&1&p[1]&&(e|=8),!l||4&p[1]||(p[5]=s),c&&Ur.apply(p[2]||(p[2]=[]),n),f&&Kr.apply(p[3]||(p[3]=[]),i),p[1]|=e,pe.apply(null,p);var h=1==e||17===e?r:S;return h([t,e,n,i,o,s])}function he(){ne.shadowedProps=z,ne.array=ne.bottom=ne.loop=ne.top="",ne.init="iterable",ne.useHas=!0;for(var t,e=0;t=arguments[e];e++)for(var n in t)ne[n]=t[n];var r=ne.args;ne.firstArg=/^[^,]+/.exec(r)[0];var i=Cr("baseCreateCallback, errorClass, errorProto, hasOwnProperty, indicatorObject, isArguments, isArray, isString, keys, objectProto, objectTypes, nonEnumProps, stringClass, stringProto, toString","return function("+r+") {\n"+li(ne)+"\n}");return i(w,F,Lr,Yr,x,be,fi,Xe,ne.keys,Ar,re,ai,J,Wr,Ir)}function de(t){return yi[t]}function ge(){var t=(t=e.indexOf)===Cn?o:t;return t}function ve(t){return"function"==typeof t&&Hr.test(t)}function ye(t){var e,n;return!t||Ir.call(t)!=Z||(e=t.constructor,De(e)&&!(e instanceof e))||!ui.argsClass&&be(t)||!ui.nodeClass&&d(t)?!1:ui.ownLast?(ki(t,function(t,e,r){return n=Yr.call(r,e),!1}),n!==!1):(ki(t,function(t,e){n=e}),"undefined"==typeof n||Yr.call(t,n))}function me(t){return mi[t]}function be(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Ir.call(t)==B||!1}function we(t,e,n,r){return"boolean"!=typeof e&&null!=e&&(r=n,n=e,e=!1),i(t,e,"function"==typeof n&&w(n,r,1))}function Se(t,e,n){return i(t,!0,"function"==typeof e&&w(e,n,1))}function _e(t,e){var n=a(t);return e?_i(n,e):n}function xe(t,n,r){var i;return n=e.createCallback(n,r,3),Ci(t,function(t,e,r){return n(t,e,r)?(i=e,!1):void 0}),i}function ke(t,n,r){var i;return n=e.createCallback(n,r,3),Ee(t,function(t,e,r){return n(t,e,r)?(i=e,!1):void 0}),i}function Ce(t,e,n){var r=[];ki(t,function(t,e){r.push(e,t)});var i=r.length;for(e=w(e,n,3);i--&&e(r[i--],r[i],t)!==!1;);return t}function Ee(t,e,n){var r=hi(t),i=r.length;for(e=w(e,n,3);i--;){var o=r[i];if(e(t[o],o,t)===!1)break}return t}function je(t){var e=[];return ki(t,function(t,n){De(t)&&e.push(n)}),e.sort()}function Te(t,e){return t?Yr.call(t,e):!1}function Oe(t){for(var e=-1,n=hi(t),r=n.length,i={};++e<r;){var o=n[e];i[t[o]]=o}return i}function Pe(t){return t===!0||t===!1||t&&"object"==typeof t&&Ir.call(t)==U||!1}function Me(t){return t&&"object"==typeof t&&Ir.call(t)==$||!1}function Ne(t){return t&&1===t.nodeType||!1}function Le(t){var e=!0;if(!t)return e;var n=Ir.call(t),r=t.length;return n==Y||n==J||(ui.argsClass?n==B:be(t))||n==Z&&"number"==typeof r&&De(t.splice)?!r:(Ci(t,function(){return e=!1}),e)}function Ae(t,e,n,r){return se(t,e,"function"==typeof n&&w(n,r,2))}function We(t){return Qr(t)&&!ti(parseFloat(t))}function De(t){return"function"==typeof t}function Ie(t){return!(!t||!re[typeof t])}function He(t){return qe(t)&&t!=+t}function Re(t){return null===t}function qe(t){return"number"==typeof t||t&&"object"==typeof t&&Ir.call(t)==K||!1}function ze(t){return t&&re[typeof t]&&Ir.call(t)==G||!1}function Xe(t){return"string"==typeof t||t&&"object"==typeof t&&Ir.call(t)==J||!1}function Be(t){return"undefined"==typeof t}function Ye(t,n,r){var i={};return n=e.createCallback(n,r,3),Ci(t,function(t,e,r){i[e]=n(t,e,r)}),i}function Ue(t){var e=arguments,n=2;if(!Ie(t))return t;if("number"!=typeof e[2]&&(n=e.length),n>3&&"function"==typeof e[n-2])var r=w(e[--n-1],e[n--],2);else n>2&&"function"==typeof e[n-1]&&(r=e[--n]);for(var i=y(arguments,1,n),o=-1,s=p(),a=p();++o<n;)ae(t,i[o],r,s,a);return g(s),g(a),t}function $e(t,n,r){var i={};if("function"!=typeof n){var o=[];ki(t,function(t,e){o.push(e)}),o=j(o,ie(arguments,!0,!1,1));for(var s=-1,a=o.length;++s<a;){var u=o[s];i[u]=t[u]}}else n=e.createCallback(n,r,3),ki(t,function(t,e,r){n(t,e,r)||(i[e]=t)});return i}function Fe(t){for(var e=-1,n=hi(t),r=n.length,i=Sr(r);++e<r;){var o=n[e];i[e]=[o,t[o]]}return i}function Ve(t,n,r){var i={};if("function"!=typeof n)for(var o=-1,s=ie(arguments,!0,!1,1),a=Ie(t)?s.length:0;++o<a;){var u=s[o];u in t&&(i[u]=t[u])}else n=e.createCallback(n,r,3),ki(t,function(t,e,r){n(t,e,r)&&(i[e]=t)});return i}function Ke(t,n,r,i){var o=fi(t);if(null==r)if(o)r=[];else{var s=t&&t.constructor,u=s&&s.prototype;r=a(u)}return n&&(n=e.createCallback(n,i,4),(o?Si:Ci)(t,function(t,e,i){return n(r,t,e,i)})),r}function Ze(t){for(var e=-1,n=hi(t),r=n.length,i=Sr(r);++e<r;)i[e]=t[n[e]];return i}function Ge(t){var e=arguments,n=-1,r=ie(e,!0,!1,1),i=e[2]&&e[2][e[1]]===t?1:r.length,o=Sr(i);for(ui.unindexedChars&&Xe(t)&&(t=t.split(""));++n<i;)o[n]=t[r[n]];return o}function Je(t,e,n){var r=-1,i=ge(),o=t?t.length:0,s=!1;return n=(0>n?ni(0,o+n):n)||0,fi(t)?s=i(t,e,n)>-1:"number"==typeof o?s=(Xe(t)?t.indexOf(e,n):i(t,e,n))>-1:Si(t,function(t){return++r>=n?!(s=t===e):void 0}),s}function Qe(t,n,r){var i=!0;if(n=e.createCallback(n,r,3),fi(t))for(var o=-1,s=t.length;++o<s&&(i=!!n(t[o],o,t)););else Si(t,function(t,e,r){return i=!!n(t,e,r)});return i}function tn(t,n,r){var i=[];if(n=e.createCallback(n,r,3),fi(t))for(var o=-1,s=t.length;++o<s;){var a=t[o];n(a,o,t)&&i.push(a)}else Si(t,function(t,e,r){n(t,e,r)&&i.push(t)});return i}function en(t,n,r){if(n=e.createCallback(n,r,3),!fi(t)){var i;return Si(t,function(t,e,r){return n(t,e,r)?(i=t,!1):void 0}),i}for(var o=-1,s=t.length;++o<s;){var a=t[o];if(n(a,o,t))return a}}function nn(t,n,r){var i;return n=e.createCallback(n,r,3),on(t,function(t,e,r){return n(t,e,r)?(i=t,!1):void 0}),i}function rn(t,e,n){if(e&&"undefined"==typeof n&&fi(t))for(var r=-1,i=t.length;++r<i&&e(t[r],r,t)!==!1;);else Si(t,e,n);return t}function on(t,e,n){var r=t,i=t?t.length:0;if(e=e&&"undefined"==typeof n?e:w(e,n,3),fi(t))for(;i--&&e(t[i],i,t)!==!1;);else{if("number"!=typeof i){var o=hi(t);i=o.length}else ui.unindexedChars&&Xe(t)&&(r=t.split(""));Si(t,function(t,n,s){return n=o?o[--i]:--i,e(r[n],n,s)})}return t}function sn(t,e){var n=y(arguments,2),r=-1,i="function"==typeof e,o=t?t.length:0,s=Sr("number"==typeof o?o:0);return rn(t,function(t){s[++r]=(i?e:t[e]).apply(t,n)}),s}function an(t,n,r){var i=-1,o=t?t.length:0,s=Sr("number"==typeof o?o:0);if(n=e.createCallback(n,r,3),fi(t))for(;++i<o;)s[i]=n(t[i],i,t);else Si(t,function(t,e,r){s[++i]=n(t,e,r)});return s}function un(t,n,r){var i=-1/0,o=i;if("function"!=typeof n&&r&&r[n]===t&&(n=null),null==n&&fi(t))for(var s=-1,a=t.length;++s<a;){var l=t[s];l>o&&(o=l)}else n=null==n&&Xe(t)?u:e.createCallback(n,r,3),Si(t,function(t,e,r){var s=n(t,e,r);s>i&&(i=s,o=t)});return o}function ln(t,n,r){var i=1/0,o=i;if("function"!=typeof n&&r&&r[n]===t&&(n=null),null==n&&fi(t))for(var s=-1,a=t.length;++s<a;){var l=t[s];o>l&&(o=l)}else n=null==n&&Xe(t)?u:e.createCallback(n,r,3),Si(t,function(t,e,r){var s=n(t,e,r);i>s&&(i=s,o=t)});return o}function cn(t,n,r,i){var o=arguments.length<3;if(n=e.createCallback(n,i,4),fi(t)){var s=-1,a=t.length;for(o&&(r=t[++s]);++s<a;)r=n(r,t[s],s,t)}else Si(t,function(t,e,i){r=o?(o=!1,t):n(r,t,e,i)});return r}function fn(t,n,r,i){var o=arguments.length<3;return n=e.createCallback(n,i,4),on(t,function(t,e,i){r=o?(o=!1,t):n(r,t,e,i)}),r}function pn(t,n,r){return n=e.createCallback(n,r,3),tn(t,function(t,e,r){return!n(t,e,r)})}function hn(t,e,n){if(t&&"number"!=typeof t.length?t=Ze(t):ui.unindexedChars&&Xe(t)&&(t=t.split("")),null==e||n)return t?t[ue(0,t.length-1)]:b;var r=dn(t);return r.length=ri(ni(0,e),r.length),r}function dn(t){var e=-1,n=t?t.length:0,r=Sr("number"==typeof n?n:0);return rn(t,function(t){var n=ue(0,++e);r[e]=r[n],r[n]=t}),r}function gn(t){var e=t?t.length:0;return"number"==typeof e?e:hi(t).length}function vn(t,n,r){var i;if(n=e.createCallback(n,r,3),fi(t))for(var o=-1,s=t.length;++o<s&&!(i=n(t[o],o,t)););else Si(t,function(t,e,r){return!(i=n(t,e,r))});return!!i}function yn(t,n,r){var i=-1,o=fi(n),s=t?t.length:0,a=Sr("number"==typeof s?s:0);for(o||(n=e.createCallback(n,r,3)),rn(t,function(t,e,r){var s=a[++i]=h();o?s.criteria=an(n,function(e){return t[e]}):(s.criteria=p())[0]=n(t,e,r),s.index=i,s.value=t}),s=a.length,a.sort(l);s--;){var u=a[s];a[s]=u.value,o||g(u.criteria),v(u)}return a}function mn(t){return t&&"number"==typeof t.length?ui.unindexedChars&&Xe(t)?t.split(""):y(t):Ze(t)}function bn(t){for(var e=-1,n=t?t.length:0,r=[];++e<n;){var i=t[e];i&&r.push(i)}return r}function wn(t){return j(t,ie(arguments,!0,!0,1))}function Sn(t,n,r){var i=-1,o=t?t.length:0;for(n=e.createCallback(n,r,3);++i<o;)if(n(t[i],i,t))return i;return-1}function _n(t,n,r){var i=t?t.length:0;for(n=e.createCallback(n,r,3);i--;)if(n(t[i],i,t))return i;return-1}function xn(t,n,r){var i=0,o=t?t.length:0;if("number"!=typeof n&&null!=n){var s=-1;for(n=e.createCallback(n,r,3);++s<o&&n(t[s],s,t);)i++}else if(i=n,null==i||r)return t?t[0]:b;return y(t,0,ri(ni(0,i),o))}function kn(t,e,n,r){return"boolean"!=typeof e&&null!=e&&(r=n,n="function"!=typeof e&&r&&r[e]===t?null:e,e=!1),null!=n&&(t=an(t,n,r)),ie(t,e)}function Cn(t,e,n){if("number"==typeof n){var r=t?t.length:0;n=0>n?ni(0,r+n):n||0}else if(n){var i=An(t,e);return t[i]===e?i:-1}return o(t,e,n)}function En(t,n,r){var i=0,o=t?t.length:0;if("number"!=typeof n&&null!=n){var s=o;for(n=e.createCallback(n,r,3);s--&&n(t[s],s,t);)i++}else i=null==n||r?1:n||i;return y(t,0,ri(ni(0,o-i),o))}function jn(){for(var t=[],e=-1,n=arguments.length,r=p(),i=ge(),a=i===o,u=p();++e<n;){var l=arguments[e];(fi(l)||be(l))&&(t.push(l),r.push(a&&l.length>=E&&c(e?t[e]:u)))}var f=t[0],h=-1,d=f?f.length:0,y=[];t:for(;++h<d;){var m=r[0];if(l=f[h],(m?s(m,l):i(u,l))<0){for(e=n,(m||u).push(l);--e;)if(m=r[e],(m?s(m,l):i(t[e],l))<0)continue t;y.push(l)}}for(;n--;)m=r[n],m&&v(m);return g(r),g(u),y}function Tn(t,n,r){var i=0,o=t?t.length:0;if("number"!=typeof n&&null!=n){var s=o;for(n=e.createCallback(n,r,3);s--&&n(t[s],s,t);)i++}else if(i=n,null==i||r)return t?t[o-1]:b;return y(t,ni(0,o-i))}function On(t,e,n){var r=t?t.length:0;for("number"==typeof n&&(r=(0>n?ni(0,r+n):ri(n,r-1))+1);r--;)if(t[r]===e)return r;return-1}function Pn(t){for(var e=arguments,n=0,r=e.length,i=t?t.length:0;++n<r;)for(var o=-1,s=e[n];++o<i;)t[o]===s&&(Vr.call(t,o--,1),i--);return t}function Mn(t,e,n){t=+t||0,n="number"==typeof n?n:+n||1,null==e&&(e=t,t=0);for(var r=-1,i=ni(0,Rr((e-t)/(n||1))),o=Sr(i);++r<i;)o[r]=t,t+=n;return o}function Nn(t,n,r){var i=-1,o=t?t.length:0,s=[];for(n=e.createCallback(n,r,3);++i<o;){var a=t[i];n(a,i,t)&&(s.push(a),Vr.call(t,i--,1),o--)}return s}function Ln(t,n,r){if("number"!=typeof n&&null!=n){var i=0,o=-1,s=t?t.length:0;for(n=e.createCallback(n,r,3);++o<s&&n(t[o],o,t);)i++}else i=null==n||r?1:ni(0,n);return y(t,i)}function An(t,n,r,i){var o=0,s=t?t.length:o;for(r=r?e.createCallback(r,i,1):or,n=r(n);s>o;){var a=o+s>>>1;r(t[a])<n?o=a+1:s=a}return o}function Wn(){return ce(ie(arguments,!0,!0))}function Dn(t,n,r,i){return"boolean"!=typeof n&&null!=n&&(i=r,r="function"!=typeof n&&i&&i[n]===t?null:n,n=!1),null!=r&&(r=e.createCallback(r,i,3)),ce(t,n,r)}function In(t){return j(t,y(arguments,1))}function Hn(){for(var t=-1,e=arguments.length;++t<e;){var n=arguments[t];if(fi(n)||be(n))var r=r?ce(j(r,n).concat(j(n,r))):n}return r||[]}function Rn(){for(var t=arguments.length>1?arguments:arguments[0],e=-1,n=t?un(Pi(t,"length")):0,r=Sr(0>n?0:n);++e<n;)r[e]=Pi(t,e);return r}function qn(t,e){var n=-1,r=t?t.length:0,i={};for(e||!r||fi(t[0])||(e=[]);++n<r;){var o=t[n];e?i[o]=e[n]:o&&(i[o[0]]=o[1])}return i}function zn(t,e){if(!De(e))throw new Mr;return function(){return--t<1?e.apply(this,arguments):void 0}}function Xn(t,e){return arguments.length>2?pe(t,17,y(arguments,2),null,e):pe(t,1,null,null,e)}function Bn(t){for(var e=arguments.length>1?ie(arguments,!0,!1,1):je(t),n=-1,r=e.length;++n<r;){var i=e[n];t[i]=pe(t[i],1,null,null,t)}return t}function Yn(t,e){return arguments.length>2?pe(e,19,y(arguments,2),null,t):pe(e,3,null,null,t)}function Un(){for(var t=arguments,e=t.length;e--;)if(!De(t[e]))throw new Mr;return function(){for(var e=arguments,n=t.length;n--;)e=[t[n].apply(this,e)];return e[0]}}function $n(t,e){return e="number"==typeof e?e:+e||t.length,pe(t,4,null,null,null,e)}function Fn(t,e,n){var r,i,o,s,a,u,l,c=0,f=!1,p=!0;if(!De(t))throw new Mr;if(e=ni(0,e)||0,n===!0){var h=!0;p=!1}else Ie(n)&&(h=n.leading,f="maxWait"in n&&(ni(e,n.maxWait)||0),p="trailing"in n?n.trailing:p);var d=function(){var n=e-(Ni()-s);if(0>=n){i&&qr(i);var f=l;i=u=l=b,f&&(c=Ni(),o=t.apply(a,r),u||i||(r=a=null))}else u=Fr(d,n)},g=function(){u&&qr(u),i=u=l=b,(p||f!==e)&&(c=Ni(),o=t.apply(a,r),u||i||(r=a=null))};return function(){if(r=arguments,s=Ni(),a=this,l=p&&(u||!h),f===!1)var n=h&&!u;else{i||h||(c=s);var v=f-(s-c),y=0>=v;y?(i&&(i=qr(i)),c=s,o=t.apply(a,r)):i||(i=Fr(g,v))}return y&&u?u=qr(u):u||e===f||(u=Fr(d,e)),n&&(y=!0,o=t.apply(a,r)),!y||u||i||(r=a=null),o}}function Vn(t){if(!De(t))throw new Mr;var e=y(arguments,1);return Fr(function(){t.apply(b,e)},1)}function Kn(t,e){if(!De(t))throw new Mr;var n=y(arguments,2);return Fr(function(){t.apply(b,n)},e)}function Zn(t,e){if(!De(t))throw new Mr;var n=function(){var r=n.cache,i=e?e.apply(this,arguments):C+arguments[0];return Yr.call(r,i)?r[i]:r[i]=t.apply(this,arguments)};return n.cache={},n}function Gn(t){var e,n;if(!De(t))throw new Mr;return function(){return e?n:(e=!0,n=t.apply(this,arguments),t=null,n)}}function Jn(t){return pe(t,16,y(arguments,1))}function Qn(t){return pe(t,32,null,y(arguments,1))}function tr(t,e,n){var r=!0,i=!0;if(!De(t))throw new Mr;return n===!1?r=!1:Ie(n)&&(r="leading"in n?n.leading:r,i="trailing"in n?n.trailing:i),te.leading=r,te.maxWait=e,te.trailing=i,Fn(t,e,te)}function er(t,e){return pe(e,16,[t])}function nr(t){return function(){return t}}function rr(t,e,n){var r=typeof t;if(null==t||"function"==r)return w(t,e,n);if("object"!=r)return lr(t);var i=hi(t),o=i[0],s=t[o];return 1!=i.length||s!==s||Ie(s)?function(e){for(var n=i.length,r=!1;n--&&(r=se(e[i[n]],t[i[n]],null,!0)););return r}:function(t){var e=t[o];return s===e&&(0!==s||1/s==1/e)}}function ir(t){return null==t?"":Pr(t).replace(wi,de)}function or(t){return t}function sr(t,r,i){var o=!0,s=r&&je(r);r&&(i||s.length)||(null==i&&(i=r),a=n,r=t,t=e,s=je(r)),i===!1?o=!1:Ie(i)&&"chain"in i&&(o=i.chain);var a=t,u=De(a);rn(s,function(e){var n=t[e]=r[e];u&&(a.prototype[e]=function(){var e=this.__chain__,r=this.__wrapped__,i=[r];Ur.apply(i,arguments);var s=n.apply(t,i);if(o||e){if(r===s&&Ie(s))return this;s=new a(s),s.__chain__=e}return s})})}function ar(){return t._=Dr,this}function ur(){}function lr(t){return function(e){return e[t]}}function cr(t,e,n){var r=null==t,i=null==e;if(null==n&&("boolean"==typeof t&&i?(n=t,t=1):i||"boolean"!=typeof e||(n=e,i=!0)),r&&i&&(e=1),t=+t||0,i?(e=t,t=0):e=+e||0,n||t%1||e%1){var o=oi();return ri(t+o*(e-t+parseFloat("1e-"+((o+"").length-1))),e)}return ue(t,e)}function fr(t,e){if(t){var n=t[e];return De(n)?t[e]():n}}function pr(t,n,r){var i=e.templateSettings;t=Pr(t||""),r=xi({},r,i);var o,s=xi({},r.imports,i.imports),a=hi(s),u=Ze(s),l=0,c=r.interpolate||I,p="__p += '",h=Or((r.escape||I).source+"|"+c.source+"|"+(c===W?N:I).source+"|"+(r.evaluate||I).source+"|$","g");t.replace(h,function(e,n,r,i,s,a){return r||(r=i),p+=t.slice(l,a).replace(R,f),n&&(p+="' +\n__e("+n+") +\n'"),s&&(o=!0,p+="';\n"+s+";\n__p += '"),r&&(p+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),l=a+e.length,e}),p+="';\n";var d=r.variable,g=d;g||(d="obj",p="with ("+d+") {\n"+p+"\n}\n"),p=(o?p.replace(O,""):p).replace(P,"$1").replace(M,"$1;"),p="function("+d+") {\n"+(g?"":d+" || ("+d+" = {});\n")+"var __t, __p = '', __e = _.escape"+(o?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var v="\n/*\n//# sourceURL="+(r.sourceURL||"/lodash/template/source["+X++ +"]")+"\n*/";try{var y=Cr(a,"return "+p+v).apply(b,u)}catch(m){throw m.source=p,m}return n?y(n):(y.source=p,y)}function hr(t,e,n){t=(t=+t)>-1?t:0;var r=-1,i=Sr(t);for(e=w(e,n,1);++r<t;)i[r]=e(r);return i}function dr(t){return null==t?"":Pr(t).replace(bi,me)}function gr(t){var e=++_;return Pr(null==t?"":t)+e}function vr(t){return t=new n(t),t.__chain__=!0,t}function yr(t,e){return e(t),t}function mr(){return this.__chain__=!0,this}function br(){return Pr(this.__wrapped__)}function wr(){return this.__wrapped__}t=t?le.defaults(oe.Object(),t,le.pick(oe,q)):oe;var Sr=t.Array,_r=t.Boolean,xr=t.Date,kr=t.Error,Cr=t.Function,Er=t.Math,jr=t.Number,Tr=t.Object,Or=t.RegExp,Pr=t.String,Mr=t.TypeError,Nr=[],Lr=kr.prototype,Ar=Tr.prototype,Wr=Pr.prototype,Dr=t._,Ir=Ar.toString,Hr=Or("^"+Pr(Ir).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),Rr=Er.ceil,qr=t.clearTimeout,zr=Er.floor,Xr=Cr.prototype.toString,Br=ve(Br=Tr.getPrototypeOf)&&Br,Yr=Ar.hasOwnProperty,Ur=Nr.push,$r=Ar.propertyIsEnumerable,Fr=t.setTimeout,Vr=Nr.splice,Kr=Nr.unshift,Zr=function(){try{var t={},e=ve(e=Tr.defineProperty)&&e,n=e(t,t,t)&&e}catch(r){}return n}(),Gr=ve(Gr=Tr.create)&&Gr,Jr=ve(Jr=Sr.isArray)&&Jr,Qr=t.isFinite,ti=t.isNaN,ei=ve(ei=Tr.keys)&&ei,ni=Er.max,ri=Er.min,ii=t.parseInt,oi=Er.random,si={};si[Y]=Sr,si[U]=_r,si[$]=xr,si[V]=Cr,si[Z]=Tr,si[K]=jr,si[G]=Or,si[J]=Pr;var ai={};ai[Y]=ai[$]=ai[K]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},ai[U]=ai[J]={constructor:!0,toString:!0,valueOf:!0},ai[F]=ai[V]=ai[G]={constructor:!0,toString:!0},ai[Z]={constructor:!0},function(){for(var t=z.length;t--;){var e=z[t];for(var n in ai)Yr.call(ai,n)&&!Yr.call(ai[n],e)&&(ai[n][e]=!1)}}(),n.prototype=e.prototype;var ui=e.support={};!function(){var e=function(){this.x=1},n={0:1,length:1},r=[];e.prototype={valueOf:1,y:1};for(var i in new e)r.push(i);for(i in arguments);ui.argsClass=Ir.call(arguments)==B,ui.argsObject=arguments.constructor==Tr&&!(arguments instanceof Sr),ui.enumErrorProps=$r.call(Lr,"message")||$r.call(Lr,"name"),ui.enumPrototypes=$r.call(e,"prototype"),ui.funcDecomp=!ve(t.WinRTError)&&H.test(m),ui.funcNames="string"==typeof Cr.name,ui.nonEnumArgs=0!=i,ui.nonEnumShadows=!/valueOf/.test(r),ui.ownLast="x"!=r[0],ui.spliceObjects=(Nr.splice.call(n,0,1),!n[0]),ui.unindexedChars="x"[0]+Tr("x")[0]!="xx";try{ui.nodeClass=!(Ir.call(document)==Z&&!({toString:0}+""))}catch(o){ui.nodeClass=!0}}(1),e.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:W,variable:"",imports:{_:e}};var li=function(t){var e="var index, iterable = "+t.firstArg+", result = "+t.init+";\nif (!iterable) return result;\n"+t.top+";";t.array?(e+="\nvar length = iterable.length; index = -1;\nif ("+t.array+") { ",ui.unindexedChars&&(e+="\n if (isString(iterable)) {\n iterable = iterable.split('')\n } "),e+="\n while (++index < length) {\n "+t.loop+";\n }\n}\nelse { "):ui.nonEnumArgs&&(e+="\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += '';\n "+t.loop+";\n }\n } else { "),ui.enumPrototypes&&(e+="\n var skipProto = typeof iterable == 'function';\n "),ui.enumErrorProps&&(e+="\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n ");var n=[];if(ui.enumPrototypes&&n.push('!(skipProto && index == "prototype")'),ui.enumErrorProps&&n.push('!(skipErrorProps && (index == "message" || index == "name"))'),t.useHas&&t.keys)e+="\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n",n.length&&(e+=" if ("+n.join(" && ")+") {\n "),e+=t.loop+"; ",n.length&&(e+="\n }"),e+="\n } ";else if(e+="\n for (index in iterable) {\n",t.useHas&&n.push("hasOwnProperty.call(iterable, index)"),n.length&&(e+=" if ("+n.join(" && ")+") {\n "),e+=t.loop+"; ",n.length&&(e+="\n }"),e+="\n } ",ui.nonEnumShadows){for(e+="\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n ",k=0;k<7;k++)e+="\n index = '"+t.shadowedProps[k]+"';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))",t.useHas||(e+=" || (!nonEnum[index] && iterable[index] !== objectProto[index])"),e+=") {\n "+t.loop+";\n } ";e+="\n } "}return(t.array||ui.nonEnumArgs)&&(e+="\n}"),e+=t.bottom+";\nreturn result"};Gr||(a=function(){function e(){}return function(n){if(Ie(n)){e.prototype=n;var r=new e;e.prototype=null}return r||t.Object()}}());var ci=Zr?function(t,e){ee.value=e,Zr(t,"__bindData__",ee)}:ur;ui.argsClass||(be=function(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Yr.call(t,"callee")&&!$r.call(t,"callee")||!1 });var fi=Jr||function(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Ir.call(t)==Y||!1},pi=he({args:"object",init:"[]",top:"if (!(objectTypes[typeof object])) return result",loop:"result.push(index)"}),hi=ei?function(t){return Ie(t)?ui.enumPrototypes&&"function"==typeof t||ui.nonEnumArgs&&t.length&&be(t)?pi(t):ei(t):[]}:pi,di={args:"collection, callback, thisArg",top:"callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)",array:"typeof length == 'number'",keys:hi,loop:"if (callback(iterable[index], index, collection) === false) return result"},gi={args:"object, source, guard",top:"var args = arguments,\n argsIndex = 0,\n argsLength = typeof guard == 'number' ? 2 : args.length;\nwhile (++argsIndex < argsLength) {\n iterable = args[argsIndex];\n if (iterable && objectTypes[typeof iterable]) {",keys:hi,loop:"if (typeof result[index] == 'undefined') result[index] = iterable[index]",bottom:" }\n}"},vi={top:"if (!objectTypes[typeof iterable]) return result;\n"+di.top,array:!1},yi={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},mi=Oe(yi),bi=Or("("+hi(mi).join("|")+")","g"),wi=Or("["+hi(yi).join("")+"]","g"),Si=he(di),_i=he(gi,{top:gi.top.replace(";",";\nif (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n callback = args[--argsLength];\n}"),loop:"result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]"}),xi=he(gi),ki=he(di,vi,{useHas:!1}),Ci=he(di,vi);De(/x/)&&(De=function(t){return"function"==typeof t&&Ir.call(t)==V});var Ei=Br?function(t){if(!t||Ir.call(t)!=Z||!ui.argsClass&&be(t))return!1;var e=t.valueOf,n=ve(e)&&(n=Br(e))&&Br(n);return n?t==n||Br(t)==n:ye(t)}:ye,ji=fe(function(t,e,n){Yr.call(t,n)?t[n]++:t[n]=1}),Ti=fe(function(t,e,n){(Yr.call(t,n)?t[n]:t[n]=[]).push(e)}),Oi=fe(function(t,e,n){t[n]=e}),Pi=an,Mi=tn,Ni=ve(Ni=xr.now)&&Ni||function(){return(new xr).getTime()},Li=8==ii(T+"08")?ii:function(t,e){return ii(Xe(t)?t.replace(D,""):t,e||0)};return e.after=zn,e.assign=_i,e.at=Ge,e.bind=Xn,e.bindAll=Bn,e.bindKey=Yn,e.chain=vr,e.compact=bn,e.compose=Un,e.constant=nr,e.countBy=ji,e.create=_e,e.createCallback=rr,e.curry=$n,e.debounce=Fn,e.defaults=xi,e.defer=Vn,e.delay=Kn,e.difference=wn,e.filter=tn,e.flatten=kn,e.forEach=rn,e.forEachRight=on,e.forIn=ki,e.forInRight=Ce,e.forOwn=Ci,e.forOwnRight=Ee,e.functions=je,e.groupBy=Ti,e.indexBy=Oi,e.initial=En,e.intersection=jn,e.invert=Oe,e.invoke=sn,e.keys=hi,e.map=an,e.mapValues=Ye,e.max=un,e.memoize=Zn,e.merge=Ue,e.min=ln,e.omit=$e,e.once=Gn,e.pairs=Fe,e.partial=Jn,e.partialRight=Qn,e.pick=Ve,e.pluck=Pi,e.property=lr,e.pull=Pn,e.range=Mn,e.reject=pn,e.remove=Nn,e.rest=Ln,e.shuffle=dn,e.sortBy=yn,e.tap=yr,e.throttle=tr,e.times=hr,e.toArray=mn,e.transform=Ke,e.union=Wn,e.uniq=Dn,e.values=Ze,e.where=Mi,e.without=In,e.wrap=er,e.xor=Hn,e.zip=Rn,e.zipObject=qn,e.collect=an,e.drop=Ln,e.each=rn,e.eachRight=on,e.extend=_i,e.methods=je,e.object=qn,e.select=tn,e.tail=Ln,e.unique=Dn,e.unzip=Rn,sr(e),e.clone=we,e.cloneDeep=Se,e.contains=Je,e.escape=ir,e.every=Qe,e.find=en,e.findIndex=Sn,e.findKey=xe,e.findLast=nn,e.findLastIndex=_n,e.findLastKey=ke,e.has=Te,e.identity=or,e.indexOf=Cn,e.isArguments=be,e.isArray=fi,e.isBoolean=Pe,e.isDate=Me,e.isElement=Ne,e.isEmpty=Le,e.isEqual=Ae,e.isFinite=We,e.isFunction=De,e.isNaN=He,e.isNull=Re,e.isNumber=qe,e.isObject=Ie,e.isPlainObject=Ei,e.isRegExp=ze,e.isString=Xe,e.isUndefined=Be,e.lastIndexOf=On,e.mixin=sr,e.noConflict=ar,e.noop=ur,e.now=Ni,e.parseInt=Li,e.random=cr,e.reduce=cn,e.reduceRight=fn,e.result=fr,e.runInContext=m,e.size=gn,e.some=vn,e.sortedIndex=An,e.template=pr,e.unescape=dr,e.uniqueId=gr,e.all=Qe,e.any=vn,e.detect=en,e.findWhere=en,e.foldl=cn,e.foldr=fn,e.include=Je,e.inject=cn,sr(function(){var t={};return Ci(e,function(n,r){e.prototype[r]||(t[r]=n)}),t}(),!1),e.first=xn,e.last=Tn,e.sample=hn,e.take=xn,e.head=xn,Ci(e,function(t,r){var i="sample"!==r;e.prototype[r]||(e.prototype[r]=function(e,r){var o=this.__chain__,s=t(this.__wrapped__,e,r);return o||null!=e&&(!r||i&&"function"==typeof e)?new n(s,o):s})}),e.VERSION="2.4.1",e.prototype.chain=mr,e.prototype.toString=br,e.prototype.value=wr,e.prototype.valueOf=wr,Si(["join","pop","shift"],function(t){var r=Nr[t];e.prototype[t]=function(){var t=this.__chain__,e=r.apply(this.__wrapped__,arguments);return t?new n(e,t):e}}),Si(["push","reverse","sort","unshift"],function(t){var n=Nr[t];e.prototype[t]=function(){return n.apply(this.__wrapped__,arguments),this}}),Si(["concat","slice","splice"],function(t){var r=Nr[t];e.prototype[t]=function(){return new n(r.apply(this.__wrapped__,arguments),this.__chain__)}}),ui.spliceObjects||Si(["pop","shift","splice"],function(t){var r=Nr[t],i="splice"==t;e.prototype[t]=function(){var t=this.__chain__,e=this.__wrapped__,o=r.apply(e,arguments);return 0===e.length&&delete e[0],t||i?new n(o,t):o}}),e}var b,w=[],S=[],_=0,x={},C=+new Date+"",E=75,j=40,T=" \f \n\r\u2028\u2029 ᠎              ",O=/\b__p \+= '';/g,P=/\b(__p \+=) '' \+/g,M=/(__e\(.*?\)|\b__t\)) \+\n'';/g,N=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,L=/\w*$/,A=/^\s*function[ \n\r\t]+\w/,W=/<%=([\s\S]+?)%>/g,D=RegExp("^["+T+"]*0+(?=.$)"),I=/($^)/,H=/\bthis\b/,R=/['\n\r\t\u2028\u2029\\]/g,q=["Array","Boolean","Date","Error","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],z=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],X=0,B="[object Arguments]",Y="[object Array]",U="[object Boolean]",$="[object Date]",F="[object Error]",V="[object Function]",K="[object Number]",Z="[object Object]",G="[object RegExp]",J="[object String]",Q={};Q[V]=!1,Q[B]=Q[Y]=Q[U]=Q[$]=Q[K]=Q[Z]=Q[G]=Q[J]=!0;var te={leading:!1,maxWait:0,trailing:!1},ee={configurable:!1,enumerable:!1,value:null,writable:!1},ne={args:"",array:null,bottom:"",firstArg:"",init:"",keys:null,loop:"",shadowedProps:null,support:null,top:"",useHas:!1},re={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},ie={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},oe=re[typeof window]&&window||this,se=re[typeof e]&&e&&!e.nodeType&&e,ae=re[typeof t]&&t&&!t.nodeType&&t,ue=(ae&&ae.exports===se&&se,re[typeof i]&&i);!ue||ue.global!==ue&&ue.window!==ue||(oe=ue);var le=m();oe._=le,r=function(){return le}.call(e,n,e,t),!(r!==b&&(t.exports=r))}).call(this)}).call(e,n(17)(t),function(){return this}())},function(t){var e={changeSlide:function(t){var e,n,r;if(r=this.state.slideCount%this.props.slidesToScroll!==0,e=r?0:(this.state.slideCount-this.state.currentSlide)%this.props.slidesToScroll,"previous"===t.message)n=0===e?this.props.slidesToScroll:this.props.slidesToShow-e,this.state.slideCount>this.props.slidesToShow&&this.slideHandler(this.state.currentSlide-n,!1);else if("next"===t.message)n=0===e?this.props.slidesToScroll:e,this.state.slideCount>this.props.slidesToShow&&this.slideHandler(this.state.currentSlide+n,!1);else if("index"===t.message){var i=t.index*this.props.slidesToScroll;i!==this.state.currentSlide&&this.slideHandler(i)}this.autoPlay()},keyHandler:function(){},selectHandler:function(){},swipeStart:function(t){var e,n;e=void 0!==t.touches?t.touches[0].pageX:t.clientX,n=void 0!==t.touches?t.touches[0].pageY:t.clientY,this.setState({dragging:!0,touchObject:{startX:e,startY:n,curX:e,curY:n}}),t.preventDefault()},swipeMove:function(t){if(this.state.dragging){var e,n,r=this.state.touchObject;n=this.getLeft(this.state.currentSlide),r.curX=t.touches?t.touches[0].pageX:t.clientX,r.curY=t.touches?t.touches[0].pageY:t.clientY,r.swipeLength=Math.round(Math.sqrt(Math.pow(r.curX-r.startX,2))),positionOffset=(this.props.rtl===!1?1:-1)*(r.curX>r.startX?1:-1),e=n+r.swipeLength*positionOffset,this.setState({touchObject:r,swipeLeft:e,trackStyle:this.getCSS(e)})}t.preventDefault()},swipeEnd:function(t){var e=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,r=this.swipeDirection(e);this.setState({dragging:!1,touchObject:{}}),e.swipeLength>n?"left"===r?this.slideHandler(this.state.currentSlide+this.props.slidesToScroll):"right"===r?this.slideHandler(this.state.currentSlide-this.props.slidesToScroll):this.slideHandler(this.state.currentSlide,null,!0):this.slideHandler(this.state.currentSlide,null,!0),t.preventDefault()}};t.exports=e},function(t,e,n){var r=(n(4),n(2)),i=n(13),o=n(14),s={initialize:function(t){var e=r.Children.count(t.children),n=this.refs.list.getDOMNode().getBoundingClientRect().width,i=this.refs.track.getDOMNode().getBoundingClientRect().width,o=this.getDOMNode().getBoundingClientRect().width/t.slidesToShow;this.setState({slideCount:e,slideWidth:o,listWidth:n,trackWidth:i,currentSlide:0},function(){var t=this.getCSS(this.getLeft(0));this.setState({trackStyle:t})})},getDotCount:function(){var t;return t=Math.ceil(this.state.slideCount/this.props.slidesToScroll),t-1},getLeft:function(t){var e,n=0;if(this.props.infinite===!0&&(this.state.slideCount>this.props.slidesToShow&&(n=this.state.slideWidth*this.props.slidesToShow*-1),this.state.slideCount%this.props.slidesToScroll!==0&&t+this.props.slidesToScroll>this.state.slideCount&&this.state.slideCount>this.props.slidesToShow&&(n=t>this.state.slideCount?(this.props.slidesToShow-(t-this.state.slideCount))*this.state.slideWidth*-1:this.state.slideCount%this.props.slidesToScroll*this.state.slideWidth*-1)),this.props.centerMode===!0&&this.props.infinite===!0?n+=this.state.slideWidth*Math.floor(this.props.slidesToShow/2)-this.state.slideWidth:this.props.centerMode===!0&&(n=this.state.slideWidth*Math.floor(this.props.slidesToShow/2)),e=t*this.state.slideWidth*-1+n,this.props.variableWidth===!0){var r;this.state.slideCount<=this.props.slidesToShow||this.props.infinite===!1?targetSlide=this.refs.track.getDOMNode().childNodes[t]:(r=t+this.props.slidesToShow,targetSlide=this.refs.track.getDOMNode().childNodes[r]),e=targetSlide?-1*targetSlide.offsetLeft:0,this.props.centerMode===!0&&(targetSlide=this.props.infinite===!1?this.refs.track.getDOMNode().childNodes[t]:this.refs.track.getDOMNode().childNodes[t+this.props.slidesToShow+1],e=targetSlide?-1*targetSlide.offsetLeft:0,e+=(this.state.listWidth-targetSlide.offsetWidth)/2)}return e},getAnimateCSS:function(t){var e=this.getCSS(t);return e.transition="transform 500ms ease",e},getCSS:function(t){var e;e=this.props.variableWidth?(this.state.slideCount+2*this.props.slidesToShow)*this.state.slideWidth:this.props.centerMode?(this.state.slideCount+2*(this.props.slidesToShow+1))*this.state.slideWidth:(this.state.slideCount+2*this.props.slidesToShow)*this.state.slideWidth;var n={opacity:1,width:e,WebkitTransform:"translate3d("+t+"px, 0px, 0px)",transform:"translate3d("+t+"px, 0px, 0px)"};return n},getSlideStyle:function(){return{width:this.state.slideWidth}},getSlideClasses:function(t){var e,n,r,o,s,a,u,l=!1;return r=0>t||t>=this.state.slideCount,this.props.centerMode?(this.refs.track&&(a=this.refs.track.getDOMNode().childNodes.length),o=Math.floor(this.props.slidesToShow/2),s=this.state.currentSlide+this.props.slidesToShow,u=this.state.currentSlide+o,n=u-1===t,this.state.currentSlide>=o&&this.state.currentSlide<=this.props.slideCount-1-o&&(l=!0),l&&t>this.state.currentSlide-o&&t<=this.state.currentSlide+o+1&&(e=!0)):e=this.state.currentSlide===t,i({"slick-slide":!0,"slick-active":e,"slick-center":n,"slick-cloned":r})},getListStyle:function(){var t={};if(this.props.adaptiveHeight){var e='[data-index="'+this.state.currentSlide+'"]';this.refs.list&&(t.height=this.refs.list.getDOMNode().querySelector(e).offsetHeight)}return t},slideHandler:function(t){var e,n,r,i;this.state.animating!==!0&&(this.props.fade!==!0||this.state.currentSlide!==t)&&(this.state.slideCount<=this.props.slidesToShow||(e=t,n=0>e?this.state.slideCount%this.props.slidesToScroll!==0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+e:e>=this.state.slideCount?this.state.slideCount%this.props.slidesToScroll!==0?0:e-this.state.slideCount:e,r=this.getLeft(e,this.state),i=this.getLeft(n,this.state),this.props.infinite===!1&&(r=i),this.setState({animating:!0,currentSlide:n,currentLeft:i,trackStyle:this.getAnimateCSS(r)},function(){o.addEndEventListener(this.refs.track.getDOMNode(),function(){this.setState({animating:!1,trackStyle:this.getCSS(i),swipeLeft:null})}.bind(this))})))},swipeDirection:function(t){var e,n,r,i;return e=t.startX-t.curX,n=t.startY-t.curY,r=Math.atan2(n,e),i=Math.round(180*r/Math.PI),0>i&&(i=360-Math.abs(i)),45>=i&&i>=0?this.props.rtl===!1?"left":"right":360>=i&&i>=315?this.props.rtl===!1?"left":"right":i>=135&&225>=i?this.props.rtl===!1?"right":"left":"vertical"},autoPlay:function(){var t=function(){this.slideHandler(this.state.currentSlide+this.props.slidesToScroll)}.bind(this);this.props.autoplay&&window.setInterval(t,this.props.autoplaySpeed)}};t.exports=s},function(t){var e={animating:!1,dragging:!1,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,slideCount:null,slideWidth:null,swipeLeft:null,touchObject:{startX:0,startY:0,curX:0,curY:0},initialized:!1,trackStyle:{},trackWidth:0};t.exports=e},function(t){var e={className:"",accessibility:!0,adaptiveHeight:!1,arrows:!0,autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",onBeforeChange:null,onAfterChange:null,onInit:null,onReInit:null,onSetPosition:null,pauseOnHover:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rtl:!1,slide:"div",slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,variableWidth:!1,vertical:!1};t.exports=e},function(t,e,n){"use strict";function r(t,e){a(!t.ref,"You are calling cloneWithProps() on a child with a ref. This is dangerous because you're creating a new child which will not be added as a ref to its parent.");var n=o.mergeProps(e,t.props);return!n.hasOwnProperty(u)&&t.props.hasOwnProperty(u)&&(n.children=t.props.children),i.createElement(t.type,n)}var i=n(19),o=n(20),s=n(21),a=n(22),u=s({children:null});t.exports=r},function(t){function e(t){return"object"==typeof t?Object.keys(t).filter(function(e){return t[e]}).join(" "):Array.prototype.join.call(arguments," ")}t.exports=e},function(t,e,n){"use strict";function r(){var t=document.createElement("div"),e=t.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a){var r=a[n];for(var i in r)if(i in e){u.push(r[i]);break}}}function i(t,e,n){t.addEventListener(e,n,!1)}function o(t,e,n){t.removeEventListener(e,n,!1)}var s=n(23),a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},u=[];s.canUseDOM&&r();var l={addEndEventListener:function(t,e){return 0===u.length?void window.setTimeout(e,0):void u.forEach(function(n){i(t,n,e)})},removeEndEventListener:function(t,e){0!==u.length&&u.forEach(function(n){o(t,n,e)})}};t.exports=l},function(t,e,n){var r=n(30),i=function(t){var e=/[height|width]$/;return e.test(t)},o=function(t){var e="",n=Object.keys(t);return n.forEach(function(o,s){var a=t[o];o=r(o),i(o)&&"number"==typeof a&&(a+="px"),e+=a===!0?o:a===!1?"not "+o:"("+o+": "+a+")",s<n.length-1&&(e+=" and ")}),e},s=function(t){var e="";return"string"==typeof t?t:t instanceof Array?(t.forEach(function(n,r){e+=o(n),r<t.length-1&&(e+=", ")}),e):o(t)};t.exports=s},function(t){var e=function(t){return t.replace(/[A-Z]/g,function(t){return"-"+t.toLowerCase()}).toLowerCase()};t.exports=e},function(t){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}},function(t,e,n){var r;!function(i,o,s){var a=window.matchMedia;"undefined"!=typeof t&&t.exports?t.exports=s(a):(r=function(){return o[i]=s(a)}.call(e,n,e,t),!(void 0!==r&&(t.exports=r)))}("enquire",this,function(t){"use strict";function e(t,e){var n,r=0,i=t.length;for(r;i>r&&(n=e(t[r],r),n!==!1);r++);}function n(t){return"[object Array]"===Object.prototype.toString.apply(t)}function r(t){return"function"==typeof t}function i(t){this.options=t,!t.deferSetup&&this.setup()}function o(e,n){this.query=e,this.isUnconditional=n,this.handlers=[],this.mql=t(e);var r=this;this.listener=function(t){r.mql=t,r.assess()},this.mql.addListener(this.listener)}function s(){if(!t)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!t("only all").matches}return i.prototype={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(t){return this.options===t||this.options.match===t}},o.prototype={addHandler:function(t){var e=new i(t);this.handlers.push(e),this.matches()&&e.on()},removeHandler:function(t){var n=this.handlers;e(n,function(e,r){return e.equals(t)?(e.destroy(),!n.splice(r,1)):void 0})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){e(this.handlers,function(t){t.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var t=this.matches()?"on":"off";e(this.handlers,function(e){e[t]()})}},s.prototype={register:function(t,i,s){var a=this.queries,u=s&&this.browserIsIncapable;return a[t]||(a[t]=new o(t,u)),r(i)&&(i={match:i}),n(i)||(i=[i]),e(i,function(e){a[t].addHandler(e)}),this},unregister:function(t,e){var n=this.queries[t];return n&&(e?n.removeHandler(e):(n.clear(),delete this.queries[t])),this}},new s})},function(t,e,n){"use strict";function r(t,e){Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[e]:null},set:function(t){a(!1,"Don't set the "+e+" property of the component. Mutate the existing props object instead."),this._store[e]=t}})}function i(t){try{var e={props:!0};for(var n in e)r(t,n);l=!0}catch(i){}}var o=n(24),s=n(25),a=n(22),u={key:!0,ref:!0},l=!1,c=function(t,e,n,r,i,o){return this.type=t,this.key=e,this.ref=n,this._owner=r,this._context=i,this._store={validated:!1,props:o},l?void Object.freeze(this):void(this.props=o)};c.prototype={_isReactElement:!0},i(c.prototype),c.createElement=function(t,e,n){var r,i={},l=null,f=null;if(null!=e){f=void 0===e.ref?null:e.ref,a(null!==e.key,"createElement(...): Encountered component with a `key` of null. In a future version, this will be treated as equivalent to the string 'null'; instead, provide an explicit key or use undefined."),l=null==e.key?null:""+e.key;for(r in e)e.hasOwnProperty(r)&&!u.hasOwnProperty(r)&&(i[r]=e[r])}var p=arguments.length-2;if(1===p)i.children=n;else if(p>1){for(var h=Array(p),d=0;p>d;d++)h[d]=arguments[d+2];i.children=h}if(t&&t.defaultProps){var g=t.defaultProps;for(r in g)"undefined"==typeof i[r]&&(i[r]=g[r])}return new c(t,l,f,s.current,o.current,i)},c.createFactory=function(t){var e=c.createElement.bind(null,t);return e.type=t,e},c.cloneAndReplaceProps=function(t,e){var n=new c(t.type,t.key,t.ref,t._owner,t._context,e);return n._store.validated=t._store.validated,n},c.isValidElement=function(t){var e=!(!t||!t._isReactElement);return e},t.exports=c},function(t,e,n){"use strict";function r(t){return function(e,n,r){e[n]=e.hasOwnProperty(n)?t(e[n],r):r}}function i(t,e){for(var n in e)if(e.hasOwnProperty(n)){var r=p[n];r&&p.hasOwnProperty(n)?r(t,n,e[n]):t.hasOwnProperty(n)||(t[n]=e[n])}return t}var o=n(26),s=n(27),a=n(28),u=n(29),l=n(22),c=!1,f=r(function(t,e){return o({},e,t)}),p={children:s,className:r(u),style:f},h={TransferStrategies:p,mergeProps:function(t,e){return i(o({},t),e)},Mixin:{transferPropsTo:function(t){return a(t._owner===this,"%s: You can't call transferPropsTo() on a component that you don't own, %s. This usually means you are calling transferPropsTo() on a component passed in as props or children.",this.constructor.displayName,"string"==typeof t.type?t.type:t.type.displayName),c||(c=!0,l(!1,"transferPropsTo is deprecated. See http://fb.me/react-transferpropsto for more information.")),i(t.props,this.props),t}}};t.exports=h},function(t){var e=function(t){var e;for(e in t)if(t.hasOwnProperty(e))return e;return null};t.exports=e},function(t,e,n){"use strict";var r=n(27),i=r;i=function(t,e){for(var n=[],r=2,i=arguments.length;i>r;r++)n.push(arguments[r]);if(void 0===e)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!t){var o=0;console.warn("Warning: "+e.replace(/%s/g,function(){return n[o++]}))}},t.exports=i},function(t){"use strict";var e=!("undefined"==typeof window||!window.document||!window.document.createElement),n={canUseDOM:e,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:e&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:e&&!!window.screen,isInWorker:!e};t.exports=n},function(t,e,n){"use strict";var r=n(26),i={current:{},withContext:function(t,e){var n,o=i.current;i.current=r({},o,t);try{n=e()}finally{i.current=o}return n}};t.exports=i},function(t){"use strict";var e={current:null};t.exports=e},function(t){function e(t){if(null==t)throw new TypeError("Object.assign target cannot be null or undefined");for(var e=Object(t),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var i=arguments[r];if(null!=i){var o=Object(i);for(var s in o)n.call(o,s)&&(e[s]=o[s])}}return e}t.exports=e},function(t){function e(t){return function(){return t}}function n(){}n.thatReturns=e,n.thatReturnsFalse=e(!1),n.thatReturnsTrue=e(!0),n.thatReturnsNull=e(null),n.thatReturnsThis=function(){return this},n.thatReturnsArgument=function(t){return t},t.exports=n},function(t){"use strict";var e=function(t,e,n,r,i,o,s,a){if(void 0===e)throw new Error("invariant requires an error message argument");if(!t){var u;if(void 0===e)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,i,o,s,a],c=0;u=new Error("Invariant Violation: "+e.replace(/%s/g,function(){return l[c++]}))}throw u.framesToPop=1,u}};t.exports=e},function(t){"use strict";function e(t){t||(t="");var e,n=arguments.length;if(n>1)for(var r=1;n>r;r++)e=arguments[r],e&&(t=(t?t+" ":"")+e);return t}t.exports=e},function(t){var e=function(t){return t.replace(/[A-Z]/g,function(t){return"-"+t.toLowerCase()}).toLowerCase()};t.exports=e}]);
src/client/index.js
aarmour/my-denver
import 'babel-polyfill'; import mapboxgl from 'mapbox-gl'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import routes from '../common/routes'; const mapbox = window.__MAPBOX__; mapboxgl.accessToken = mapbox.accessToken; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); render( <Provider store={store}> {routes} </Provider>, rootElement );
node_modules/reactify/node_modules/react-tools/src/core/__tests__/ReactMultiChildText-test.js
SlateRobotics/slate-website
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ /*jslint evil: true */ 'use strict'; require('mock-modules'); var React = require('React'); var ReactFragment = require('ReactFragment'); var ReactTestUtils = require('ReactTestUtils'); var reactComponentExpect = require('reactComponentExpect'); var frag = ReactFragment.create; // Helpers var testAllPermutations = function(testCases) { for (var i = 0; i < testCases.length; i += 2) { var renderWithChildren = testCases[i]; var expectedResultAfterRender = testCases[i + 1]; for (var j = 0; j < testCases.length; j += 2) { var updateWithChildren = testCases[j]; var expectedResultAfterUpdate = testCases[j + 1]; var d = renderChildren(renderWithChildren); expectChildren(d, expectedResultAfterRender); updateChildren(d, updateWithChildren); expectChildren(d, expectedResultAfterUpdate); } } }; var renderChildren = function(children) { return ReactTestUtils.renderIntoDocument( <div>{children}</div> ); }; var updateChildren = function(d, children) { d.replaceProps({children: children}); }; var expectChildren = function(d, children) { var textNode; if (typeof children === 'string') { textNode = d.getDOMNode().firstChild; if (children === '') { expect(textNode != null).toBe(false); } else { expect(textNode != null).toBe(true); expect(textNode.nodeType).toBe(3); expect(textNode.data).toBe('' + children); } } else { expect(d.getDOMNode().childNodes.length).toBe(children.length); for (var i = 0; i < children.length; i++) { var child = children[i]; if (typeof child === 'string') { reactComponentExpect(d) .expectRenderedChildAt(i) .toBeTextComponentWithValue(child); textNode = d.getDOMNode().childNodes[i].firstChild; if (child === '') { expect(textNode != null).toBe(false); } else { expect(textNode != null).toBe(true); expect(textNode.nodeType).toBe(3); expect(textNode.data).toBe('' + child); } } else { var elementDOMNode = reactComponentExpect(d) .expectRenderedChildAt(i) .toBeComponentOfType('div') .instance() .getDOMNode(); expect(elementDOMNode.tagName).toBe('DIV'); } } } }; /** * ReactMultiChild DOM integration test. In ReactDOM components, we make sure * that single children that are strings are treated as "content" which is much * faster to render and update. */ describe('ReactMultiChildText', function() { it('should correctly handle all possible children for render and update', function() { testAllPermutations([ // basic values undefined, [], null, [], false, [], true, [], 0, '0', 1.2, '1.2', '', '', 'foo', 'foo', [], [], [undefined], [], [null], [], [false], [], [true], [], [0], ['0'], [1.2], ['1.2'], [''], [''], ['foo'], ['foo'], [<div />], [<div />], // two adjacent values [true, 0], ['0'], [0, 0], ['0', '0'], [1.2, 0], ['1.2', '0'], [0, ''], ['0', ''], ['foo', 0], ['foo', '0'], [0, <div />], ['0', <div />], [true, 1.2], ['1.2'], [1.2, 0], ['1.2', '0'], [1.2, 1.2], ['1.2', '1.2'], [1.2, ''], ['1.2', ''], ['foo', 1.2], ['foo', '1.2'], [1.2, <div />], ['1.2', <div />], [true, ''], [''], ['', 0], ['', '0'], [1.2, ''], ['1.2', ''], ['', ''], ['', ''], ['foo', ''], ['foo', ''], ['', <div />], ['', <div />], [true, 'foo'], ['foo'], ['foo', 0], ['foo', '0'], [1.2, 'foo'], ['1.2', 'foo'], ['foo', ''], ['foo', ''], ['foo', 'foo'], ['foo', 'foo'], ['foo', <div />], ['foo', <div />], // values separated by an element [true, <div />, true], [<div />], [1.2, <div />, 1.2], ['1.2', <div />, '1.2'], ['', <div />, ''], ['', <div />, ''], ['foo', <div />, 'foo'], ['foo', <div />, 'foo'], [true, 1.2, <div />, '', 'foo'], ['1.2', <div />, '', 'foo'], [1.2, '', <div />, 'foo', true], ['1.2', '', <div />, 'foo'], ['', 'foo', <div />, true, 1.2], ['', 'foo', <div />, '1.2'], [true, 1.2, '', <div />, 'foo', true, 1.2], ['1.2', '', <div />, 'foo', '1.2'], ['', 'foo', true, <div />, 1.2, '', 'foo'], ['', 'foo', <div />, '1.2', '', 'foo'], // values inside arrays [[true], [true]], [], [[1.2], [1.2]], ['1.2', '1.2'], [[''], ['']], ['', ''], [['foo'], ['foo']], ['foo', 'foo'], [[<div />], [<div />]], [<div />, <div />], [[true, 1.2, <div />], '', 'foo'], ['1.2', <div />, '', 'foo'], [1.2, '', [<div />, 'foo', true]], ['1.2', '', <div />, 'foo'], ['', ['foo', <div />, true], 1.2], ['', 'foo', <div />, '1.2'], [true, [1.2, '', <div />, 'foo'], true, 1.2], ['1.2', '', <div />, 'foo', '1.2'], ['', 'foo', [true, <div />, 1.2, ''], 'foo'], ['', 'foo', <div />, '1.2', '', 'foo'], // values inside objects [frag({a: true}), frag({a: true})], [], [frag({a: 1.2}), frag({a: 1.2})], ['1.2', '1.2'], [frag({a: ''}), frag({a: ''})], ['', ''], [frag({a: 'foo'}), frag({a: 'foo'})], ['foo', 'foo'], [frag({a: <div />}), frag({a: <div />})], [<div />, <div />], [frag({a: true, b: 1.2, c: <div />}), '', 'foo'], ['1.2', <div />, '', 'foo'], [1.2, '', frag({a: <div />, b: 'foo', c: true})], ['1.2', '', <div />, 'foo'], ['', frag({a: 'foo', b: <div />, c: true}), 1.2], ['', 'foo', <div />, '1.2'], [true, frag({a: 1.2, b: '', c: <div />, d: 'foo'}), true, 1.2], ['1.2', '', <div />, 'foo', '1.2'], ['', 'foo', frag({a: true, b: <div />, c: 1.2, d: ''}), 'foo'], ['', 'foo', <div />, '1.2', '', 'foo'], // values inside elements [<div>{true}{1.2}{<div />}</div>, '', 'foo'], [<div />, '', 'foo'], [1.2, '', <div>{<div />}{'foo'}{true}</div>], ['1.2', '', <div />], ['', <div>{'foo'}{<div />}{true}</div>, 1.2], ['', <div />, '1.2'], [true, <div>{1.2}{''}{<div />}{'foo'}</div>, true, 1.2], [<div />, '1.2'], ['', 'foo', <div>{true}{<div />}{1.2}{''}</div>, 'foo'], ['', 'foo', <div />, 'foo'] ]); }); it('should throw if rendering both HTML and children', function() { expect(function() { ReactTestUtils.renderIntoDocument( <div dangerouslySetInnerHTML={{_html: 'abcdef'}}>ghjkl</div> ); }).toThrow(); }); it('should render between nested components and inline children', function() { ReactTestUtils.renderIntoDocument(<div><h1><span /><span /></h1></div>); expect(function() { ReactTestUtils.renderIntoDocument(<div><h1>A</h1></div>); }).not.toThrow(); expect(function() { ReactTestUtils.renderIntoDocument(<div><h1>{['A']}</h1></div>); }).not.toThrow(); expect(function() { ReactTestUtils.renderIntoDocument(<div><h1>{['A', 'B']}</h1></div>); }).not.toThrow(); }); });
src/DateTimePickerYears.js
Vydia/react-bootstrap-datetimepicker
import React, { Component, PropTypes } from "react"; import classnames from "classnames"; export default class DateTimePickerYears extends Component { static propTypes = { subtractDecade: PropTypes.func.isRequired, addDecade: PropTypes.func.isRequired, viewDate: PropTypes.object.isRequired, selectedDate: PropTypes.object.isRequired, setViewYear: PropTypes.func.isRequired } renderYears = () => { var classes, i, year, years; years = []; year = parseInt(this.props.viewDate.year() / 10, 10) * 10; year--; i = -1; while (i < 11) { classes = { year: true, old: i === -1 | i === 10, active: this.props.selectedDate.year() === year }; years.push(<span className={classnames(classes)} key={year}onClick={this.props.setViewYear}>{year}</span>); year++; i++; } return years; } render() { var year; year = parseInt(this.props.viewDate.year() / 10, 10) * 10; return ( <div className="datepicker-years" style={{display: "block"}}> <table className="table-condensed"> <thead> <tr> <th className="prev" onClick={this.props.subtractDecade}>‹</th> <th className="switch" colSpan="5">{year} - {year + 9}</th> <th className="next" onClick={this.props.addDecade}>›</th> </tr> </thead> <tbody> <tr> <td colSpan="7">{this.renderYears()}</td> </tr> </tbody> </table> </div> ); } }
lib/containers/github-tab-container.js
atom/github
import React from 'react'; import PropTypes from 'prop-types'; import yubikiri from 'yubikiri'; import {Disposable} from 'event-kit'; import {GithubLoginModelPropType, RefHolderPropType} from '../prop-types'; import OperationStateObserver, {PUSH, PULL, FETCH} from '../models/operation-state-observer'; import Refresher from '../models/refresher'; import GitHubTabController from '../controllers/github-tab-controller'; import ObserveModel from '../views/observe-model'; import RemoteSet from '../models/remote-set'; import {nullRemote} from '../models/remote'; import BranchSet from '../models/branch-set'; import {nullBranch} from '../models/branch'; import {DOTCOM} from '../models/endpoint'; export default class GitHubTabContainer extends React.Component { static propTypes = { workspace: PropTypes.object.isRequired, repository: PropTypes.object, loginModel: GithubLoginModelPropType.isRequired, rootHolder: RefHolderPropType.isRequired, changeWorkingDirectory: PropTypes.func.isRequired, onDidChangeWorkDirs: PropTypes.func.isRequired, getCurrentWorkDirs: PropTypes.func.isRequired, openCreateDialog: PropTypes.func.isRequired, openPublishDialog: PropTypes.func.isRequired, openCloneDialog: PropTypes.func.isRequired, openGitTab: PropTypes.func.isRequired, } constructor(props) { super(props); this.state = { lastRepository: null, remoteOperationObserver: new Disposable(), refresher: new Refresher(), observerSub: new Disposable(), }; } static getDerivedStateFromProps(props, state) { if (props.repository !== state.lastRepository) { state.remoteOperationObserver.dispose(); state.observerSub.dispose(); const remoteOperationObserver = new OperationStateObserver(props.repository, PUSH, PULL, FETCH); const observerSub = remoteOperationObserver.onDidComplete(() => state.refresher.trigger()); return { lastRepository: props.repository, remoteOperationObserver, observerSub, }; } return null; } componentWillUnmount() { this.state.observerSub.dispose(); this.state.remoteOperationObserver.dispose(); this.state.refresher.dispose(); } fetchRepositoryData = repository => { return yubikiri({ workingDirectory: repository.getWorkingDirectoryPath(), allRemotes: repository.getRemotes(), branches: repository.getBranches(), selectedRemoteName: repository.getConfig('atomGithub.currentRemote'), aheadCount: async query => { const branches = await query.branches; const currentBranch = branches.getHeadBranch(); return repository.getAheadCount(currentBranch.getName()); }, pushInProgress: repository.getOperationStates().isPushInProgress(), }); } fetchToken = (loginModel, endpoint) => loginModel.getToken(endpoint.getLoginAccount()); render() { return ( <ObserveModel model={this.props.repository} fetchData={this.fetchRepositoryData}> {this.renderRepositoryData} </ObserveModel> ); } renderRepositoryData = repoData => { let endpoint = DOTCOM; if (repoData) { repoData.githubRemotes = repoData.allRemotes.filter(remote => remote.isGithubRepo()); repoData.currentBranch = repoData.branches.getHeadBranch(); repoData.currentRemote = repoData.githubRemotes.withName(repoData.selectedRemoteName); repoData.manyRemotesAvailable = false; if (!repoData.currentRemote.isPresent() && repoData.githubRemotes.size() === 1) { repoData.currentRemote = Array.from(repoData.githubRemotes)[0]; } else if (!repoData.currentRemote.isPresent() && repoData.githubRemotes.size() > 1) { repoData.manyRemotesAvailable = true; } repoData.endpoint = endpoint = repoData.currentRemote.getEndpointOrDotcom(); } return ( <ObserveModel model={this.props.loginModel} fetchData={this.fetchToken} fetchParams={[endpoint]}> {token => this.renderToken(token, repoData)} </ObserveModel> ); } renderToken(token, repoData) { if (!repoData || this.props.repository.isLoading()) { return ( <GitHubTabController {...this.props} refresher={this.state.refresher} allRemotes={new RemoteSet()} githubRemotes={new RemoteSet()} currentRemote={nullRemote} branches={new BranchSet()} currentBranch={nullBranch} aheadCount={0} manyRemotesAvailable={false} pushInProgress={false} isLoading={true} token={token} /> ); } if (!this.props.repository.isPresent()) { return ( <GitHubTabController {...this.props} refresher={this.state.refresher} allRemotes={new RemoteSet()} githubRemotes={new RemoteSet()} currentRemote={nullRemote} branches={new BranchSet()} currentBranch={nullBranch} aheadCount={0} manyRemotesAvailable={false} pushInProgress={false} isLoading={false} token={token} /> ); } return ( <GitHubTabController {...repoData} {...this.props} refresher={this.state.refresher} isLoading={false} token={token} /> ); } }
generators/react/template/index.js
ui-storybook/sb-cli
import React from 'react'; import ReactDOM from 'react-dom'; import 'sb-react-helper'; // Hot reload support if (module.hot) { module.hot.accept(); window.parent.sb && window.parent.sb.contact(); } // Remove this demo component import { Welcome } from './welcome/welcome'; // Import your app here and SB will load it // For more details see docs here https://github.com/ui-storybook/sb
client/src/components/Auth.js
xmas-bunch/amigo-invisible
import React, { Component } from 'react'; class Auth extends Component { setUser(e) { e.preventDefault(); this.props.setUser(this.refs.username.value); } login(e) { e.preventDefault(); this.props.login({ password: this.refs.password.value }) } register(e) { e.preventDefault(); this.props.register({ password1: this.refs.password1.value, password2: this.refs.password2.value }); } render() { if (this.props.user == null) { let userOptions = this.props.users.map(user => { return ( <option key={user.id} value={user.id}>{user.username}</option> ) }); return ( <form onSubmit={this.setUser.bind(this)}> <h3>Seleccione usuario</h3> <select ref="username"> {userOptions} </select> <button type="submit">Confirmar usuario</button> </form> ); } else if (!this.props.user.hasPassword){ return ( <form onSubmit={this.register.bind(this)} onFocus={this.props.deleteMessage}> <h3>Registramiento</h3> <input placeholder="Contraseña" ref="password1" type="password" /> <input placeholder="Verificación" ref="password2" type="password" /> <button type="submit">Registrarse</button> <hr /> <button type="button" onClick={this.props.logout.bind(this)}>Salir</button> </form> ); } else { return ( <form onSubmit={this.login.bind(this)} onFocus={this.props.deleteMessage}> <h3>Ingresamiento</h3> <input placeholder="Contraseña" ref="password" type="password" /> <button type="submit">Ingresar</button> <hr /> <button type="button" onClick={this.props.logout.bind(this)}>Salir</button> </form> ); } } } export default Auth;
src/client.js
jhlav/mpn-web-app
/** * 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 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import deepForceUpdate from 'react-deep-force-update'; import queryString from 'query-string'; import { createPath } from 'history/PathUtils'; import App from './components/App'; import createFetch from './createFetch'; import configureStore from './store/configureStore'; import { updateMeta } from './DOMUtils'; import history from './history'; import createApolloClient from './core/createApolloClient'; import router from './router'; // Universal HTTP client const fetch = createFetch(window.fetch, { baseUrl: window.App.apiUrl, }); const apolloClient = createApolloClient(); // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, // For react-apollo client: apolloClient, // Initialize a new Redux store // http://redux.js.org/docs/basics/UsageWithReact.html store: configureStore(window.App.state, { fetch, history }), fetch, storeSubscription: null, }; const container = document.getElementById('app'); let currentLocation = history.location; let appInstance; const scrollPositionsHistory = {}; // Re-render the app when window.location changes async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; const isInitialRender = !action; try { context.pathname = location.pathname; context.query = queryString.parse(location.search); // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve(context); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } const renderReactApp = isInitialRender ? ReactDOM.hydrate : ReactDOM.render; appInstance = renderReactApp( <App context={context}>{route.component}</App>, container, () => { if (isInitialRender) { // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); return; } document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }, ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (!isInitialRender && currentLocation.key === location.key) { console.error('RSK will reload your page after error'); window.location.reload(); } } } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/mjackson/history#readme history.listen(onLocationChange); onLocationChange(currentLocation); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./router', () => { if (appInstance && appInstance.updater.isMounted(appInstance)) { // Force-update the whole tree, including components that refuse to update deepForceUpdate(appInstance); } onLocationChange(currentLocation); }); }
js/vendor/jquery-1.11.2.min.js
chadbaudoin/vimeo-gallery-bootstrap-carousel
/*! jQuery v1.11.2 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.2",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=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=hb(),z=hb(),A=hb(),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-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},eb=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fb){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 gb(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(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+rb(o[l]);w=ab.test(a)&&pb(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 hb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ib(a){return a[u]=!0,a}function jb(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function kb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function lb(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 mb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function nb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function ob(a){return ib(function(b){return b=+b,ib(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 pb(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=gb.support={},f=gb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=gb.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",eb,!1):e.attachEvent&&e.attachEvent("onunload",eb)),p=!f(g),c.attributes=jb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=jb(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=jb(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(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c="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))&&(jb(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(".#.+[+~]")}),jb(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))&&jb(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 lb(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?lb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},gb.matches=function(a,b){return gb(a,null,null,b)},gb.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 gb(b,n,null,[a]).length>0},gb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},gb.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},gb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},gb.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=gb.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=gb.selectors={cacheLength:50,createPseudo:ib,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||gb.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]&&gb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+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=gb.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()]||gb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ib(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:ib(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ib(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:ib(function(a){return function(b){return gb(a,b).length>0}}),contains:ib(function(a){return a=a.replace(cb,db),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ib(function(a){return W.test(a||"")||gb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:ob(function(){return[0]}),last:ob(function(a,b){return[b-1]}),eq:ob(function(a,b,c){return[0>c?c+b:c]}),even:ob(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:ob(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:ob(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:ob(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]=mb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=nb(b);function qb(){}qb.prototype=d.filters=d.pseudos,d.setFilters=new qb,g=gb.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?gb.error(a):z(a,i).slice(0)};function rb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sb(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 tb(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 ub(a,b,c){for(var d=0,e=b.length;e>d;d++)gb(a,b[d],c);return c}function vb(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 wb(a,b,c,d,e,f){return d&&!d[u]&&(d=wb(d)),e&&!e[u]&&(e=wb(e,f)),ib(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ub(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:vb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=vb(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=vb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sb(function(a){return a===b},h,!0),l=sb(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=[sb(tb(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 wb(i>1&&tb(m),i>1&&rb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xb(a.slice(i,e)),f>e&&xb(a=a.slice(e)),f>e&&rb(a))}m.push(c)}return tb(m)}function yb(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=vb(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&gb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ib(f):f}return h=gb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,yb(e,d)),f.selector=a}return f},i=gb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&pb(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&rb(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&pb(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=jb(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),jb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||kb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&jb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||kb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),jb(function(a){return null==a.getAttribute("disabled")})||kb(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}),gb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.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 Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e) }m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.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 cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); //# sourceMappingURL=jquery.min.map
packages/containers/src/Slider/Slider.stories.js
Talend/ui
import React from 'react'; import { Map } from 'immutable'; import Slider from '.'; const icons = [ 'talend-smiley-angry', 'talend-smiley-unhappy', 'talend-smiley-neutral', 'talend-smiley-satisfied', 'talend-smiley-enthusiast', ]; const delimiterStyle = { paddingTop: '25px', paddingBottom: '25px', borderBottom: '1px dashed grey', }; const paragraphStyle = { paddingLeft: '10px', }; const actions = [ { id: 'icon1', label: 'Click Me', icon: 'talend-smiley-angry', 'data-feature': 'action', link: true, hideLabel: true, }, { id: 'icon2', label: 'Click Me', icon: 'talend-smiley-neutral', 'data-feature': 'action', link: true, hideLabel: true, }, { id: 'icon3', label: 'Click Me', icon: 'talend-smiley-neutral', 'data-feature': 'action', link: true, hideLabel: true, }, { id: 'icon4', label: 'Click Me', icon: 'talend-smiley-neutral', 'data-feature': 'action', link: true, hideLabel: true, }, { id: 'icon5', label: 'Click Me', icon: 'talend-smiley-satisfied', 'data-feature': 'action', link: true, hideLabel: true, }, ]; const functionToFormat = value => `${value}`; const nullState = new Map(); const initialState = new Map({ value: 50, }); export default { title: 'Slider', }; export const Default = () => ( <div style={{ padding: '0 1.2rem' }}> <div style={delimiterStyle}> <p style={paragraphStyle}>default</p> <Slider id="slider1" initialState={initialState} /> </div> <div style={delimiterStyle}> <p style={paragraphStyle}>with some icons</p> <Slider id="slider2" captionIcons={icons} initialState={nullState} /> </div> <div style={delimiterStyle}> <p style={paragraphStyle}>with some actions icons</p> <Slider id="slider3" captionActions={actions} initialState={initialState} /> </div> <div style={delimiterStyle}> <p style={paragraphStyle}>with step number</p> <Slider id="slider4" initialState={initialState} captionsFormat={functionToFormat} captionTextStepNumber={5} /> </div> </div> );
docs/app/Examples/collections/Grid/ResponsiveVariations/GridDoublingExample.js
jamiehill/stardust
import React from 'react' import { Image, Grid } from 'stardust' const { Column } = Grid const image = <Image src='http://semantic-ui.com/images/wireframe/image.png' /> const GridDoublingExample = () => ( <Grid doubling columns={5}> <Column>{image}</Column> <Column>{image}</Column> <Column>{image}</Column> <Column>{image}</Column> <Column>{image}</Column> </Grid> ) export default GridDoublingExample
test/lib/backbone.js
matghaleb/Backbone-relational
// Backbone.js 1.2.1 // (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(factory) { // Establish the root object, `window` (`self`) in the browser, or `global` on the server. // 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); // Set up Backbone appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'exports'], function(_, $, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.Backbone = factory(root, exports, _, $); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'), $; try { $ = require('jquery'); } catch(e) {} factory(root, exports, _, $); // Finally, as a browser global. } else { root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } }(function(root, Backbone, _, $) { // Initial Setup // ------------- // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create a local reference to a common array method we'll want to use later. var slice = [].slice; // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.2.1'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... this will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Proxy Underscore methods to a Backbone class' prototype using a // particular attribute as the data argument var addMethod = function(length, method, attribute) { switch (length) { case 1: return function() { return _[method](this[attribute]); }; case 2: return function(value) { return _[method](this[attribute], value); }; case 3: return function(iteratee, context) { return _[method](this[attribute], iteratee, context); }; case 4: return function(iteratee, defaultVal, context) { return _[method](this[attribute], iteratee, defaultVal, context); }; default: return function() { var args = slice.call(arguments); args.unshift(this[attribute]); return _[method].apply(_, args); }; } }; var addUnderscoreMethods = function(Class, methods, attribute) { _.each(methods, function(length, method) { if (_[method]) Class.prototype[method] = addMethod(length, method, attribute); }); }; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = {}; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Iterates over the standard `event, callback` (as well as the fancy multiple // space-separated events `"change blur", callback` and jQuery-style event // maps `{event: callback}`), reducing them by manipulating `memo`. // Passes a normalized single event name and callback, as well as any // optional `opts`. var eventsApi = function(iteratee, memo, name, callback, opts) { var i = 0, names; if (name && typeof name === 'object') { // Handle event maps. if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback; for (names = _.keys(name); i < names.length ; i++) { memo = iteratee(memo, names[i], name[names[i]], opts); } } else if (name && eventSplitter.test(name)) { // Handle space separated event names. for (names = name.split(eventSplitter); i < names.length; i++) { memo = iteratee(memo, names[i], callback, opts); } } else { memo = iteratee(memo, name, callback, opts); } return memo; }; // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. Events.on = function(name, callback, context) { return internalOn(this, name, callback, context); }; // An internal use `on` function, used to guard the `listening` argument from // the public API. var internalOn = function(obj, name, callback, context, listening) { obj._events = eventsApi(onApi, obj._events || {}, name, callback, { context: context, ctx: obj, listening: listening }); if (listening) { var listeners = obj._listeners || (obj._listeners = {}); listeners[listening.id] = listening; } return obj; }; // Inversion-of-control versions of `on`. Tell *this* object to listen to // an event in another object... keeping track of what it's listening to. Events.listenTo = function(obj, name, callback) { if (!obj) return this; var id = obj._listenId || (obj._listenId = _.uniqueId('l')); var listeningTo = this._listeningTo || (this._listeningTo = {}); var listening = listeningTo[id]; // This object is not listening to any other events on `obj` yet. // Setup the necessary references to track the listening callbacks. if (!listening) { var thisId = this._listenId || (this._listenId = _.uniqueId('l')); listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0}; } // Bind callbacks on obj, and keep track of them on listening. internalOn(obj, name, callback, this, listening); return this; }; // The reducing API that adds a callback to the `events` object. var onApi = function(events, name, callback, options) { if (callback) { var handlers = events[name] || (events[name] = []); var context = options.context, ctx = options.ctx, listening = options.listening; if (listening) listening.count++; handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening }); } return events; }; // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. Events.off = function(name, callback, context) { if (!this._events) return this; this._events = eventsApi(offApi, this._events, name, callback, { context: context, listeners: this._listeners }); return this; }; // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. Events.stopListening = function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var ids = obj ? [obj._listenId] : _.keys(listeningTo); for (var i = 0; i < ids.length; i++) { var listening = listeningTo[ids[i]]; // If listening doesn't exist, this object is not currently // listening to obj. Break out early. if (!listening) break; listening.obj.off(name, callback, this); } if (_.isEmpty(listeningTo)) this._listeningTo = void 0; return this; }; // The reducing API that removes a callback from the `events` object. var offApi = function(events, name, callback, options) { // No events to consider. if (!events) return; var i = 0, listening; var context = options.context, listeners = options.listeners; // Delete all events listeners and "drop" events. if (!name && !callback && !context) { var ids = _.keys(listeners); for (; i < ids.length; i++) { listening = listeners[ids[i]]; delete listeners[listening.id]; delete listening.listeningTo[listening.objId]; } return; } var names = name ? [name] : _.keys(events); for (; i < names.length; i++) { name = names[i]; var handlers = events[name]; // Bail out if there are no events stored. if (!handlers) break; // Replace events if there are any remaining. Otherwise, clean up. var remaining = []; for (var j = 0; j < handlers.length; j++) { var handler = handlers[j]; if ( callback && callback !== handler.callback && callback !== handler.callback._callback || context && context !== handler.context ) { remaining.push(handler); } else { listening = handler.listening; if (listening && --listening.count === 0) { delete listeners[listening.id]; delete listening.listeningTo[listening.objId]; } } } // Update tail event if the list has any events. Otherwise, clean up. if (remaining.length) { events[name] = remaining; } else { delete events[name]; } } if (_.size(events)) return events; }; // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. When multiple events are // passed in using the space-separated syntax, the event will fire once for every // event you passed in, not once for a combination of all events Events.once = function(name, callback, context) { // Map the event into a `{event: once}` object. var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this)); return this.on(events, void 0, context); }; // Inversion-of-control versions of `once`. Events.listenToOnce = function(obj, name, callback) { // Map the event into a `{event: once}` object. var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj)); return this.listenTo(obj, events); }; // Reduces the event callbacks into a map of `{event: onceWrapper}`. // `offer` unbinds the `onceWrapper` after it has been called. var onceMap = function(map, name, callback, offer) { if (callback) { var once = map[name] = _.once(function() { offer(name, once); callback.apply(this, arguments); }); once._callback = callback; } return map; }; // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). Events.trigger = function(name) { if (!this._events) return this; var length = Math.max(0, arguments.length - 1); var args = Array(length); for (var i = 0; i < length; i++) args[i] = arguments[i + 1]; eventsApi(triggerApi, this._events, name, void 0, args); return this; }; // Handles triggering the appropriate event callbacks. var triggerApi = function(objEvents, name, cb, args) { if (objEvents) { var events = objEvents[name]; var allEvents = objEvents.all; if (events && allEvents) allEvents = allEvents.slice(); if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, [name].concat(args)); } return objEvents; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId(this.cidPrefix); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // The prefix is used to create the client id which is used to identify models locally. // You may want to override this if you're experiencing name clashes with model ids. cidPrefix: 'c', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Special-cased proxy to underscore's `_.matches` method. matches: function(attrs) { return !!_.iteratee(attrs, this)(this.attributes); }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. var attrs; if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. var unset = options.unset; var silent = options.silent; var changes = []; var changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } var current = this.attributes; var changed = this.changed; var prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (var attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { changed[attr] = val; } else { delete changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; for (var i = 0; i < changes.length; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { options = this._pending; this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var old = this._changing ? this._previousAttributes : this.attributes; var changed = {}; for (var attr in diff) { var val = diff[attr]; if (_.isEqual(old[attr], val)) continue; changed[attr] = val; } return _.size(changed) ? changed : false; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server, merging the response with the model's // local attributes. Any changed attributes will trigger a "change" event. fetch: function(options) { options = _.extend({parse: true}, options); var model = this; var success = options.success; options.success = function(resp) { var serverAttrs = options.parse ? model.parse(resp, options) : resp; if (!model.set(serverAttrs, options)) return false; if (success) success.call(options.context, model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { // Handle both `"key", value` and `{key: value}` -style arguments. var attrs; if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true, parse: true}, options); var wait = options.wait; // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !wait) { if (!this.set(attrs, options)) return false; } else { if (!this._validate(attrs, options)) return false; } // After a successful server-side save, the client is (optionally) // updated with the server-side state. var model = this; var success = options.success; var attributes = this.attributes; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = options.parse ? model.parse(resp, options) : resp; if (wait) serverAttrs = _.extend({}, attrs, serverAttrs); if (serverAttrs && !model.set(serverAttrs, options)) return false; if (success) success.call(options.context, model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); // Set temporary attributes if `{wait: true}` to properly find new ids. if (attrs && wait) this.attributes = _.extend({}, attributes, attrs); var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch' && !options.attrs) options.attrs = attrs; var xhr = this.sync(method, this, options); // Restore attributes. this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var wait = options.wait; var destroy = function() { model.stopListening(); model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (wait) destroy(); if (success) success.call(options.context, model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; var xhr = false; if (this.isNew()) { _.defer(options.success); } else { wrapError(this, options); xhr = this.sync('delete', this, options); } if (!wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; var id = this.get(this.idAttribute); return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return !this.has(this.idAttribute); }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.defaults({validate: true}, options)); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0, omit: 0, chain: 1, isEmpty: 1 }; // Mix in each Underscore method as a proxy to `Model#attributes`. addUnderscoreMethods(Model, modelMethods, 'attributes'); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analogous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model) { return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { options = _.extend({}, options); var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); var removed = this._removeModels(models, options); if (!options.silent && removed) this.trigger('update', this, options); return singular ? removed[0] : removed; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults({}, options, setOptions); if (options.parse && !this._isModel(models)) models = this.parse(models, options); var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : models.slice(); var id, model, attrs, existing, sort; var at = options.at; if (at != null) at = +at; if (at < 0) at += this.length + 1; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; var orderChanged = false; // Turn bare objects into model references, and prevent invalid models // from being added. for (var i = 0; i < models.length; i++) { attrs = models[i]; // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(attrs)) { if (remove) modelMap[existing.cid] = true; if (merge && attrs !== existing) { attrs = this._isModel(attrs) ? attrs.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); this._addReference(model, options); } // Do not add multiple models with the same `id`. model = existing || model; if (!model) continue; id = this.modelId(model.attributes); if (order && (model.isNew() || !modelMap[id])) { order.push(model); // Check to see if this is actually a new model at this index. orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid; } modelMap[id] = true; } // Remove nonexistent models if appropriate. if (remove) { for (var i = 0; i < this.length; i++) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this._removeModels(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length || orderChanged) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { for (var i = 0; i < toAdd.length; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else { if (order) this.models.length = 0; var orderedModels = order || toAdd; for (var i = 0; i < orderedModels.length; i++) { this.models.push(orderedModels[i]); } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort events. if (!options.silent) { var addOpts = at != null ? _.clone(options) : options; for (var i = 0; i < toAdd.length; i++) { if (at != null) addOpts.index = at + i; (model = toAdd[i]).trigger('add', model, this, addOpts); } if (sort || orderChanged) this.trigger('sort', this, options); if (toAdd.length || toRemove.length) this.trigger('update', this, options); } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options = options ? _.clone(options) : {}; for (var i = 0; i < this.models.length; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); return this.remove(model, options); }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); return this.remove(model, options); }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; var id = this.modelId(this._isModel(obj) ? obj.attributes : obj); return this._byId[obj] || this._byId[id] || this._byId[obj.cid]; }, // Get the model at the given index. at: function(index) { if (index < 0) index += this.length; return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { var matches = _.matches(attrs); return this[first ? 'find' : 'filter'](function(model) { return matches(model.attributes); }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = _.extend({parse: true}, options); var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success.call(options.context, collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; var wait = options.wait; model = this._prepareModel(model, options); if (!model) return false; if (!wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(model, resp, callbackOpts) { if (wait) collection.add(model, callbackOpts); if (success) success.call(callbackOpts.context, model, resp, callbackOpts); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models, { model: this.model, comparator: this.comparator }); }, // Define how to uniquely identify models in the collection. modelId: function (attrs) { return attrs[this.model.prototype.idAttribute || 'id']; }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (this._isModel(attrs)) { if (!attrs.collection) attrs.collection = this; return attrs; } options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method called by both remove and set. // Returns removed models, or false if nothing is removed. _removeModels: function(models, options) { var removed = []; for (var i = 0; i < models.length; i++) { var model = this.get(models[i]); if (!model) continue; var index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } removed.push(model); this._removeReference(model, options); } return removed.length ? removed : false; }, // Method for checking whether an object should be considered a model for // the purposes of adding to the collection. _isModel: function (model) { return model instanceof Model; }, // Internal method to create a model's ties to a collection. _addReference: function(model, options) { this._byId[model.cid] = model; var id = this.modelId(model.attributes); if (id != null) this._byId[id] = model; model.on('all', this._onModelEvent, this); }, // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { delete this._byId[model.cid]; var id = this.modelId(model.attributes); if (id != null) delete this._byId[id]; if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (event === 'change') { var prevId = this.modelId(model.previousAttributes()); var id = this.modelId(model.attributes); if (prevId !== id) { if (prevId != null) delete this._byId[prevId]; if (id != null) this._byId[id] = model; } } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4, foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3, select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 2, contains: 2, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, isEmpty: 1, chain: 1, sample: 3, partition: 3 }; // Mix in each Underscore method as a proxy to `Collection#models`. addUnderscoreMethods(Collection, collectionMethods, 'models'); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { if (!_[method]) return; Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this._removeElement(); this.stopListening(); return this; }, // Remove this view's element from the document and all event listeners // attached to it. Exposed for subclasses using an alternative DOM // manipulation API. _removeElement: function() { this.$el.remove(); }, // Change the view's element (`this.el` property) and re-delegate the // view's events on the new element. setElement: function(element) { this.undelegateEvents(); this._setElement(element); this.delegateEvents(); return this; }, // Creates the `this.el` and `this.$el` references for this view using the // given `el`. `el` can be a CSS selector or an HTML string, a jQuery // context or an element. Subclasses can override this to utilize an // alternative DOM manipulation API and are only required to set the // `this.el` property. _setElement: function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. delegateEvents: function(events) { events || (events = _.result(this, 'events')); if (!events) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[method]; if (!method) continue; var match = key.match(delegateEventSplitter); this.delegate(match[1], match[2], _.bind(method, this)); } return this; }, // Add a single event listener to the view's element (or a child element // using `selector`). This only works for delegate-able events: not `focus`, // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer. delegate: function(eventName, selector, listener) { this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener); return this; }, // Clears all callbacks previously bound to the view by `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { if (this.$el) this.$el.off('.delegateEvents' + this.cid); return this; }, // A finer-grained `undelegateEvents` for removing a single delegated event. // `selector` and `listener` are both optional. undelegate: function(eventName, selector, listener) { this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener); return this; }, // Produces a DOM element to be assigned to your view. Exposed for // subclasses using an alternative DOM manipulation API. _createElement: function(tagName) { return document.createElement(tagName); }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); this.setElement(this._createElement(_.result(this, 'tagName'))); this._setAttributes(attrs); } else { this.setElement(_.result(this, 'el')); } }, // Set attributes from a hash on this view's element. Exposed for // subclasses using an alternative DOM manipulation API. _setAttributes: function(attributes) { this.$el.attr(attributes); } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // Pass along `textStatus` and `errorThrown` from jQuery. var error = options.error; options.error = function(xhr, textStatus, errorThrown) { options.textStatus = textStatus; options.errorThrown = errorThrown; if (error) error.call(options.context, xhr, textStatus, errorThrown); }; // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); } }); return this; }, // Execute a route handler with the provided parameters. This is an // excellent place to do pre-route setup or post-route cleanup. execute: function(callback, args, name) { if (callback) callback.apply(this, args); }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^/?]+)'; }) .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param, i) { // Don't decode the search params. if (i === params.length - 1) return param || null; return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for stripping urls of hash. var pathStripper = /#.*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Are we at the app root? atRoot: function() { var path = this.location.pathname.replace(/[^\/]$/, '$&/'); return path === this.root && !this.getSearch(); }, // Does the pathname match the root? matchRoot: function() { var path = this.decodeFragment(this.location.pathname); var root = path.slice(0, this.root.length - 1) + '/'; return root === this.root; }, // Unicode characters in `location.pathname` are percent encoded so they're // decoded for comparison. `%25` should not be decoded since it may be part // of an encoded parameter. decodeFragment: function(fragment) { return decodeURI(fragment.replace(/%25/g, '%2525')); }, // In IE6, the hash fragment and search params are incorrect if the // fragment contains `?`. getSearch: function() { var match = this.location.href.replace(/#.*/, '').match(/\?.+/); return match ? match[0] : ''; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the pathname and search params, without the root. getPath: function() { var path = this.decodeFragment( this.location.pathname + this.getSearch() ).slice(this.root.length - 1); return path.charAt(0) === '/' ? path.slice(1) : path; }, // Get the cross-browser normalized URL fragment from the path or hash. getFragment: function(fragment) { if (fragment == null) { if (this._usePushState || !this._wantsHashChange) { fragment = this.getPath(); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error('Backbone.history has already been started'); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._hasHashChange = 'onhashchange' in window; this._useHashChange = this._wantsHashChange && this._hasHashChange; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.history && this.history.pushState); this._usePushState = this._wantsPushState && this._hasPushState; this.fragment = this.getFragment(); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); // Transition from hashChange to pushState or vice versa if both are // requested. if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { var root = this.root.slice(0, -1) || '/'; this.location.replace(root + '#' + this.getPath()); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._hasPushState && this.atRoot()) { this.navigate(this.getHash(), {replace: true}); } } // Proxy an iframe to handle location events if the browser doesn't // support the `hashchange` event, HTML5 history, or the user wants // `hashChange` but not `pushState`. if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { this.iframe = document.createElement('iframe'); this.iframe.src = 'javascript:0'; this.iframe.style.display = 'none'; this.iframe.tabIndex = -1; var body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready. var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; iWindow.document.open(); iWindow.document.close(); iWindow.location.hash = '#' + this.fragment; } // Add a cross-platform `addEventListener` shim for older browsers. var addEventListener = window.addEventListener || function (eventName, listener) { return attachEvent('on' + eventName, listener); }; // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._usePushState) { addEventListener('popstate', this.checkUrl, false); } else if (this._useHashChange && !this.iframe) { addEventListener('hashchange', this.checkUrl, false); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { // Add a cross-platform `removeEventListener` shim for older browsers. var removeEventListener = window.removeEventListener || function (eventName, listener) { return detachEvent('on' + eventName, listener); }; // Remove window listeners. if (this._usePushState) { removeEventListener('popstate', this.checkUrl, false); } else if (this._useHashChange && !this.iframe) { removeEventListener('hashchange', this.checkUrl, false); } // Clean up the iframe if necessary. if (this.iframe) { document.body.removeChild(this.iframe); this.iframe = null; } // Some environments will throw when clearing an undefined interval. if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); // If the user pressed the back button, the iframe's hash will have // changed and we should use that for comparison. if (current === this.fragment && this.iframe) { current = this.getHash(this.iframe.contentWindow); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragment) { // If the root doesn't match, no routes can match either. if (!this.matchRoot()) return false; fragment = this.fragment = this.getFragment(fragment); return _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options}; // Normalize the fragment. fragment = this.getFragment(fragment || ''); // Don't include a trailing slash on the root. var root = this.root; if (fragment === '' || fragment.charAt(0) === '?') { root = root.slice(0, -1) || '/'; } var url = root + fragment; // Strip the hash and decode for matching. fragment = this.decodeFragment(fragment.replace(pathStripper, '')); if (this.fragment === fragment) return; this.fragment = fragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._usePushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) { var iWindow = this.iframe.contentWindow; // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if (!options.replace) { iWindow.document.open(); iWindow.document.close(); } this._updateHash(iWindow.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent` constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error.call(options.context, model, resp, options); model.trigger('error', model, resp, options); }; }; return Backbone; }));
.storybook/config.js
Bandwidth/shared-components
import { configure } from '@storybook/react'; import './global.css'; import '../fonts/fonts.css'; import { addDecorator } from '@storybook/react'; import React from 'react'; import BandwidthProvider from 'components/BandwidthProvider'; import { Router } from 'react-router'; import { createMemoryHistory } from 'history'; const history = createMemoryHistory('/'); // pull in provider, see https://github.com/storybooks/storybook/issues/1844 addDecorator(getStory => <BandwidthProvider>{getStory()}</BandwidthProvider>); addDecorator(getStory => <Router history={history}>{getStory()}</Router>); function loadStories() { require('../stories/index.js'); } configure(require.context('../stories', false, /index\.js/), module);
server/sonar-web/src/main/js/apps/quality-profiles/changelog/__tests__/ChangesList-test.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { shallow } from 'enzyme'; import React from 'react'; import ChangesList from '../ChangesList'; import SeverityChange from '../SeverityChange'; import ParameterChange from '../ParameterChange'; it('should render changes', () => { const changes = { severity: 'BLOCKER', foo: 'bar' }; const output = shallow(<ChangesList changes={changes} />); expect(output.find('li').length).toBe(2); }); it('should render severity change', () => { const changes = { severity: 'BLOCKER' }; const output = shallow(<ChangesList changes={changes} />).find(SeverityChange); expect(output.length).toBe(1); expect(output.prop('severity')).toBe('BLOCKER'); }); it('should render parameter change', () => { const changes = { foo: 'bar' }; const output = shallow(<ChangesList changes={changes} />).find(ParameterChange); expect(output.length).toBe(1); expect(output.prop('name')).toBe('foo'); expect(output.prop('value')).toBe('bar'); });
packages/material-ui-icons/src/NotificationsOffRounded.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="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zM18 11c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68c-.24.06-.47.15-.69.23L18 13.1V11z" /><path d="M5.41 3.35L4 4.76l2.81 2.81C6.29 8.57 6 9.73 6 11v5l-1.29 1.29c-.63.63-.19 1.71.7 1.71h12.83l1.74 1.74 1.41-1.41L5.41 3.35z" /></g></React.Fragment> , 'NotificationsOffRounded');
test/components/Test.js
loggur/react-redux-provide-history
import React from 'react'; import PropTypes from 'prop-types'; import Title from './Title'; const Test = () => ( <Title /> ); export default Test;
public/assets/plugins/bootstrap3-editable/js/bootstrap-editable.js
AEGEE/oms-neo-core
/*! X-editable - v1.5.1 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); //prerender: get input.$input this.input.prerender(); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value; this.input.value2input(value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = (''+msg).split('\n'); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); //get new value from input var newValue = this.input.input2value(); //validation: if validate returns string or truthy value - means error //if returns object like {newValue: '...'} => submitted value is reassigned to it var error = this.validate(newValue); if ($.type(error) === 'object' && error.newValue !== undefined) { newValue = error.newValue; this.input.value2input(newValue); if(typeof error.msg === 'string') { this.error(error.msg); this.showForm(); return; } } else if (error) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Value that will be displayed in input if original field value is empty (`null|undefined|''`). @property defaultValue @type string|object @default null @since 1.4.6 **/ defaultValue: null, /** Strategy for sending data on server. Can be `auto|always|never`. When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. Since 1.5.1 you can modify submitted value by returning object from `validate`: `{newValue: '...'}` or `{newValue: '...', msg: '...'}` @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; //engine $.fn.editableform.engine = 'jquery'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } if (typeof(valueProp) !== "function") { var idKey = valueProp || 'value'; valueProp = function (e) { return e[idKey]; }; } var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) { result.push(o); } } else { var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o; if(value == itemValue) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //method to call container on element containerDataName: null, //object name in element's .data() innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element defaults: {}, //container itself defaults init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks if(this.input.type === 'textarea') { this.$element.addClass('editable-pre-wrapped'); } //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty //for some inputs we need more smart check //e.g. wysihtml5 may have <br>, <p></p>, <img> if(typeof(this.input.isEmpty) === 'function') { this.isEmpty = this.input.isEmpty(this.$element); } else { this.isEmpty = $.trim(this.$element.html()) === ''; } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ if(bgColor === 'transparent') { bgColor = ''; } $e.css('background-color', bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 10); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case `url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'); // validation ok if($.isEmptyObject(errors)) { var ajaxOptions = {}; // for single element use url, success etc from options if($elems.length === 1) { var editable = $elems.data('editable'); //standard params var params = { name: editable.options.name || '', value: editable.input.value2submit(editable.value), pk: (typeof editable.options.pk === 'function') ? editable.options.pk.call(editable.options.scope) : editable.options.pk }; //additional params if(typeof editable.options.params === 'function') { params = editable.options.params.call(editable.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true); $.extend(params, editable.options.params); } ajaxOptions = { url: editable.options.url, data: params, type: 'POST' }; // use success / error from options config.success = config.success || editable.options.success; config.error = config.error || editable.options.error; // multiple elements } else { var values = this.editable('getValue'); ajaxOptions = { url: config.url, data: values, type: 'POST' }; } // ajax success callabck (response 200 OK) ajaxOptions.success = typeof config.success === 'function' ? function(response) { config.success.call($elems, response, config); } : $.noop; // ajax error callabck ajaxOptions.error = typeof config.error === 'function' ? function() { config.error.apply($elems, arguments); } : $.noop; // extend ajaxOptions if(config.ajaxOptions) { $.extend(ajaxOptions, config.ajaxOptions); } // extra data if(config.data) { $.extend(ajaxOptions.data, config.data); } // perform ajax request $.ajax(ajaxOptions); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; //for delegated targets do not store `editable` object for element //it's allows several different selectors. //see: https://github.com/vitalets/x-editable/issues/312 if(options && options.selector) { data = new Editable(this, options); return; } if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element)[this.options.escape ? 'text' : 'html']($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default null **/ inputclass: null, /** If `true` - html will be escaped in content of element via $.text() method. If `false` - html will not be escaped, $.html() used. When you use own `display` function, this option obviosly has no effect. @property escape @type boolean @since 1.5.0 @default true **/ escape: true, //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //ajaxOptions for source. Can be overwritten bt options.sourceOptions var ajaxOptions = $.extend({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }, this.options.sourceOptions); //loading sourceData from server $.ajax(ajaxOptions); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true, /** Additional ajax options to be used in $.ajax() when loading list from server. Useful to send extra parameters (`data` key) or change request method (`type` key). @property sourceOptions @type object|function @default null @since 1.5.0 **/ sourceOptions: null }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, //using `white-space: pre-wrap` solves \n <--> BR conversion very elegant! /* value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, */ activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { var attr; if($.isArray(data)) { for(var i=0; i<data.length; i++) { attr = {}; if(data[i].children) { attr.label = data[i].text; $el.append(fillItems($('<optgroup>', attr), data[i].children)); } else { attr.value = data[i].value; if(data[i].disabled) { attr.disabled = true; } $el.append($('<option>', attr).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } //$(element).text(text); $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData), escape = this.options.escape; if(checked.length) { $.each(checked, function(i, v) { var text = escape ? $.fn.editableutils.escape(v.text) : v.text; html.push(text); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range * time Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /* Time */ (function ($) { "use strict"; var Time = function (options) { this.init('time', options, Time.defaults); }; //inherit from abstract, as inheritance from text gives selection error. $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput); $.extend(Time.prototype, { render: function() { this.setClass(); } }); Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<input type="time">' }); $.fn.editabletypes.time = Time; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ //local source $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); //remote source (simple) $('#country').editable({ source: '/getCountries', select2: { placeholder: 'Select Country', minimumInputLength: 1 } }); //remote source (advanced) $('#country').editable({ select2: { placeholder: 'Select Country', allowClear: true, minimumInputLength: 3, id: function (item) { return item.CountryId; }, ajax: { url: '/getCountries', dataType: 'json', data: function (term, page) { return { query: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (item) { return item.CountryName; }, formatSelection: function (item) { return item.CountryName; }, initSelection: function (element, callback) { return $.get('/getCountryById', { query: element.val() }, function (data) { callback(data); }); } } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); //store function returning ID of item //should be here as used inautotext for local source this.idFunc = this.options.select2.id; if (typeof(this.idFunc) !== "function") { var idKey = this.idFunc || 'id'; this.idFunc = function (e) { return e[idKey]; }; } //store function that renders text in select2 this.formatSelection = this.options.select2.formatSelection; if (typeof(this.formatSelection) !== "function") { this.formatSelection = function (e) { return e.text; }; } }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //can not apply select2 here as it calls initSelection //over input that does not have correct value yet. //apply select2 only in value2input //this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data, that = this; if(this.options.select2.tags) { //in tags mode just assign value data = value; //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc); } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); } else { //can not get list of possible values //(e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? that.formatSelection(v) : v); }); } else if(data) { text = that.formatSelection(data); } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { // if value array => join it anyway if($.isArray(value)) { value = value.join(this.getSeparator()); } //for remote source just set value, text is updated by initSelection if(!this.$input.data('select2')) { this.$input.val(value); this.$input.select2(this.options.select2); } else { //second argument needed to separate initial change from user's click (for autosubmit) this.$input.val(value).trigger('change', true); //Uncaught Error: cannot call val() if initSelection() is not defined //this.$input.select2('val', value); } // if defined remote source AND no multiple mode AND no user's initSelection provided --> // we should somehow get text for provided id. // The solution is to use element's text as text for that id (exclude empty) if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) { // customId and customText are methods to extract `id` and `text` from data object // we can use this workaround only if user did not define these methods // otherwise we cant construct data object var customId = this.options.select2.id, customText = this.options.select2.formatSelection; if(!customId && !customText) { var $el = $(this.options.scope); if (!$el.data('editable').isEmpty) { var data = {id: value, text: $el.text()}; this.$input.select2('data', data); } } } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.getSeparator(); var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, getSeparator: function() { return this.options.select2.separator || $.fn.select2.defaults.separator; }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; }, destroy: function() { if(this.$input.data('select2')) { this.$input.select2('destroy'); } } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array|string|function @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.5 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(e) { this.$element.val(this.getValue()).change(); // update days count if month or year changes if (this.options.smartDays) { if ($(e.target).is('.month') || $(e.target).is('.year')) { this.fillCombo('day'); } } }, this)); this.$widget.find('select').css('width', 'auto'); // hide original input and insert widget this.$element.hide().after(this.$widget); // set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { for (var k in this.map) { var $c = this.$widget.find('.'+k); // set properties like this.$day, this.$month etc. this['$'+k] = $c.length ? $c : null; // fill with items this.fillCombo(k); } }, /* Fill combo with items */ fillCombo: function(k) { var $combo = this['$'+k]; if (!$combo) { return; } // define method name to fill items, e.g `fillDays` var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); var items = this[f](); var value = $combo.val(); $combo.empty(); for(var i=0; i<items.length; i++) { $combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } $combo.val(value); }, /* Initialize items of combos. Handles `firstItem` option */ fillCommon: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* fill day */ fillDay: function() { var items = this.fillCommon('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1, daysCount = 31; // detect days count (depends on month and year) // originally https://github.com/vitalets/combodate/pull/7 if (this.options.smartDays && this.$month && this.$year) { var month = parseInt(this.$month.val(), 10); var year = parseInt(this.$year.val(), 10); if (!isNaN(month) && !isNaN(year)) { daysCount = moment([year, month]).daysInMonth(); } } for (i = 1; i <= daysCount; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.fillCommon('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.fillCommon('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.fillCommon('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.fillCommon('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.fillCommon('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); // update days count if (this.options.smartDays) { this.fillCombo('day'); } this.$element.val(dt.format(this.options.format)).change(); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true, // whether to round minutes and seconds if step > 1 smartDays: false // whether days in combo depend on selected month: 31, 30, 28 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); if($.fn.editableform.engine === 'bs3') { this.$input.siblings().find('select').addClass('form-control'); } if(this.options.inputclass) { this.$input.siblings().find('select').addClass(this.options.inputclass); } //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on Twitter Bootstrap 3 */ (function ($) { "use strict"; //store parent methods var pInitInput = $.fn.editableform.Constructor.prototype.initInput; $.extend($.fn.editableform.Constructor.prototype, { initTemplate: function() { this.$form = $($.fn.editableform.template); this.$form.find('.control-group').addClass('form-group'); this.$form.find('.editable-error-block').addClass('help-block'); }, initInput: function() { pInitInput.apply(this); //for bs3 set default class `input-sm` to standard inputs var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false; var defaultClass = 'input-sm'; //bs3 add `form-control` class to standard inputs var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(','); if(~$.inArray(this.input.type, stdtypes)) { this.input.$input.addClass('form-control'); if(emptyInputClass) { this.input.options.inputclass = defaultClass; this.input.$input.addClass(defaultClass); } } //apply bs3 size class also to buttons (to fit size of control) var $btn = this.$form.find('.editable-buttons'); var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' '); for(var i=0; i<classes.length; i++) { // `btn-sm` is default now /* if(classes[i].toLowerCase() === 'input-sm') { $btn.find('button').addClass('btn-sm'); } */ if(classes[i].toLowerCase() === 'input-lg') { $btn.find('button').removeClass('btn-sm').addClass('btn-lg'); } } } }); //buttons $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary btn-sm editable-submit">'+ '<i class="glyphicon glyphicon-ok"></i>'+ '</button>'+ '<button type="button" class="btn btn-default btn-sm editable-cancel">'+ '<i class="glyphicon glyphicon-remove"></i>'+ '</button>'; //error classes $.fn.editableform.errorGroupClass = 'has-error'; $.fn.editableform.errorBlockClass = null; //engine $.fn.editableform.engine = 'bs3'; }(window.jQuery)); /** * Editable Popover3 (for Bootstrap 3) * --------------------- * requires bootstrap-popover.js */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'popover', containerDataName: 'bs.popover', innerCss: '.popover-content', defaults: $.fn.popover.Constructor.DEFAULTS, initContainer: function(){ $.extend(this.containerOptions, { trigger: 'manual', selector: false, content: ' ', template: this.defaults.template }); //as template property is used in inputs, hide it from popover var t; if(this.$element.data('template')) { t = this.$element.data('template'); this.$element.removeData('template'); } this.call(this.containerOptions); if(t) { //restore data('template') this.$element.data('template', t); } }, /* show */ innerShow: function () { this.call('show'); }, /* hide */ innerHide: function () { this.call('hide'); }, /* destroy */ innerDestroy: function() { this.call('destroy'); }, setContainerOption: function(key, value) { this.container().options[key] = value; }, /** * move popover to new position. This function mainly copied from bootstrap-popover. */ /*jshint laxcomma: true, eqeqeq: false*/ setPosition: function () { (function() { /* var $tip = this.tip() , inside , pos , actualWidth , actualHeight , placement , tp , tpt , tpb , tpl , tpr; placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; inside = /in/.test(placement); $tip // .detach() //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover .removeClass('top right bottom left') .css({ top: 0, left: 0, display: 'block' }); // .insertAfter(this.$element); pos = this.getPosition(inside); actualWidth = $tip[0].offsetWidth; actualHeight = $tip[0].offsetHeight; placement = inside ? placement.split(' ')[1] : placement; tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}; tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}; tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}; tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}; switch (placement) { case 'bottom': if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) { if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'top': if (tpt.top < $(window).scrollTop()) { if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) { placement = 'bottom'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'left': if (tpl.left < $(window).scrollLeft()) { if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } else { placement = 'right'; } } break; case 'right': if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) { if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } } break; } switch (placement) { case 'bottom': tp = tpb; break; case 'top': tp = tpt; break; case 'left': tp = tpl; break; case 'right': tp = tpr; break; } $tip .offset(tp) .addClass(placement) .addClass('in'); */ var $tip = this.tip(); var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; var autoToken = /\s?auto?\s?/i; var autoPlace = autoToken.test(placement); if (autoPlace) { placement = placement.replace(autoToken, '') || 'top'; } var pos = this.getPosition(); var actualWidth = $tip[0].offsetWidth; var actualHeight = $tip[0].offsetHeight; if (autoPlace) { var $parent = this.$element.parent(); var orgPlacement = placement; var docScroll = document.documentElement.scrollTop || document.body.scrollTop; var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth(); var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight(); var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left; placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement; $tip .removeClass(orgPlacement) .addClass(placement); } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight); this.applyPlacement(calculatedOffset, placement); }).call(this.container()); /*jshint laxcomma: false, eqeqeq: true*/ } }); }(window.jQuery)); /* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ (function( $ ) { function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function(element, options) { var that = this; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if(this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if(this.isInline) { this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl){ this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this.o.startDate); this.setEndDate(this.o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if(this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function(opts){ // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]) { lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch(o.startView){ case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode) { case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format) if (o.startDate !== -Infinity) { o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } if (o.endDate !== Infinity) { o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } o.daysOfWeekDisabled = o.daysOfWeekDisabled||[]; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); }, _events: [], _secondaryEvents: [], _applyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.on(ev); } }, _unapplyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.off(ev); } }, _buildEvents: function(){ if (this.isInput) { // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { mousedown: $.proxy(function (e) { // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).size() || this.picker.is(e.target) || this.picker.find(e.target).size() )) { this.hide(); } }, this) }] ]; }, _attachEvents: function(){ this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function(){ this._unapplyEvents(this._events); }, _attachSecondaryEvents: function(){ this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function(){ this._unapplyEvents(this._secondaryEvents); }, _trigger: function(event, altdate){ var date = altdate || this.date, local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000)); this.element.trigger({ type: event, date: local_date, format: $.proxy(function(altformat){ var format = altformat || this.o.format; return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function(e) { if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.place(); this._attachSecondaryEvents(); if (e) { e.preventDefault(); } this._trigger('show'); }, hide: function(e){ if(this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function() { this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput) { delete this.element.data().date; } }, getDate: function() { var d = this.getUTCDate(); return new Date(d.getTime() + (d.getTimezoneOffset()*60000)); }, getUTCDate: function() { return this.date; }, setDate: function(d) { this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000))); }, setUTCDate: function(d) { this.date = d; this.setValue(); }, setValue: function() { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component){ this.element.find('input').val(formatted); } } else { this.element.val(formatted); } }, getFormattedDate: function(format) { if (format === undefined) format = this.o.format; return DPGlobal.formatDate(this.date, format, this.o.language); }, setStartDate: function(startDate){ this._process_options({startDate: startDate}); this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this._process_options({endDate: endDate}); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this._process_options({daysOfWeekDisabled: daysOfWeekDisabled}); this.update(); this.updateNavArrows(); }, place: function(){ if(this.isInline) return; var zIndex = parseInt(this.element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true); this.picker.css({ top: offset.top + height, left: offset.left, zIndex: zIndex }); }, _allow_update: true, update: function(){ if (!this._allow_update) return; var date, fromArgs = false; if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); delete this.element.data().date; } this.date = DPGlobal.parseDate(date, this.o.format, this.o.language); if(fromArgs) this.setValue(); if (this.date < this.o.startDate) { this.viewDate = new Date(this.o.startDate); } else if (this.date > this.o.endDate) { this.viewDate = new Date(this.o.endDate); } else { this.viewDate = new Date(this.date); } this.fill(); }, fillDow: function(){ var dowCnt = this.o.weekStart, html = '<tr>'; if(this.o.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7) { html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12) { html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function(range){ if (!range || !range.length) delete this.range; else this.range = $.map(range, function(d){ return d.valueOf(); }); this.fill(); }, getClassNames: function(date){ var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), currentDate = this.date.valueOf(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) { cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) { cls.push('new'); } // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() == today.getFullYear() && date.getUTCMonth() == today.getMonth() && date.getUTCDate() == today.getDate()) { cls.push('today'); } if (currentDate && date.valueOf() == currentDate) { cls.push('active'); } if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) { cls.push('disabled'); } if (this.range){ if (date > this.range[0] && date < this.range[this.range.length-1]){ cls.push('range'); } if ($.inArray(date.valueOf(), this.range) != -1){ cls.push('selected'); } } return cls; }, fill: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(dates[this.o.language].today) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(dates[this.o.language].clear) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28,0,0,0,0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while(prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.o.weekStart) { html.push('<tr>'); if(this.o.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); var before = this.o.beforeShowDay(prevMonth); if (before === undefined) before = {}; else if (typeof(before) === 'boolean') before = {enabled: before}; else if (typeof(before) === 'string') before = {classes: before}; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; clsName = $.unique(clsName); html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.o.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function() { if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e) { e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch(target[0].nodeName.toLowerCase()) { case 'th': switch(target[0].className) { case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch(this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this._trigger('changeDate'); this.update(); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var day = 1; var month = target.parent().find('span').index(target); var year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } else { var year = parseInt(target.text(), 10)||0; var day = 1; var month = 0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ var day = parseInt(target.text(), 10)||1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day,0,0,0,0)); } break; } } }, _setDate: function(date, which){ if (!which || which == 'date') this.date = new Date(date); if (!which || which == 'view') this.viewDate = new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); if (this.o.autoclose && (!which || which == 'date')) { this.hide(); } } }, moveMonth: function(date, dir){ if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1){ test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i<mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch(e.keyCode){ case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged){ this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function(dir) { if (dir) { this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function(element, options){ this.element = $(element); this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function(){ this.dates = $.map(this.pickers, function(i){ return i.date; }); this.updateRanges(); }, updateRanges: function(){ var range = $.map(this.dates, function(d){ return d.valueOf(); }); $.each(this.pickers, function(i, p){ p.setRange(range); }); }, dateUpdated: function(e){ var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i == -1) return; if (new_date < this.dates[i]){ // Date being moved earlier/left while (i>=0 && new_date < this.dates[i]){ this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]){ // Date being moved later/right while (i<l && new_date > this.dates[i]){ this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); }, remove: function(){ $.map(this.pickers, function(p){ p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix){ // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'), prefix = new RegExp('^' + prefix.toLowerCase()); for (var key in data) if (prefix.test(key)){ inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); }); out[inkey] = data[key]; } return out; } function opts_from_locale(lang){ // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]) { lang = lang.split('-')[0] if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function(i,k){ if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; var datepicker = $.fn.datepicker = function ( option ) { var args = Array.apply(null, arguments); args.shift(); var internal_return, this_return; this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs){ var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else{ $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language) { if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i=0; i<parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch(part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ v -= 1; while (v<0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i=0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch(part) { case 'MM': filtered = $(dates[language].months).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i=0, s; i<setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]); } } return date; }, formatDate: function(date, format, language){ if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev"><i class="icon-arrow-left"/></th>'+ '<th colspan="5" class="datepicker-switch"></th>'+ '<th class="next"><i class="icon-arrow-right"/></th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function(e){ var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it datepicker.call($this, 'show'); } ); $(function(){ //$('[data-provide="datepicker-inline"]').datepicker(); //vit: changed to support noConflict() datepicker.call($('[data-provide="datepicker-inline"]')); }); }( window.jQuery )); /** Bootstrap-datepicker. Description and examples: https://github.com/eternicode/bootstrap-datepicker. For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales and set `language` option. Since 1.4.0 date has different appearance in **popup** and **inline** modes. @class date @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one $.fn.bdatepicker = $.fn.datepicker.noConflict(); if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name $.fn.datepicker = $.fn.bdatepicker; } var Date = function (options) { this.init('date', options, Date.defaults); this.initPicker(options, Date.defaults); }; $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput); $.extend(Date.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datepicker config defined as json string in data-datepicker options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true); //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { format: this.options.viewformat }); //language this.options.datepicker.language = this.options.datepicker.language || 'en'; //store DPglobal this.dpg = $.fn.bdatepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat); }, render: function () { this.$input.bdatepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''; Date.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.parseDate(html, this.parsedViewFormat); }, value2str: function(value) { return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : ''; }, str2value: function(str) { return this.parseDate(str, this.parsedFormat); }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.bdatepicker('update', value); }, input2value: function() { return this.$input.data('datepicker').date; }, activate: function() { }, clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.day', function(e){ if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) { return; } var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); //changedate is not suitable as it triggered when showing datepicker. see #149 /* this.$input.on('changeDate', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); */ }, /* For incorrect date bootstrap-datepicker returns current date that is not suitable for datefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datepicker.language); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language); if(str !== formattedBack) { date = null; } } } return date; } }); Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code> @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://bootstrap-datepicker.readthedocs.org/en/latest/options.html @property datepicker @type object @default { weekStart: 0, startView: 0, minViewMode: 0, autoclose: false } **/ datepicker:{ weekStart: 0, startView: 0, minViewMode: 0, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.date = Date; }(window.jQuery)); /** Bootstrap datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class datefield @extends date @since 1.4.0 **/ (function ($) { "use strict"; var DateField = function (options) { this.init('datefield', options, DateField.defaults); this.initPicker(options, DateField.defaults); }; $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date); $.extend(DateField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js) this.$tpl.bdatepicker(this.options.datepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.bdatepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''); this.$tpl.bdatepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-small' **/ inputclass: 'input-small', /* datepicker config */ datepicker: { weekStart: 0, startView: 0, minViewMode: 0, autoclose: true } }); $.fn.editabletypes.datefield = DateField; }(window.jQuery)); /** Bootstrap-datetimepicker. Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). Before usage you should manually include dependent js and css: <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> <script src="js/bootstrap-datetimepicker.js"></script> For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales and set `language` option. @class datetime @extends abstractinput @final @since 1.4.4 @example <a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a> <script> $(function(){ $('#last_seen').editable({ format: 'yyyy-mm-dd hh:ii', viewformat: 'dd/mm/yyyy hh:ii', datetimepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateTime = function (options) { this.init('datetime', options, DateTime.defaults); this.initPicker(options, DateTime.defaults); }; $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput); $.extend(DateTime.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datetimepicker config defined as json string in data-datetimepicker options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true); //overriding datetimepicker config (as by default jQuery extend() is not recursive) //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, { format: this.options.viewformat }); //language this.options.datetimepicker.language = this.options.datetimepicker.language || 'en'; //store DPglobal this.dpg = $.fn.datetimepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType); }, render: function () { this.$input.datetimepicker(this.options.datetimepicker); //adjust container position when viewMode changes //see https://github.com/smalot/bootstrap-datetimepicker/pull/80 this.$input.on('changeMode', function(e) { var f = $(this).closest('form').parent(); //timeout here, otherwise container changes position before form has new size setTimeout(function(){ f.triggerHandler('resize'); }, 0); }); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { //formatDate works with UTCDate! var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : ''; if(element) { DateTime.superclass.value2html.call(this, text, element); } else { return text; } }, html2value: function(html) { //parseDate return utc date! var value = this.parseDate(html, this.parsedViewFormat); return value ? this.fromUTC(value) : null; }, value2str: function(value) { //formatDate works with UTCDate! return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : ''; }, str2value: function(str) { //parseDate return utc date! var value = this.parseDate(str, this.parsedFormat); return value ? this.fromUTC(value) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { if(value) { this.$input.data('datetimepicker').setDate(value); } }, input2value: function() { //date may be cleared, in that case getDate() triggers error var dt = this.$input.data('datetimepicker'); return dt.date ? dt.getDate() : null; }, activate: function() { }, clear: function() { this.$input.data('datetimepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.minute', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); }, //convert date from local to utc toUTC: function(value) { return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value; }, //convert date from utc to local fromUTC: function(value) { return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value; }, /* For incorrect date bootstrap-datetimepicker returns current date that is not suitable for datetimefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType); if(str !== formattedBack) { date = null; } } } return date; } }); DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code> @property format @type string @default yyyy-mm-dd hh:ii **/ format:'yyyy-mm-dd hh:ii', formatType:'standard', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datetimepicker. Full list of options: https://github.com/smalot/bootstrap-datetimepicker @property datetimepicker @type object @default { } **/ datetimepicker:{ todayHighlight: false, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.datetime = DateTime; }(window.jQuery)); /** Bootstrap datetimefield input - datetime input for inline mode. Shows normal <input type="text"> and binds popup datetimepicker. Automatically shown in inline mode. @class datetimefield @extends datetime **/ (function ($) { "use strict"; var DateTimeField = function (options) { this.init('datetimefield', options, DateTimeField.defaults); this.initPicker(options, DateTimeField.defaults); }; $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime); $.extend(DateTimeField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); this.$tpl.datetimepicker(this.options.datetimepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.datetimepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(this.value2html(value)); this.$tpl.datetimepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-medium' **/ inputclass: 'input-medium', /* datetimepicker config */ datetimepicker:{ todayHighlight: false, autoclose: true } }); $.fn.editabletypes.datetimefield = DateTimeField; }(window.jQuery));
packages/material-ui-icons/src/AirplanemodeActive.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment> , 'AirplanemodeActive');
src/svg-icons/device/network-cell.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceNetworkCell = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M2 22h20V2z"/><path d="M17 7L2 22h15z"/> </SvgIcon> ); DeviceNetworkCell = pure(DeviceNetworkCell); DeviceNetworkCell.displayName = 'DeviceNetworkCell'; DeviceNetworkCell.muiName = 'SvgIcon'; export default DeviceNetworkCell;
packages/mui-icons-material/lib/esm/AgricultureRounded.js
oliviertassinari/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M19.5 11.97c.93 0 1.78.28 2.5.76V7.97c0-1.1-.9-2-2-2h-6.29l-1.06-1.06 1.06-1.06c.2-.2.2-.51 0-.71s-.51-.2-.71 0l-2.83 2.83c-.2.2-.2.51 0 .71.2.2.51.2.71 0l1.06-1.06L13 6.68v2.29c0 1.1-.9 2-2 2h-.54c.95 1.06 1.54 2.46 1.54 4 0 .34-.04.67-.09 1h3.14c.25-2.24 2.14-4 4.45-4z" }, "0"), /*#__PURE__*/_jsx("path", { d: "M19.5 12.97c-1.93 0-3.5 1.57-3.5 3.5s1.57 3.5 3.5 3.5 3.5-1.57 3.5-3.5-1.57-3.5-3.5-3.5zm0 5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM4 8.97h5c0-1.1-.9-2-2-2H4c-.55 0-1 .45-1 1 0 .56.45 1 1 1zm5.83 4.82-.18-.47.93-.35c-.46-1.06-1.28-1.91-2.31-2.43l-.4.89-.46-.21.4-.9c-.55-.21-1.17-.35-1.81-.35-.53 0-1.04.11-1.52.26l.34.91-.47.18L4 10.4c-1.06.46-1.91 1.28-2.43 2.31l.89.4-.21.46-.9-.4c-.22.55-.35 1.16-.35 1.8 0 .53.11 1.04.26 1.52l.91-.34.18.47-.93.35c.46 1.06 1.28 1.91 2.31 2.43l.4-.89.46.21-.4.9c.57.22 1.18.35 1.82.35.53 0 1.04-.11 1.52-.26l-.35-.91.47-.18.35.93c1.06-.46 1.91-1.28 2.43-2.31l-.89-.4.21-.46.9.4c.22-.57.35-1.18.35-1.82 0-.53-.11-1.04-.26-1.52l-.91.35zm-2.68 3.96c-1.53.63-3.29-.09-3.92-1.62-.63-1.53.09-3.29 1.62-3.92 1.53-.63 3.29.09 3.92 1.62.64 1.53-.09 3.28-1.62 3.92z" }, "1")], 'AgricultureRounded');
src/styles/withTheme.js
xotahal/react-native-material-ui
import React from 'react'; import hoistNonReactStatics from 'hoist-non-react-statics'; import ThemeContext from './themeContext'; // This function takes a component... const withTheme = WrappedComponent => { // ...and returns another component... class ThemedComponent extends React.PureComponent { render() { return ( <ThemeContext.Consumer> {theme => <WrappedComponent {...this.props} theme={theme} />} </ThemeContext.Consumer> ); } } hoistNonReactStatics(ThemedComponent, WrappedComponent); return ThemedComponent; }; export default withTheme;
src/components/topic/description/index.js
nickhsine/twreporter-react
import PropTypes from 'prop-types' import React from 'react' import renderTopicContent, { Paragraph } from './render-content' import styled from 'styled-components' const Container = styled.div` position: relative; width: 100%; padding-top: 72px; padding-bottom: 40px; ` const Section = styled.div` position: relative; font-size: 18px; width: 38em; max-width: 90%; a { cursor: pointer; border-bottom: 1px #c71b0a solid; transition: 100ms color ease; position: relative; color: #262626; &:hover { color: #c71b0a; } } ` const TopicDescription = styled(Section)` margin: 0 auto; padding-bottom: 40px; /* distacne to red line */ /* horizontal red line */ &::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; width: 200px; margin: auto; border-top: 2px solid #c71b0a; } ` const TeamDescription = styled(Section)` margin: 40px auto 0 auto; font-size: 15px; /* overwrite paragraph styles */ ${Paragraph} { font-size: 15px; color: #808080; margin: 0 auto; } ` const Description = props => { const { topicDescription, teamDescription } = props const topicDescElements = renderTopicContent(topicDescription) const teamDescElements = renderTopicContent(teamDescription) if (topicDescElements.length > 0 || teamDescElements.length > 0) { return ( <Container> {topicDescElements.length > 0 ? ( <TopicDescription>{topicDescElements}</TopicDescription> ) : null} {teamDescElements.length > 0 ? ( <TeamDescription>{teamDescElements}</TeamDescription> ) : null} </Container> ) } return null } Description.propTypes = { topicDescription: PropTypes.array, teamDescription: PropTypes.array, } Description.defaultProps = { topicDescription: [], teamDescription: [], } export default Description
src/components/nav/footer.js
ChrisRast/Le-Taguenet
import React from 'react'; import * as ui from 'semantic-ui-react'; export default function Footer(props) { return ( <ui.Container textAlign="center" > <ui.Divider /> <ui.List horizontal > <ui.List.Item > <ui.List.Icon name="copyright" style={{ marginRight: '.5rem', }} /> 2018 - {new Date().getFullYear()}, Christophe Rast </ui.List.Item> <ui.List.Item > <ui.List.Icon name="code" style={{ marginRight: '.5rem', }} /> <a href="https://github.com/ChrisRast/Le-Taguenet" target="_blank" rel="noopener external nofollow noreferrer"> Code source </a> </ui.List.Item> </ui.List> </ui.Container> ); }
src/svg-icons/image/view-comfy.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageViewComfy = (props) => ( <SvgIcon {...props}> <path d="M3 9h4V5H3v4zm0 5h4v-4H3v4zm5 0h4v-4H8v4zm5 0h4v-4h-4v4zM8 9h4V5H8v4zm5-4v4h4V5h-4zm5 9h4v-4h-4v4zM3 19h4v-4H3v4zm5 0h4v-4H8v4zm5 0h4v-4h-4v4zm5 0h4v-4h-4v4zm0-14v4h4V5h-4z"/> </SvgIcon> ); ImageViewComfy = pure(ImageViewComfy); ImageViewComfy.displayName = 'ImageViewComfy'; ImageViewComfy.muiName = 'SvgIcon'; export default ImageViewComfy;
packages/node_modules/@webex/react-component-spark-logo/src/index.js
adamweeks/react-ciscospark-1
import React from 'react'; import classNames from 'classnames'; import styles from './styles.css'; export default function SparkLogo() { return ( <div className={classNames('webex-spark-logo', styles.logo)} /> ); }
packages/material-ui-icons/src/ExpandMoreRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M24 24H0V0h24v24z" opacity=".87" /><path d="M15.88 9.29L12 13.17 8.12 9.29a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0z" /></React.Fragment> , 'ExpandMoreRounded');
packages/material-ui-icons/src/DeveloperMode.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let DeveloperMode = props => <SvgIcon {...props}> <path d="M7 5h10v2h2V3c0-1.1-.9-1.99-2-1.99L7 1c-1.1 0-2 .9-2 2v4h2V5zm8.41 11.59L20 12l-4.59-4.59L14 8.83 17.17 12 14 15.17l1.41 1.42zM10 15.17L6.83 12 10 8.83 8.59 7.41 4 12l4.59 4.59L10 15.17zM17 19H7v-2H5v4c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-4h-2v2z" /> </SvgIcon>; DeveloperMode = pure(DeveloperMode); DeveloperMode.muiName = 'SvgIcon'; export default DeveloperMode;
packages/plutarch/tpls/redux-project/src/routes/router.prod.js
Alfred-sg/plutarch
import React from 'react' import PropTypes from 'prop-types' import { Provider } from 'react-redux' import { Route, Redirect } from 'react-router-dom' import App from './app' import Demo from './demo' const Root = ({ store }) => ( <Provider store={store}> <App> <Route path="/" render={() => (<Redirect to="/demo" />)} /> <Route path="/demo" component={Demo} /> </App> </Provider> ) Root.propTypes = { store: PropTypes.object.isRequired, } export default Root
_tests_/index.js
joropeza/react-fullscreen-app-boilerplate
import React from 'react'; import reactDom from 'react-dom/server'; import { expect } from 'chai'; import dom from 'cheerio'; import componentToTest from '../src/your-code-goes-here/components/content/homePageContent'; const render = reactDom.renderToStaticMarkup; describe('(sample functional component tests)', function() { describe('(homePageContent)', function() { it('should render some stuff', function() { const props = {}; const Component = componentToTest(props); const $ = dom.load(render(Component)); const output = $('div').html(); expect(output).to.be.ok; }); }); });
ajax/libs/yui/3.10.2/event-custom-base/event-custom-base.js
masahirotanaka/cdnjs
YUI.add('event-custom-base', function (Y, NAME) { /** * 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 * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <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 (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; 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(); } } }; 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; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * 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} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * 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 */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * 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 */ /** * 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 event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * 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; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default 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 */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * 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 */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * 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 */ 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 */ bubbles : true, /** * 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 = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } 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 = nativeSlice.call(arguments, 0); 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 sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * 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) { mixConfigs(this, o, force); }, /** * 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) { 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) { if (!this._afters) { this._afters = []; this._hasAfters = true; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; this._hasSubs = true; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } 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) ? nativeSlice.call(arguments, 2) : 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) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { 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) ? nativeSlice.call(arguments, 2) : 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 = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); 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) { var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { 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) { }, /** * 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() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { 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()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { 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, l; for (i = 0, l = subs.length; i < l; 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 = args.concat(); 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 s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); if (subs.length === 0) { if (when === AFTER) { this._hasAfters = false; } else { this._hasSubs = false; } } } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { 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, when) { /** * 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.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * 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 && 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); } }, valueOf : function() { return this.id; } }; /** * 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~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$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 = function(type, pre) { if (!pre || 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 etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; 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 yuievt = this._yuievt, parts = _parseType(type, 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 = nativeSlice.call(arguments, 0); 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 (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 = nativeSlice.call(arguments, 0); 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 = nativeSlice.call(arguments, 0); 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 = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (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 = nativeSlice.call(arguments, 0); 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 = nativeSlice.call(arguments, 0); // 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 ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * 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 eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.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 = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (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); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } 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 = nativeSlice.call(arguments, 0); 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"]});
client/containers/users/email-enrollment-form.js
ShannChiang/USzhejiang
import React from 'react'; import {useDeps} from 'react-simple-di'; import {composeAll, withTracker} from 'react-komposer-plus'; import EmailEnrollmentForm from '../../components/users/email-enrollment-form'; function composer({context}, onData) { onData(null, { loggingIn: context.Meteor.loggingIn(), loggedIn: !!context.Meteor.user() }); } const depsToProps = (context, actions) => ({ context, enrollWithEmail: actions.users.enrollWithEmail }); export default composeAll( withTracker(composer), useDeps(depsToProps)) (EmailEnrollmentForm);
src/components/file/download.js
abbr/ShowPreper
import React from 'react' import { langs } from 'i18n/lang' import _ from 'lodash' module.exports = class Exporter extends React.Component { render() { let blob = new Blob([JSON.stringify(this.props.deck, null, 2)], { type: 'application/json' }) let blobURL = window.URL.createObjectURL(blob) return ( <div id="sp-open-download" className="modal fade" tabIndex="-1" role="dialog" > <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> <h4 className="modal-title"> {langs[this.props.language].download} </h4> </div> <div className="modal-body"> <ul className="nav nav-tabs" role="tablist"> <li role="presentation" className="active"> <a href="#sp-project" aria-controls="project" role="tab" data-toggle="tab" > {langs[this.props.language].project} </a> </li> <li role="presentation"> <a href="#sp-presentation" aria-controls="presentation" role="tab" data-toggle="tab" > {langs[this.props.language].presentation} </a> </li> </ul> <div className="tab-content"> <div role="tabpanel" className="tab-pane fade in active" id="sp-project" > <div className="alert alert-info"> {langs[this.props.language].downloadProjectFileExplain} </div> <div className="alert alert-success"> <a href={blobURL} download={ this.props.deck._fn + (this.props.deck._fn.endsWith('.spj') ? '' : '.spj') } > {langs[this.props.language].download}{' '} {this.props.deck._fn} </a> </div> </div> <div role="tabpanel" className="tab-pane fade" id="sp-presentation" > <div className="alert alert-info"> {langs[this.props.language].downloadRenderedPresentation} <ol> <li>{langs[this.props.language].closeThisDialog}</li> <li> <span dangerouslySetInnerHTML={{ __html: langs[ this.props.language ].clickRenderButton.replace( '{BTN}', `<a type="button" class="btn btn-success"> <span class="glyphicon glyphicon-play" /> <div>${langs[this.props.language][ this.props.presentationFormat ] || _.capitalize(this.props.presentationFormat)}</div> </a>` ) }} /> </li> <li> <span dangerouslySetInnerHTML={{ __html: langs[this.props.language].pressCtrlSToSave .replace('{CtrlS}', '<code>Ctrl+S</code>') .replace('{CmdS}', '<code>⌘+S</code>') }} /> </li> </ol> </div> </div> </div> </div> <div className="modal-footer"> <button type="button" className="btn btn-default" data-dismiss="modal" > {langs[this.props.language].btnClose} </button> </div> </div> </div> </div> ) } }
client/app/scripts/utils/metric-utils.js
kinvolk/scope
import { includes } from 'lodash'; import { scaleLog } from 'd3-scale'; import React from 'react'; import { formatMetricSvg } from './string-utils'; import { colors } from './color-utils'; export function getClipPathDefinition(clipId, height, radius) { const barHeight = 1 - (2 * height); // in the interval [-1, 1] return ( <defs> <clipPath id={clipId} transform={`scale(${2 * radius})`}> <rect width={2} height={2} x={-1} y={barHeight} /> </clipPath> </defs> ); } // // loadScale(1) == 0.5; E.g. a nicely balanced system :). const loadScale = scaleLog().domain([0.01, 100]).range([0, 1]); export function getMetricValue(metric) { if (!metric) { return {height: 0, value: null, formattedValue: 'n/a'}; } const m = metric.toJS(); const { value } = m; let valuePercentage = value === 0 ? 0 : value / m.max; let { max } = m; if (includes(['load1', 'load5', 'load15'], m.id)) { valuePercentage = loadScale(value); max = null; } let displayedValue = Number(value).toFixed(1); if (displayedValue > 0 && (!max || displayedValue < max)) { const baseline = 0.1; displayedValue = (valuePercentage * (1 - (baseline * 2))) + baseline; } else if (displayedValue >= m.max && displayedValue > 0) { displayedValue = 1; } return { height: displayedValue, hasMetric: value !== null, formattedValue: formatMetricSvg(value, m) }; } export function getMetricColor(metric) { const metricId = typeof metric === 'string' ? metric : metric && metric.get('id'); if (/mem/.test(metricId)) { return 'steelBlue'; } else if (/cpu/.test(metricId)) { return colors('cpu').toString(); } else if (/files/.test(metricId)) { // purple return '#9467bd'; } else if (/load/.test(metricId)) { return colors('load').toString(); } return 'steelBlue'; }
lib/index.js
NikBorn/Weatherly
import React from 'react'; import ReactDOM from 'react-dom'; import Weather from './Weather'; ReactDOM.render(<Weather/>, document.getElementById('application'));
definitions/npm/react-library-paginator_v2.x.x/flow_v0.25.x-v0.103.x/test_react-library-paginator_v2.x.x.js
flowtype/flow-typed
// @flow import { describe, it } from 'flow-typed-test'; import React from 'react'; import PaginatorContainer from 'react-library-paginator'; describe('PaginatorContainer ', () => { const handlePageChange = (page: number) => {}; it('should accept all props', () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} currentPage={1} itemsPerPage={4} maxPagesToShow={4} useBootstrapClasses={true} styles={{}} classes={{}} navigation={{}} />; }); it('should fail with incompatible types', () => { // $FlowExpectedError <PaginatorContainer totalItems={'777'} onPageChange={(str: string) => {}} currentPage={{}} itemsPerPage={true} />; }); it("shouldn't fail with only required props", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} />; }); it('should fail when some required props are missing', () => { // $FlowExpectedError <PaginatorContainer onPageChange={handlePageChange} />; // $FlowExpectedError <PaginatorContainer totalItems={10} />; }); // test 'classes' props it("should accept all fields in 'classes' prop of type PaginatorClasses", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} classes={{ container: 'paginator-container', list: 'paginator-list', pageItem: 'paginator-item', pageLink: 'paginator-link', pageLinkActive: 'paginator-link--active', pageLinkDisabled: 'paginator-link--disabled' }} />; }); it("should fail when passing non-object value as 'classes' prop", () => { // $FlowExpectedError <PaginatorContainer totalItems={10} onPageChange={handlePageChange} classes={'paginator-container'} />; }); it("should allow skip fields in 'classes' prop", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} classes={{ container: 'paginator-container', pageLink: 'paginator-link', pageLinkDisabled: 'paginator-link--disabled' }} />; }); it("should fail when passing non-string values in 'classes' prop", () => { // $FlowExpectedError <PaginatorContainer totalItems={10} onPageChange={handlePageChange} classes={{ container: { test: 1 }, pageLink: 'paginator-link', pageLinkDisabled: 'paginator-link--disabled' }} />; }); // test 'styles' props it("should accept all fields in 'styles' prop of type PaginatorStyles", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} styles={{ container: { padding: '10px 0' }, list: { marginBottom: 0, padding: 0 }, pageItem: { padding: '5px 0' }, pageLink: { padding: '8px 13px', color: '#285e28' }, pageLinkActive: { backgroundColor: '#b1d1be' }, pageLinkDisabled: { color: 'gray' } }} />; }); it("should fail when passing non-object value as 'styles' prop", () => { // $FlowExpectedError <PaginatorContainer totalItems={10} onPageChange={handlePageChange} classes={'paginator-container-styles'} />; }); it("should allow skip fields in 'styles' prop", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} styles={{ list: { marginBottom: 0, padding: 0 }, pageLink: { padding: '8px 13px', color: '#285e28' }, pageLinkActive: { backgroundColor: '#b1d1be' }, pageItem: { padding: '5px 0' } }} />; }); it("should fail when passing non-object values in 'styles' prop", () => { // $FlowExpectedError <PaginatorContainer totalItems={10} onPageChange={handlePageChange} styles={{ container: 'border-bottom: 1px solid #ccc;', pageLinkActive: { backgroundColor: '#b1d1be' }, pageItem: { padding: '5px 0' } }} />; }); // tets 'navigation' prop it("should accept all fields in 'navigation' prop of type Navigation", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} navigation={{ firstPageText: 'fffirst', prevPageText: 'back!', nextPageText: 'forward!', lastPageText: 'lllast', hideFirstPageNav: false, hidePrevPageNav: false, hideNextPageNav: true, hideLastPageNav: true }} />; }); it("should fail when passing non-object value as 'navigation' prop", () => { // $FlowExpectedError <PaginatorContainer totalItems={10} onPageChange={handlePageChange} navigation={'paginator-navigation-config'} />; }); it("should allow skip fields in 'navigation' prop", () => { <PaginatorContainer totalItems={10} onPageChange={handlePageChange} navigation={{ firstPageText: 'fffirst', prevPageText: 'back!', hideNextPageNav: true, hideLastPageNav: true }} />; }); it("should fail when passing values of incorrect types in 'navigation' prop", () => { // $FlowExpectedError <PaginatorContainer totalItems={10} onPageChange={handlePageChange} navigation={{ firstPageText: {}, prevPageText: 'back!', hideLastPageNav: 120 }} />; }); });
src/index.js
pawelgalazka/spaceroom
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
client/components/Box.js
yuanyusi/redux
import React from 'react'; const url = 'http://localhost:8080/api/goals'; class Box extends React.Component { constructor(props){ super(props); this.handleDelete = this.handleDelete.bind(this); this.handleSuccesses = this.handleSuccesses.bind(this); this.handleFailures = this.handleFailures.bind(this); var uid = this.props.emp._links.self.href.slice(0, 100).split('goals/'); this.id = uid[1]; } handleDelete(e){ e.preventDefault(); this.props.removeGoal(url, this.id, this.props.i); } handleSuccesses(e){ e.preventDefault(); this.props.successesGoal(url, this.id, this.props.i); } handleFailures(e){ e.preventDefault(); this.props.failuresGoal(url, this.id, this.props.i); } render() { var emp = this.props.emp; var d = emp.createdAt.slice(0, 10).split('-'); var formatDate = d[1] +'/'+ d[2] +'/'+ d[0]; // 10/30/2010 return ( <ul className="goals-list content-grid mdl-grid"> <li id="1" className="mdl-card mdl-cell mdl-shadow--2dp"> <div className="mdl-card__title mdl-color--light-blue-700 mdl-color-text--white"> <h2> <div className="mdl-card__title-text">{emp.description}</div> <div className="mdl-card__subtitle-text"><span className="successes">{emp.successes.length}</span> successes, <span className="failures">{emp.failures.length}</span> failures</div> </h2> </div> <div className="mdl-layout-spacer"></div> <div className="mdl-card__supporting-text"> Since {formatDate} </div> <div className="mdl-card__actions mdl-card--border"> <button className="mdl-button mdl-js-button mdl-button--primary success" onClick={this.handleSuccesses}><i className="material-icons">trending_up</i></button> <button className="mdl-button mdl-js-button mdl-button--primary failure" onClick={this.handleFailures}><i className="material-icons">trending_down</i></button> <div className="mdl-layout-spacer"></div> <button className="mdl-button mdl-js-button mdl-button--colored" onClick={this.handleDelete}><i className="material-icons">delete</i></button> </div> </li> </ul> ) } }; export default Box;
tests/components/LikeButton.spec.js
eugenrein/voteshirt
import React from 'react'; import { shallow } from 'enzyme'; import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import Button from '../../src/components/Button'; import LikeButton from '../../src/components/LikeButton'; chai.should(); chai.use(sinonChai); describe('<LikeButton />', () => { it('should contain <Button />', () => { const props = { onClick: sinon.spy() }; const wrapper = shallow(<LikeButton {...props} />); expect(wrapper.find(Button)).to.be.length(1); }); it('should handle click', () => { const props = { onClick: sinon.spy() }; const wrapper = shallow(<LikeButton {...props} />); props.onClick.should.not.have.been.called; wrapper.simulate('click'); expect(props.onClick).to.have.been.called; }); it('should have a <Button /> with name \'thumb_up\'', () => { const props = { onClick: sinon.spy() }; const wrapper = shallow(<LikeButton {...props} />); const actual = wrapper.find(Button).prop('name'); const expected = 'thumb_up'; expect(actual).to.equal(expected); }); });
src/components/Main.js
fernandojsg/aframe-inspector
/* global VERSION BUILD_TIMESTAMP COMMIT_HASH webFont */ require('../lib/vendor/ga'); const INSPECTOR = require('../lib/inspector.js'); import React from 'react'; import ReactDOM from 'react-dom'; THREE.ImageUtils.crossOrigin = ''; const Events = require('../lib/Events.js'); import ComponentsSidebar from './components/Sidebar'; import ModalTextures from './modals/ModalTextures'; import ModalHelp from './modals/ModalHelp'; import SceneGraph from './scenegraph/SceneGraph'; import ToolBar from './ToolBar'; import {injectCSS, injectJS} from '../lib/utils'; import '../css/main.css'; // Megahack to include font-awesome. injectCSS('https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'); injectCSS('https://fonts.googleapis.com/css?family=Roboto:400,300,500'); export default class Main extends React.Component { constructor (props) { super(props); this.state = { entity: null, inspectorEnabled: true, isMotionCaptureRecording: false, isModalTexturesOpen: false, motionCaptureCountdown: -1, sceneEl: AFRAME.scenes[0], visible: { scenegraph: true, attributes: true } }; Events.on('togglesidebar', event => { if (event.which === 'all') { if (this.state.visible.scenegraph || this.state.visible.attributes) { this.setState({ visible: { scenegraph: false, attributes: false } }); } else { this.setState({ visible: { scenegraph: true, attributes: true } }); } } else if (event.which === 'attributes') { this.setState((prevState) => ({ visible: { attributes: !prevState.visible.attributes } })); } else if (event.which === 'scenegraph') { this.setState((prevState) => ({ visible: { scenegraph: !prevState.visible.scenegraph } })); } this.forceUpdate(); }); } componentDidMount () { // Create an observer to notify the changes in the scene var observer = new MutationObserver(function (mutations) { Events.emit('dommodified', mutations); }); var config = {attributes: true, childList: true, characterData: true}; observer.observe(this.state.sceneEl, config); Events.on('opentexturesmodal', function (selectedTexture, textureOnClose) { this.setState({selectedTexture: selectedTexture, isModalTexturesOpen: true, textureOnClose: textureOnClose}); }.bind(this)); Events.on('entityselected', entity => { this.setState({entity: entity}); }); Events.on('inspectormodechanged', enabled => { this.setState({inspectorEnabled: enabled}); }); Events.on('openhelpmodal', () => { this.setState({isHelpOpen: true}); }); Events.on('motioncapturerecordstart', () => { this.setState({isMotionCaptureRecording: true}); }); Events.on('motioncapturerecordstop', () => { this.setState({isMotionCaptureRecording: false}); }); Events.on('motioncapturecountdown', val => { this.setState({motionCaptureCountdown: val}); }); } onCloseHelpModal = value => { this.setState({isHelpOpen: false}); } onModalTextureOnClose = value => { this.setState({isModalTexturesOpen: false}); if (this.state.textureOnClose) { this.state.textureOnClose(value); } } /* openModal = () => { this.setState({isModalTexturesOpen: true}); } */ toggleEdit = () => { if (this.state.inspectorEnabled) { INSPECTOR.close(); } else { INSPECTOR.open(); } } render () { var scene = this.state.sceneEl; const showScenegraph = this.state.visible.scenegraph ? null : <div className="toggle-sidebar left"><a onClick={() => { this.setState({visible: {scenegraph: true}}); this.forceUpdate(); }} className='fa fa-plus' title='Show scenegraph'></a></div>; const showAttributes = !this.state.entity || this.state.visible.attributes ? null : <div className="toggle-sidebar right"><a onClick={() => { this.setState({visible: {attributes: true}}); this.forceUpdate(); }} className='fa fa-plus' title='Show components'></a></div>; let toggleButtonText = 'Inspect Scene'; if (this.state.motionCaptureCountdown !== -1) { toggleButtonText = this.state.motionCaptureCountdown; } else if (this.state.isMotionCaptureRecording) { toggleButtonText = 'Stop Recording'; } else if (this.state.inspectorEnabled) { toggleButtonText = 'Back to Scene'; } return ( <div> <a className='toggle-edit' onClick={this.toggleEdit}>{toggleButtonText}</a> <div id='aframe-inspector-panels' className={this.state.inspectorEnabled ? '' : 'hidden'}> <ModalTextures ref='modaltextures' isOpen={this.state.isModalTexturesOpen} selectedTexture={this.state.selectedTexture} onClose={this.onModalTextureOnClose}/> <SceneGraph id='left-sidebar' scene={scene} selectedEntity={this.state.entity} visible={this.state.visible.scenegraph}/> {showScenegraph} {showAttributes} <div id='right-panels'> <ToolBar/> <ComponentsSidebar entity={this.state.entity} visible={this.state.visible.attributes}/> </div> </div> <ModalHelp isOpen={this.state.isHelpOpen} onClose={this.onCloseHelpModal}/> </div> ); } } (function init () { injectJS('https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js', function () { var webFontLoader = document.createElement('script'); webFontLoader.setAttribute('data-aframe-inspector', 'webfont'); webFontLoader.innerHTML = 'WebFont.load({google: {families: ["Roboto", "Roboto Mono"]}});'; document.head.appendChild(webFontLoader); }, function () { console.warn('Could not load WebFont script:', webFont.src); // webFont or webFontLoader? }); var div = document.createElement('div'); div.id = 'aframe-inspector'; div.setAttribute('data-aframe-inspector', 'app'); document.body.appendChild(div); window.addEventListener('inspector-loaded', function () { ReactDOM.render(<Main/>, div); }); console.log('A-Frame Inspector Version:', VERSION, '(' + BUILD_TIMESTAMP + ' Commit: ' + COMMIT_HASH.substr(0, 7) + ')'); })();
src/containers/List/Page.js
LifeSourceUA/lifesource.ua
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { asyncConnect } from 'redux-connect'; import Helmet from 'react-helmet'; import * as Common from 'components/Common'; import Meta from './Meta'; @asyncConnect( [], ({ browser }) => { return { browser }; } ) /* eslint-disable react/prefer-stateless-function */ class ListPage extends Component { static propTypes = { browser: PropTypes.object.isRequired }; render = () => { return ( <div> <Helmet { ...Meta() }/> <Common.List type={ 'magazines4' }/> </div> ); } } export default ListPage;
src/icons/LocalHotelIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class LocalHotelIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M14 26c3.31 0 6-2.69 6-6s-2.69-6-6-6-6 2.69-6 6 2.69 6 6 6zm24-12H22v14H6V10H2v30h4v-6h36v6h4V22c0-4.42-3.58-8-8-8z"/></svg>;} };
ajax/libs/survey-react/0.12.19/survey.react.min.js
dakshshah96/cdnjs
/*! * surveyjs - Survey JavaScript library v0.12.19 * Copyright (c) 2015-2017 Devsoft Baltic OÜ - http://surveyjs.org/ * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define("Survey",["react"],t):"object"==typeof exports?exports.Survey=t(require("react")):e.Survey=t(e.React)}(this,function(e){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},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=86)}([function(e,t,n){"use strict";function r(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}n.d(t,"a",function(){return i}),t.b=r,n.d(t,"c",function(){return o});var i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},o=function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s}},function(e,t,n){"use strict";n.d(t,"a",function(){return r}),n.d(t,"b",function(){return i});var r={currentLocale:"",defaultLocale:"en",locales:{},supportedLocales:[],getString:function(e){var t=this.currentLocale?this.locales[this.currentLocale]:this.locales[this.defaultLocale];return t&&t[e]||(t=this.locales[this.defaultLocale]),t[e]},getLocales:function(){var e=[];if(e.push(""),this.supportedLocales&&this.supportedLocales.length>0)for(var t=0;t<this.supportedLocales.length;t++)e.push(this.supportedLocales[t]);else for(var n in this.locales)e.push(n);return e.sort(),e}},i={pagePrevText:"Previous",pageNextText:"Next",completeText:"Complete",otherItemText:"Other (describe)",progressText:"Page {0} of {1}",emptySurvey:"There is no visible page or question in the survey.",completingSurvey:"Thank you for completing the survey!",loadingSurvey:"Survey is loading...",optionsCaption:"Choose...",requiredError:"Please answer the question.",requiredInAllRowsError:"Please answer questions in all rows.",numericError:"The value should be numeric.",textMinLength:"Please enter at least {0} symbols.",textMaxLength:"Please enter less than {0} symbols.",textMinMaxLength:"Please enter more than {0} and less than {1} symbols.",minRowCountError:"Please fill in at least {0} rows.",minSelectError:"Please select at least {0} variants.",maxSelectError:"Please select no more than {0} variants.",numericMinMax:"The '{0}' should be equal or more than {1} and equal or less than {2}",numericMin:"The '{0}' should be equal or more than {1}",numericMax:"The '{0}' should be equal or less than {1}",invalidEmail:"Please enter a valid e-mail address.",urlRequestError:"The request returned error '{0}'. {1}",urlGetChoicesError:"The request returned empty data or the 'path' property is incorrect",exceedMaxSize:"The file size should not exceed {0}.",otherRequiredError:"Please enter the other value.",uploadingFile:"Your file is uploading. Please wait several seconds and try again.",addRow:"Add row",removeRow:"Remove",choices_Item:"item",matrix_column:"Column",matrix_row:"Row",savingData:"The results are saving on the server...",savingDataError:"An error occurred and we could not save the results.",savingDataSuccess:"The results were saved successfully!",saveAgainButton:"Try again"};r.locales.en=i,String.prototype.format||(String.prototype.format=function(){var e=arguments;return this.replace(/{(\d+)}/g,function(t,n){return void 0!==e[n]?e[n]:t})})},function(e,t,n){"use strict";var r=n(0);n.d(t,"h",function(){return i}),n.d(t,"e",function(){return o}),n.d(t,"d",function(){return s}),n.d(t,"b",function(){return a}),n.d(t,"j",function(){return u}),n.d(t,"g",function(){return l}),n.d(t,"f",function(){return c}),n.d(t,"c",function(){return h}),n.d(t,"i",function(){return p}),n.d(t,"a",function(){return d});var i=function(){function e(e){this.name=e,this.typeValue=null,this.choicesValue=null,this.choicesfunc=null,this.className=null,this.alternativeName=null,this.classNamePart=null,this.baseClassName=null,this.defaultValue=null,this.readOnly=!1,this.visible=!0,this.isLocalizable=!1,this.serializationProperty=null,this.onGetValue=null}return Object.defineProperty(e.prototype,"type",{get:function(){return this.typeValue?this.typeValue:"string"},set:function(e){this.typeValue=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasToUseGetValue",{get:function(){return this.onGetValue||this.serializationProperty},enumerable:!0,configurable:!0}),e.prototype.isDefaultValue=function(e){return this.defaultValue?this.defaultValue==e:!e},e.prototype.getValue=function(e){return this.onGetValue?this.onGetValue(e):this.serializationProperty?e[this.serializationProperty].getJson():e[this.name]},e.prototype.getPropertyValue=function(e){return this.isLocalizable?e[this.serializationProperty].text:this.getValue(e)},Object.defineProperty(e.prototype,"hasToUseSetValue",{get:function(){return this.onSetValue||this.serializationProperty},enumerable:!0,configurable:!0}),e.prototype.setValue=function(e,t,n){this.onSetValue?this.onSetValue(e,t,n):this.serializationProperty?e[this.serializationProperty].setJson(t):(t&&"string"==typeof t&&("number"==this.type&&(t=parseInt(t)),"boolean"==this.type&&(t="true"===t.toLowerCase())),e[this.name]=t)},e.prototype.getObjType=function(e){return this.classNamePart?e.replace(this.classNamePart,""):e},e.prototype.getClassName=function(e){return this.classNamePart&&e.indexOf(this.classNamePart)<0?e+this.classNamePart:e},Object.defineProperty(e.prototype,"choices",{get:function(){return null!=this.choicesValue?this.choicesValue:null!=this.choicesfunc?this.choicesfunc():null},enumerable:!0,configurable:!0}),e.prototype.setChoices=function(e,t){this.choicesValue=e,this.choicesfunc=t},e}(),o=function(){function e(e,t,n,r){void 0===n&&(n=null),void 0===r&&(r=null),this.name=e,this.creator=n,this.parentName=r,this.properties=null,this.requiredProperties=null,this.properties=new Array;for(var i=0;i<t.length;i++){var o=this.createProperty(t[i]);o&&this.properties.push(o)}}return e.prototype.find=function(e){for(var t=0;t<this.properties.length;t++)if(this.properties[t].name==e)return this.properties[t];return null},e.prototype.createProperty=function(t){var n="string"==typeof t?t:t.name;if(n){var r=null,o=n.indexOf(e.typeSymbol);o>-1&&(r=n.substring(o+1),n=n.substring(0,o)),n=this.getPropertyName(n);var s=new i(n);if(r&&(s.type=r),"object"==typeof t){if(t.type&&(s.type=t.type),t.default&&(s.defaultValue=t.default),!1===t.visible&&(s.visible=!1),t.isRequired&&this.makePropertyRequired(s.name),t.choices){var a="function"==typeof t.choices?t.choices:null,u="function"!=typeof t.choices?t.choices:null;s.setChoices(u,a)}if(t.onGetValue&&(s.onGetValue=t.onGetValue),t.onSetValue&&(s.onSetValue=t.onSetValue),t.serializationProperty){s.serializationProperty=t.serializationProperty;s.serializationProperty&&0==s.serializationProperty.indexOf("loc")&&(s.isLocalizable=!0)}t.isLocalizable&&(s.isLocalizable=t.isLocalizable),t.className&&(s.className=t.className),t.baseClassName&&(s.baseClassName=t.baseClassName),t.classNamePart&&(s.classNamePart=t.classNamePart),t.alternativeName&&(s.alternativeName=t.alternativeName)}return s}},e.prototype.getPropertyName=function(t){return 0==t.length||t[0]!=e.requiredSymbol?t:(t=t.slice(1),this.makePropertyRequired(t),t)},e.prototype.makePropertyRequired=function(e){this.requiredProperties||(this.requiredProperties=new Array),this.requiredProperties.push(e)},e}();o.requiredSymbol="!",o.typeSymbol=":";var s=function(){function e(){this.classes={},this.childrenClasses={},this.classProperties={},this.classRequiredProperties={}}return e.prototype.addClass=function(e,t,n,r){void 0===n&&(n=null),void 0===r&&(r=null);var i=new o(e,t,n,r);if(this.classes[e]=i,r){this.childrenClasses[r]||(this.childrenClasses[r]=[]),this.childrenClasses[r].push(i)}return i},e.prototype.overrideClassCreatore=function(e,t){var n=this.findClass(e);n&&(n.creator=t)},e.prototype.getProperties=function(e){var t=this.classProperties[e];return t||(t=new Array,this.fillProperties(e,t),this.classProperties[e]=t),t},e.prototype.findProperty=function(e,t){for(var n=this.getProperties(e),r=0;r<n.length;r++)if(n[r].name==t)return n[r];return null},e.prototype.createClass=function(e){var t=this.findClass(e);return t?t.creator():null},e.prototype.getChildrenClasses=function(e,t){void 0===t&&(t=!1);var n=[];return this.fillChildrenClasses(e,t,n),n},e.prototype.getRequiredProperties=function(e){var t=this.classRequiredProperties[e];return t||(t=new Array,this.fillRequiredProperties(e,t),this.classRequiredProperties[e]=t),t},e.prototype.addProperty=function(e,t){var n=this.findClass(e);if(n){var r=n.createProperty(t);r&&(this.addPropertyToClass(n,r),this.emptyClassPropertiesHash(n))}},e.prototype.removeProperty=function(e,t){var n=this.findClass(e);if(!n)return!1;var r=n.find(t);r&&(this.removePropertyFromClass(n,r),this.emptyClassPropertiesHash(n))},e.prototype.addPropertyToClass=function(e,t){null==e.find(t.name)&&e.properties.push(t)},e.prototype.removePropertyFromClass=function(e,t){var n=e.properties.indexOf(t);n<0||(e.properties.splice(n,1),e.requiredProperties&&(n=e.requiredProperties.indexOf(t.name))>=0&&e.requiredProperties.splice(n,1))},e.prototype.emptyClassPropertiesHash=function(e){this.classProperties[e.name]=null;for(var t=this.getChildrenClasses(e.name),n=0;n<t.length;n++)this.classProperties[t[n].name]=null},e.prototype.fillChildrenClasses=function(e,t,n){var r=this.childrenClasses[e];if(r)for(var i=0;i<r.length;i++)t&&!r[i].creator||n.push(r[i]),this.fillChildrenClasses(r[i].name,t,n)},e.prototype.findClass=function(e){return this.classes[e]},e.prototype.fillProperties=function(e,t){var n=this.findClass(e);if(n){n.parentName&&this.fillProperties(n.parentName,t);for(var r=0;r<n.properties.length;r++)this.addPropertyCore(n.properties[r],t,t.length)}},e.prototype.addPropertyCore=function(e,t,n){for(var r=-1,i=0;i<n;i++)if(t[i].name==e.name){r=i;break}r<0?t.push(e):t[r]=e},e.prototype.fillRequiredProperties=function(e,t){var n=this.findClass(e);n&&(n.requiredProperties&&Array.prototype.push.apply(t,n.requiredProperties),n.parentName&&this.fillRequiredProperties(n.parentName,t))},e}(),a=function(){function e(e,t){this.type=e,this.message=t,this.description="",this.at=-1}return e.prototype.getFullDescription=function(){return this.message+(this.description?"\n"+this.description:"")},e}(),u=function(e){function t(t,n){var r=e.call(this,"unknownproperty","The property '"+t+"' in class '"+n+"' is unknown.")||this;r.propertyName=t,r.className=n;var i=d.metaData.getProperties(n);if(i){r.description="The list of available properties are: ";for(var o=0;o<i.length;o++)o>0&&(r.description+=", "),r.description+=i[o].name;r.description+="."}return r}return r.b(t,e),t}(a),l=function(e){function t(t,n,r){var i=e.call(this,n,r)||this;i.baseClassName=t,i.type=n,i.message=r,i.description="The following types are available: ";for(var o=d.metaData.getChildrenClasses(t,!0),s=0;s<o.length;s++)s>0&&(i.description+=", "),i.description+="'"+o[s].name+"'";return i.description+=".",i}return r.b(t,e),t}(a),c=function(e){function t(t,n){var r=e.call(this,n,"missingtypeproperty","The property type is missing in the object. Please take a look at property: '"+t+"'.")||this;return r.propertyName=t,r.baseClassName=n,r}return r.b(t,e),t}(l),h=function(e){function t(t,n){var r=e.call(this,n,"incorrecttypeproperty","The property type is incorrect in the object. Please take a look at property: '"+t+"'.")||this;return r.propertyName=t,r.baseClassName=n,r}return r.b(t,e),t}(l),p=function(e){function t(t,n){var r=e.call(this,"requiredproperty","The property '"+t+"' is required in class '"+n+"'.")||this;return r.propertyName=t,r.className=n,r}return r.b(t,e),t}(a),d=function(){function e(){this.errors=new Array}return Object.defineProperty(e,"metaData",{get:function(){return e.metaDataValue},enumerable:!0,configurable:!0}),e.prototype.toJsonObject=function(e){return this.toJsonObjectCore(e,null)},e.prototype.toObject=function(t,n){if(t){var r=null;if(n.getType&&(r=e.metaData.getProperties(n.getType())),r)for(var i in t)if(i!=e.typePropertyName)if(i!=e.positionPropertyName){var o=this.findProperty(r,i);o?this.valueToObj(t[i],n,i,o):this.addNewError(new u(i.toString(),n.getType()),t)}else n[i]=t[i]}},e.prototype.toJsonObjectCore=function(t,n){if(!t.getType)return t;var r={};null==n||n.className||(r[e.typePropertyName]=n.getObjType(t.getType()));for(var i=e.metaData.getProperties(t.getType()),o=0;o<i.length;o++)this.valueToJson(t,r,i[o]);return r},e.prototype.valueToJson=function(e,t,n){var r=n.getValue(e);if(void 0!==r&&null!==r&&!n.isDefaultValue(r)){if(this.isValueArray(r)){for(var i=[],o=0;o<r.length;o++)i.push(this.toJsonObjectCore(r[o],n));r=i.length>0?i:null}else r=this.toJsonObjectCore(r,n);n.isDefaultValue(r)||(t[n.name]=r)}},e.prototype.valueToObj=function(e,t,n,r){if(null!=e){if(null!=r&&r.hasToUseSetValue)return void r.setValue(t,e,this);if(this.isValueArray(e))return void this.valueToArray(e,t,r.name,r);var i=this.createNewObj(e,r);i.newObj&&(this.toObject(e,i.newObj),e=i.newObj),i.error||(null!=r?r.setValue(t,e,this):t[r.name]=e)}},e.prototype.isValueArray=function(e){return e&&Array.isArray(e)},e.prototype.createNewObj=function(t,n){var r={newObj:null,error:null},i=t[e.typePropertyName];return!i&&null!=n&&n.className&&(i=n.className),i=n.getClassName(i),r.newObj=i?e.metaData.createClass(i):null,r.error=this.checkNewObjectOnErrors(r.newObj,t,n,i),r},e.prototype.checkNewObjectOnErrors=function(t,n,r,i){var o=null;if(t){var s=e.metaData.getRequiredProperties(i);if(s)for(var a=0;a<s.length;a++)if(!n[s[a]]){o=new p(s[a],i);break}}else r.baseClassName&&(o=i?new h(r.name,r.baseClassName):new c(r.name,r.baseClassName));return o&&this.addNewError(o,n),o},e.prototype.addNewError=function(t,n){n&&n[e.positionPropertyName]&&(t.at=n[e.positionPropertyName].start),this.errors.push(t)},e.prototype.valueToArray=function(e,t,n,r){t[n]&&e.length>0&&t[n].splice(0,t[n].length);for(var i=0;i<e.length;i++){var o=this.createNewObj(e[i],r);o.newObj?(t[n].push(o.newObj),this.toObject(e[i],o.newObj)):o.error||t[n].push(e[i])}},e.prototype.findProperty=function(e,t){if(!e)return null;for(var n=0;n<e.length;n++){var r=e[n];if(r.name==t||r.alternativeName==t)return r}return null},e}();d.typePropertyName="type",d.positionPropertyName="pos",d.metaDataValue=new s},function(t,n){t.exports=e},function(e,t,n){"use strict";var r=n(0),i=n(3);n.n(i);n.d(t,"a",function(){return o}),n.d(t,"c",function(){return s}),n.d(t,"b",function(){return a});var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isDisplayMode=t.isDisplayMode||!1,n}return r.b(t,e),t.renderLocString=function(e,t){if(void 0===t&&(t=null),e.hasHtml){var n={__html:e.renderedHtml};return i.createElement("span",{style:t,dangerouslySetInnerHTML:n})}return i.createElement("span",{style:t},e.renderedHtml)},t.prototype.componentWillReceiveProps=function(e){this.isDisplayMode=e.isDisplayMode||!1},t.prototype.renderLocString=function(e,n){return void 0===n&&(n=null),t.renderLocString(e,n)},t}(i.Component),s=function(e){function t(t){var n=e.call(this,t)||this;return n.cssClasses=t.cssClasses,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.cssClasses=t.cssClasses},t}(o),a=function(e){function t(t){var n=e.call(this,t)||this;return n.questionBase=t.question,n.creator=t.creator,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.questionBase=t.question,this.creator=t.creator},t.prototype.shouldComponentUpdate=function(){return!this.questionBase.customWidget||!!this.questionBase.customWidgetData.isNeedRender||!!this.questionBase.customWidget.widgetJson.render},t}(o)},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(){this.creatorHash={}}return e.prototype.registerQuestion=function(e,t){this.creatorHash[e]=t},e.prototype.getAllTypes=function(){var e=new Array;for(var t in this.creatorHash)e.push(t);return e.sort()},e.prototype.createQuestion=function(e,t){var n=this.creatorHash[e];return null==n?null:n(t)},e}();r.Instance=new r},function(e,t,n){"use strict";n.d(t,"b",function(){return i}),n.d(t,"d",function(){return o}),n.d(t,"e",function(){return r}),n.d(t,"a",function(){return s}),n.d(t,"c",function(){return a});var r,i=function(){function e(){}return e.isValueEmpty=function(e){return!(!Array.isArray(e)||0!==e.length)||(e&&("string"==typeof e||e instanceof String)&&(e=e.trim()),!e&&0!==e&&!1!==e)},e.prototype.getType=function(){throw new Error("This method is abstract")},e.prototype.isTwoValueEquals=function(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;for(var n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(e[n]!==t[n]){if("object"!=typeof e[n])return!1;if(!this.isTwoValueEquals(e[n],t[n]))return!1}}for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0},e}(),o=function(){function e(){}return e.prototype.getText=function(){throw new Error("This method is abstract")},e}();r="sq_page";var s=function(){function e(){}return e.ScrollElementToTop=function(e){if(!e)return!1;var t=document.getElementById(e);if(!t||!t.scrollIntoView)return!1;var n=t.getBoundingClientRect().top;return n<0&&t.scrollIntoView(),n<0},e.GetFirstNonTextElement=function(e){if(e&&e.length){for(var t=0;t<e.length;t++)if("#text"!=e[t].nodeName&&"#comment"!=e[t].nodeName)return e[t];return null}},e.FocusElement=function(e){if(!e)return!1;var t=document.getElementById(e);return!!t&&(t.focus(),!0)},e}(),a=function(){function e(){}return Object.defineProperty(e.prototype,"isEmpty",{get:function(){return null==this.callbacks||0==this.callbacks.length},enumerable:!0,configurable:!0}),e.prototype.fire=function(e,t){if(null!=this.callbacks)for(var n=0;n<this.callbacks.length;n++){this.callbacks[n](e,t)}},e.prototype.add=function(e){null==this.callbacks&&(this.callbacks=new Array),this.callbacks.push(e)},e.prototype.remove=function(e){if(null!=this.callbacks){var t=this.callbacks.indexOf(e,0);void 0!=t&&this.callbacks.splice(t,1)}},e}()},function(e,t,n){"use strict";var r=n(1);n.d(t,"a",function(){return i}),n.d(t,"b",function(){return o});var i=function(){function e(){this.creatorHash={}}return Object.defineProperty(e,"DefaultChoices",{get:function(){return[r.a.getString("choices_Item")+"1",r.a.getString("choices_Item")+"2",r.a.getString("choices_Item")+"3"]},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultColums",{get:function(){var e=r.a.getString("matrix_column")+" ";return[e+"1",e+"2",e+"3"]},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultRows",{get:function(){var e=r.a.getString("matrix_row")+" ";return[e+"1",e+"2"]},enumerable:!0,configurable:!0}),e.prototype.registerQuestion=function(e,t){this.creatorHash[e]=t},e.prototype.clear=function(){this.creatorHash={}},e.prototype.getAllTypes=function(){var e=new Array;for(var t in this.creatorHash)e.push(t);return e.sort()},e.prototype.createQuestion=function(e,t){var n=this.creatorHash[e];return null==n?null:n(t)},e}();i.Instance=new i;var o=function(){function e(){this.creatorHash={}}return e.prototype.registerElement=function(e,t){this.creatorHash[e]=t},e.prototype.clear=function(){this.creatorHash={}},e.prototype.getAllTypes=function(){var e=i.Instance.getAllTypes();for(var t in this.creatorHash)e.push(t);return e.sort()},e.prototype.createElement=function(e,t){var n=this.creatorHash[e];return null==n?i.Instance.createQuestion(e,t):n(t)},e}();o.Instance=new o},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(e,t){void 0===t&&(t=!1),this.owner=e,this.useMarkdown=t,this.values={},this.htmlValues={},this.onGetTextCallback=null,this.onCreating()}return Object.defineProperty(e.prototype,"locale",{get:function(){return this.owner?this.owner.getLocale():""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"text",{get:function(){var e=this.pureText;return this.onGetTextCallback&&(e=this.onGetTextCallback(e)),e},set:function(e){this.setLocaleText(this.locale,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pureText",{get:function(){var t=this.locale;t||(t=e.defaultLocale);var n=this.values[t];return n||t===e.defaultLocale||(n=this.values[e.defaultLocale]),n||(n=""),n},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasHtml",{get:function(){return this.hasHtmlValue()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"html",{get:function(){return this.hasHtml?this.getHtmlValue():""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textOrHtml",{get:function(){return this.hasHtml?this.getHtmlValue():this.text},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderedHtml",{get:function(){var e=this.textOrHtml;return this.onRenderedHtmlCallback?this.onRenderedHtmlCallback(e):e},enumerable:!0,configurable:!0}),e.prototype.getLocaleText=function(t){t||(t=e.defaultLocale);var n=this.values[t];return n||""},e.prototype.setLocaleText=function(t,n){n!=this.getLocaleText(t)&&(t||(t=e.defaultLocale),delete this.htmlValues[t],n?"string"==typeof n&&(t!=e.defaultLocale&&n==this.getLocaleText(e.defaultLocale)?this.setLocaleText(t,null):(this.values[t]=n,t==e.defaultLocale&&this.deleteValuesEqualsToDefault(n))):this.values[t]&&delete this.values[t],this.onChanged())},e.prototype.getJson=function(){var t=Object.keys(this.values);return 0==t.length?null:1==t.length&&t[0]==e.defaultLocale?this.values[t[0]]:this.values},e.prototype.setJson=function(e){if(this.values={},this.htmlValues={},e){if("string"==typeof e)this.setLocaleText(null,e);else for(var t in e)this.setLocaleText(t,e[t]);this.onChanged()}},e.prototype.onChanged=function(){},e.prototype.onCreating=function(){},e.prototype.hasHtmlValue=function(){if(!this.owner||!this.useMarkdown)return!1;var t=this.text;if(!t)return!1;var n=this.locale;return n||(n=e.defaultLocale),n in this.htmlValues||(this.htmlValues[n]=this.owner.getMarkdownHtml(t)),!!this.htmlValues[n]},e.prototype.getHtmlValue=function(){var t=this.locale;return t||(t=e.defaultLocale),this.htmlValues[t]},e.prototype.deleteValuesEqualsToDefault=function(t){for(var n=Object.keys(this.values),r=0;r<n.length;r++)n[r]!=e.defaultLocale&&this.values[n[r]]==t&&delete this.values[n[r]]},e}();r.defaultLocale="default"},function(e,t,n){"use strict";var r=n(0),i=n(1),o=n(6);n.d(t,"a",function(){return s}),n.d(t,"b",function(){return a}),n.d(t,"d",function(){return u}),n.d(t,"c",function(){return l});var s=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getText=function(){return i.a.getString("requiredError")},t}(o.d),a=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getText=function(){return i.a.getString("numericError")},t}(o.d),u=function(e){function t(t){var n=e.call(this)||this;return n.maxSize=t,n}return r.b(t,e),t.prototype.getText=function(){return i.a.getString("exceedMaxSize").format(this.getTextSize())},t.prototype.getTextSize=function(){var e=["Bytes","KB","MB","GB","TB"],t=[0,0,2,3,3];if(0==this.maxSize)return"0 Byte";var n=Math.floor(Math.log(this.maxSize)/Math.log(1024));return(this.maxSize/Math.pow(1024,n)).toFixed(t[n])+" "+e[n]},t}(o.d),l=function(e){function t(t){var n=e.call(this)||this;return n.text=t,n}return r.b(t,e),t.prototype.getText=function(){return this.text},t}(o.d)},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(23),s=n(6),a=n(1),u=n(9),l=n(27),c=n(26),h=n(8);n.d(t,"a",function(){return p});var p=function(e){function t(t){var n=e.call(this,t)||this;n.name=t,n.isRequiredValue=!1,n.hasCommentValue=!1,n.hasOtherValue=!1,n.readOnlyValue=!1,n.errors=[],n.validators=new Array,n.isvalueChangedCallbackFiring=!1,n.isValueChangedInSurvey=!1,n.locTitleValue=new h.a(n,!0);var r=n;return n.locTitleValue.onRenderedHtmlCallback=function(e){return r.fullTitle},n.locCommentTextValue=new h.a(n,!0),n}return r.b(t,e),Object.defineProperty(t.prototype,"hasTitle",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasInput",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputId",{get:function(){return this.id+"i"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){var e=this.locTitle.text;return e||this.name},set:function(e){this.locTitle.text=e,this.fireCallback(this.titleChangedCallback)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locCommentText",{get:function(){return this.locCommentTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitleHtml",{get:function(){var e=this.locTitle.textOrHtml;return e||this.name},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.locTitle.onChanged(),this.locCommentText.onChanged()},Object.defineProperty(t.prototype,"processedTitle",{get:function(){return null!=this.survey?this.survey.processText(this.locTitleHtml):this.locTitleHtml},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullTitle",{get:function(){if(this.survey&&this.survey.getQuestionTitleTemplate()){if(!this.textPreProcessor){var e=this;this.textPreProcessor=new c.a,this.textPreProcessor.onHasValue=function(t){return e.canProcessedTextValues(t.toLowerCase())},this.textPreProcessor.onProcess=function(t){return e.getProcessedTextValue(t)}}return this.textPreProcessor.process(this.survey.getQuestionTitleTemplate())}var t=this.requiredText;t&&(t+=" ");var n=this.no;return n&&(n+=". "),n+t+this.processedTitle},enumerable:!0,configurable:!0}),t.prototype.focus=function(e){void 0===e&&(e=!1),s.a.ScrollElementToTop(this.id);var t=e?this.getFirstErrorInputElementId():this.getFirstInputElementId();s.a.FocusElement(t)&&this.fireCallback(this.focusCallback)},t.prototype.updateCssClasses=function(t,n){e.prototype.updateCssClasses.call(this,t,n),this.isRequired&&(n.question.required&&(t.root+=" "+n.question.required),n.question.titleRequired&&(t.title+=" "+n.question.titleRequired))},t.prototype.getFirstInputElementId=function(){return this.inputId},t.prototype.getFirstErrorInputElementId=function(){return this.getFirstInputElementId()},t.prototype.canProcessedTextValues=function(e){return"no"==e||"title"==e||"require"==e},t.prototype.getProcessedTextValue=function(e){return"no"==e?this.no:"title"==e?this.processedTitle:"require"==e?this.requiredText:null},t.prototype.supportComment=function(){return!1},t.prototype.supportOther=function(){return!1},Object.defineProperty(t.prototype,"isRequired",{get:function(){return this.isRequiredValue},set:function(e){this.isRequired!=e&&(this.isRequiredValue=e,this.fireCallback(this.titleChangedCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasComment",{get:function(){return this.hasCommentValue},set:function(e){this.supportComment()&&(this.hasCommentValue=e,this.hasComment&&(this.hasOther=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"commentText",{get:function(){var e=this.locCommentText.text;return e||a.a.getString("otherItemText")},set:function(e){this.locCommentText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasOther",{get:function(){return this.hasOtherValue},set:function(e){this.supportOther()&&this.hasOther!=e&&(this.hasOtherValue=e,this.hasOther&&(this.hasComment=!1),this.hasOtherChanged())},enumerable:!0,configurable:!0}),t.prototype.hasOtherChanged=function(){},Object.defineProperty(t.prototype,"isReadOnly",{get:function(){return this.readOnly||null!=this.survey&&this.survey.isDisplayMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"readOnly",{get:function(){return this.readOnlyValue},set:function(e){this.readOnly!=e&&(this.readOnlyValue=e,this.onReadOnlyChanged())},enumerable:!0,configurable:!0}),t.prototype.onReadOnlyChanged=function(){this.fireCallback(this.readOnlyChangedCallback)},t.prototype.onAnyValueChanged=function(e){if(e){var t=this.locTitle.text;t&&t.toLocaleLowerCase().indexOf("{"+e.toLowerCase()+"}")>-1&&this.fireCallback(this.titleChangedCallback)}},Object.defineProperty(t.prototype,"no",{get:function(){if(this.visibleIndex<0)return"";var e=1,t=!0,n="";return this.survey&&this.survey.questionStartIndex&&(n=this.survey.questionStartIndex,parseInt(n)?e=parseInt(n):1==n.length&&(t=!1)),t?(this.visibleIndex+e).toString():String.fromCharCode(n.charCodeAt(0)+this.visibleIndex)},enumerable:!0,configurable:!0}),t.prototype.onSetData=function(){e.prototype.onSetData.call(this),this.onSurveyValueChanged(this.value)},Object.defineProperty(t.prototype,"value",{get:function(){return this.valueFromData(this.getValueCore())},set:function(e){this.setNewValue(e),this.isvalueChangedCallbackFiring||(this.isvalueChangedCallbackFiring=!0,this.fireCallback(this.valueChangedCallback),this.isvalueChangedCallbackFiring=!1)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"comment",{get:function(){return this.getComment()},set:function(e){this.comment!=e&&(this.setComment(e),this.fireCallback(this.commentChangedCallback))},enumerable:!0,configurable:!0}),t.prototype.getComment=function(){return null!=this.data?this.data.getComment(this.name):this.questionComment},t.prototype.setComment=function(e){this.setNewComment(e)},t.prototype.isEmpty=function(){return s.b.isValueEmpty(this.value)},t.prototype.hasErrors=function(e){return void 0===e&&(e=!0),this.checkForErrors(e),this.errors.length>0},Object.defineProperty(t.prototype,"currentErrorCount",{get:function(){return this.errors.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"requiredText",{get:function(){return null!=this.survey&&this.isRequired?this.survey.requiredText:""},enumerable:!0,configurable:!0}),t.prototype.addError=function(e){this.errors.push(e),this.fireCallback(this.errorsChangedCallback)},t.prototype.checkForErrors=function(e){var t=this.errors?this.errors.length:0;if(this.errors=[],this.onCheckForErrors(this.errors),0==this.errors.length&&this.value){var n=this.runValidators();n&&this.errors.push(n)}if(this.survey&&0==this.errors.length){var n=this.fireSurveyValidation();n&&this.errors.push(n)}e&&(t!=this.errors.length||t>0)&&this.fireCallback(this.errorsChangedCallback)},t.prototype.fireSurveyValidation=function(){return this.validateValueCallback?this.validateValueCallback():this.survey?this.survey.validateQuestion(this.name):null},t.prototype.onCheckForErrors=function(e){this.hasRequiredError()&&this.errors.push(new u.a)},t.prototype.hasRequiredError=function(){return this.isRequired&&this.isEmpty()},t.prototype.runValidators=function(){return(new l.a).run(this)},t.prototype.setNewValue=function(e){this.setNewValueInData(e),this.onValueChanged()},t.prototype.setNewValueInData=function(e){this.isValueChangedInSurvey||(e=this.valueToData(e),this.setValueCore(e))},t.prototype.getValueCore=function(){return null!=this.data?this.data.getValue(this.name):this.questionValue},t.prototype.setValueCore=function(e){null!=this.data?this.data.setValue(this.name,e):this.questionValue=e},t.prototype.valueFromData=function(e){return e},t.prototype.valueToData=function(e){return e},t.prototype.onValueChanged=function(){},t.prototype.setNewComment=function(e){null!=this.data?this.data.setComment(this.name,e):this.questionComment=e},t.prototype.onSurveyValueChanged=function(e){this.isValueChangedInSurvey=!0,this.value=this.valueFromData(e),this.fireCallback(this.commentChangedCallback),this.isValueChangedInSurvey=!1},t.prototype.getValidatorTitle=function(){return null},t}(o.a);i.a.metaData.addClass("question",[{name:"title:text",serializationProperty:"locTitle"},{name:"commentText",serializationProperty:"locCommentText"},"isRequired:boolean","readOnly:boolean",{name:"validators:validators",baseClassName:"surveyvalidator",classNamePart:"validator"}],null,"questionbase")},function(e,t,n){"use strict";var r=n(8);n.d(t,"a",function(){return i});var i=function(){function e(e,t){void 0===t&&(t=null),this.locTextValue=new r.a(null,!0);var n=this;this.locTextValue.onGetTextCallback=function(e){return e||(n.value?n.value.toString():null)},t&&(this.locText.text=t),this.value=e}return e.createArray=function(t){var n=[];return e.setupArray(n,t),n},e.setupArray=function(e,t){e.push=function(e){var n=Array.prototype.push.call(this,e);return e.locOwner=t,n},e.splice=function(e,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var o=(a=Array.prototype.splice).call.apply(a,[this,e,n].concat(r));r||(r=[]);for(var s=0;s<r.length;s++)r[s].locOwner=t;return o;var a}},e.setData=function(t,n){t.length=0;for(var r=0;r<n.length;r++){var i=n[r],o=new e(null);o.setData(i),t.push(o)}},e.getData=function(e){for(var t=new Array,n=0;n<e.length;n++){var r=e[n],i=r.locText.getJson();i?t.push({value:r.value,text:i}):t.push(r.value)}return t},e.getItemByValue=function(e,t){for(var n=0;n<e.length;n++)if(e[n].value==t)return e[n];return null},e.NotifyArrayOnLocaleChanged=function(e){for(var t=0;t<e.length;t++)e[t].locText.onChanged()},e.prototype.getType=function(){return"itemvalue"},Object.defineProperty(e.prototype,"locText",{get:function(){return this.locTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"locOwner",{get:function(){return this.locText.owner},set:function(e){this.locText.owner=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.itemValue},set:function(t){if(this.itemValue=t,this.itemValue){var n=this.itemValue.toString(),r=n.indexOf(e.Separator);r>-1&&(this.itemValue=n.slice(0,r),this.text=n.slice(r+1))}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasText",{get:function(){return!!this.locText.pureText},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"text",{get:function(){return this.locText.text},set:function(e){this.locText.text=e},enumerable:!0,configurable:!0}),e.prototype.setData=function(t){if(void 0!==t.value){var n=null;this.isObjItemValue(t)&&(t.itemValue=t.itemValue,this.locText.setJson(t.locText.getJson()),n=e.itemValueProp),this.copyAttributes(t,n)}else this.value=t},e.prototype.isObjItemValue=function(e){return void 0!==e.getType&&"itemvalue"==e.getType()},e.prototype.copyAttributes=function(e,t){for(var n in e)"function"!=typeof e[n]&&(t&&t.indexOf(n)>-1||("text"==n?this.locText.setJson(e[n]):this[n]=e[n]))},e}();i.Separator="|",i.itemValueProp=["text","value","hasText","locOwner","locText"]},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"b",function(){return a}),n.d(t,"a",function(){return u});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.state={value:n.question.value||""},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.state={value:this.question.value||""}},t.prototype.handleOnChange=function(e){this.setState({value:e.target.value})},t.prototype.handleOnBlur=function(e){this.question.value=e.target.value,this.setState({value:this.question.value||""})},t.prototype.render=function(){if(!this.question)return null;var e=this.question.cssClasses;return i.createElement("textarea",{id:this.question.inputId,className:e.root,type:"text",readOnly:this.isDisplayMode,value:this.state.value,placeholder:this.question.placeHolder,onBlur:this.handleOnBlur,onChange:this.handleOnChange,cols:this.question.cols,rows:this.question.rows})},t}(o.b),u=function(e){function t(t){var n=e.call(this,t)||this;return n.question=t.question,n.comment=n.question.comment,n.otherCss=t.otherCss,n.state={value:n.comment},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),t.prototype.handleOnChange=function(e){this.comment=e.target.value,this.setState({value:this.comment})},t.prototype.handleOnBlur=function(e){this.question.comment=this.comment},t.prototype.componentWillReceiveProps=function(e){this.question=e.question},t.prototype.render=function(){if(!this.question)return null;if(this.isDisplayMode)return i.createElement("div",{className:this.cssClasses.comment},this.comment);var e=this.otherCss?this.otherCss:this.cssClasses.comment;return i.createElement("input",{type:"text",className:e,value:this.state.value,onChange:this.handleOnChange,onBlur:this.handleOnBlur})},t}(o.c);s.a.Instance.registerQuestion("comment",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";n.d(t,"b",function(){return r}),n.d(t,"a",function(){return i});var r={currentType:"",getCss:function(){var e=this.currentType?this[this.currentType]:i;return e||(e=i),e}},i={root:"sv_main",header:"",body:"sv_body",footer:"sv_nav",navigationButton:"",navigation:{complete:"sv_complete_btn",prev:"sv_prev_btn",next:"sv_next_btn"},progress:"sv_progress",progressBar:"",pageTitle:"sv_p_title",row:"sv_row",question:{mainRoot:"sv_q",title:"sv_q_title",comment:"",required:"",titleRequired:"",indent:20},error:{root:"sv_q_erbox",icon:"",item:""},checkbox:{root:"sv_qcbc",item:"sv_q_checkbox",other:"sv_q_other"},comment:"",dropdown:{root:"",control:"",other:"sv_q_other"},matrix:{root:"sv_q_matrix"},matrixdropdown:{root:"sv_q_matrix"},matrixdynamic:{root:"table",button:""},multipletext:{root:"",itemTitle:"",row:"",itemValue:""},radiogroup:{root:"sv_qcbc",item:"sv_q_radiogroup",label:"",other:"sv_q_other"},rating:{root:"sv_q_rating",item:"sv_q_rating_item"},text:"",saveData:{root:"",saving:"",error:"",success:"",saveAgainButton:""},window:{root:"sv_window",body:"sv_window_content",header:{root:"sv_window_title",title:"",button:"",buttonExpanded:"",buttonCollapsed:""}}};r.standard=i},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(10),s=n(11),a=n(1),u=n(9),l=n(19),c=n(8);n.d(t,"b",function(){return h}),n.d(t,"a",function(){return p});var h=function(e){function t(t){var n=e.call(this,t)||this;n.visibleChoicesCache=null,n.otherItemValue=new s.a("other",a.a.getString("otherItemText")),n.choicesFromUrl=null,n.cachedValueForUrlRequestion=null,n.storeOthersAsComment=!0,n.choicesOrderValue="none",n.isSettingComment=!1,n.choicesValues=s.a.createArray(n),n.choicesByUrl=n.createRestfull(),n.locOtherTextValue=new c.a(n,!0),n.locOtherErrorTextValue=new c.a(n,!0),n.otherItemValue.locOwner=n;var r=n;return n.choicesByUrl.getResultCallback=function(e){r.onLoadChoicesFromUrl(e)},n}return r.b(t,e),Object.defineProperty(t.prototype,"otherItem",{get:function(){return this.otherItemValue.text=this.otherText?this.otherText:a.a.getString("otherItemText"),this.otherItemValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isOtherSelected",{get:function(){return this.getStoreOthersAsComment()?this.getHasOther(this.value):this.getHasOther(this.cachedValue)},enumerable:!0,configurable:!0}),t.prototype.getHasOther=function(e){return e==this.otherItem.value},t.prototype.createRestfull=function(){return new l.a},t.prototype.getComment=function(){return this.getStoreOthersAsComment()?e.prototype.getComment.call(this):this.commentValue},t.prototype.setComment=function(t){this.getStoreOthersAsComment()?e.prototype.setComment.call(this,t):this.isSettingComment||t==this.commentValue||(this.isSettingComment=!0,this.commentValue=t,this.isOtherSelected&&this.setNewValueInData(this.cachedValue),this.isSettingComment=!1)},t.prototype.setNewValue=function(t){t&&(this.cachedValueForUrlRequestion=t),e.prototype.setNewValue.call(this,t)},t.prototype.valueFromData=function(t){return this.getStoreOthersAsComment()?e.prototype.valueFromData.call(this,t):(this.cachedValue=this.valueFromDataCore(t),this.cachedValue)},t.prototype.valueToData=function(t){return this.getStoreOthersAsComment()?e.prototype.valueToData.call(this,t):(this.cachedValue=t,this.valueToDataCore(t))},t.prototype.valueFromDataCore=function(e){return this.hasUnknownValue(e)?e==this.otherItem.value?e:(this.comment=e,this.otherItem.value):e},t.prototype.valueToDataCore=function(e){return e==this.otherItem.value&&this.getComment()&&(e=this.getComment()),e},t.prototype.hasUnknownValue=function(e){if(!e)return!1;for(var t=this.activeChoices,n=0;n<t.length;n++)if(t[n].value==e)return!1;return!0},Object.defineProperty(t.prototype,"choices",{get:function(){return this.choicesValues},set:function(e){s.a.setData(this.choicesValues,e),this.onVisibleChoicesChanged()},enumerable:!0,configurable:!0}),t.prototype.hasOtherChanged=function(){this.onVisibleChoicesChanged()},Object.defineProperty(t.prototype,"choicesOrder",{get:function(){return this.choicesOrderValue},set:function(e){(e=e.toLowerCase())!=this.choicesOrderValue&&(this.choicesOrderValue=e,this.onVisibleChoicesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"otherText",{get:function(){return this.locOtherText.text},set:function(e){this.locOtherText.text=e,this.onVisibleChoicesChanged()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"otherErrorText",{get:function(){return this.locOtherErrorText.text},set:function(e){this.locOtherErrorText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOtherText",{get:function(){return this.locOtherTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOtherErrorText",{get:function(){return this.locOtherErrorTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleChoices",{get:function(){return this.hasOther||"none"!=this.choicesOrder?(this.visibleChoicesCache||(this.visibleChoicesCache=this.sortVisibleChoices(this.activeChoices.slice()),this.hasOther&&this.visibleChoicesCache.push(this.otherItem)),this.visibleChoicesCache):this.activeChoices},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activeChoices",{get:function(){return this.choicesFromUrl?this.choicesFromUrl:this.choices},enumerable:!0,configurable:!0}),t.prototype.supportComment=function(){return!0},t.prototype.supportOther=function(){return!0},t.prototype.onCheckForErrors=function(t){if(e.prototype.onCheckForErrors.call(this,t),this.isOtherSelected&&!this.comment){var n=this.otherErrorText;n||(n=a.a.getString("otherRequiredError")),t.push(new u.c(n))}},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.onVisibleChoicesChanged(),s.a.NotifyArrayOnLocaleChanged(this.visibleChoices)},t.prototype.getStoreOthersAsComment=function(){return this.storeOthersAsComment&&(null==this.survey||this.survey.storeOthersAsComment)},t.prototype.onSurveyLoad=function(){e.prototype.onSurveyLoad.call(this),this.runChoicesByUrl(),this.onVisibleChoicesChanged()},t.prototype.onAnyValueChanged=function(t){e.prototype.onAnyValueChanged.call(this,t),this.runChoicesByUrl()},t.prototype.runChoicesByUrl=function(){this.choicesByUrl&&this.choicesByUrl.run(this.survey)},t.prototype.onLoadChoicesFromUrl=function(e){var t=this.errors.length;this.errors=[],this.choicesByUrl&&this.choicesByUrl.error&&this.errors.push(this.choicesByUrl.error),(t>0||this.errors.length>0)&&this.fireCallback(this.errorsChangedCallback);var n=null;e&&e.length>0&&(n=new Array,s.a.setData(n,e)),this.choicesFromUrl=n,this.onVisibleChoicesChanged(),this.cachedValueForUrlRequestion&&(this.value=this.cachedValueForUrlRequestion)},t.prototype.onVisibleChoicesChanged=function(){this.isLoadingFromJson||(this.visibleChoicesCache=null,this.fireCallback(this.choicesChangedCallback))},t.prototype.sortVisibleChoices=function(e){var t=this.choicesOrder.toLowerCase();return"asc"==t?this.sortArray(e,1):"desc"==t?this.sortArray(e,-1):"random"==t?this.randomizeArray(e):e},t.prototype.sortArray=function(e,t){return e.sort(function(e,n){return e.text<n.text?-1*t:e.text>n.text?1*t:0})},t.prototype.randomizeArray=function(e){for(var t=e.length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),r=e[t];e[t]=e[n],e[n]=r}return e},t.prototype.clearUnusedValues=function(){e.prototype.clearUnusedValues.call(this),this.isOtherSelected||this.hasComment||(this.comment=null)},t}(o.a),p=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.colCountValue=1,n}return r.b(t,e),Object.defineProperty(t.prototype,"colCount",{get:function(){return this.colCountValue},set:function(e){e<0||e>4||(this.colCountValue=e,this.fireCallback(this.colCountChangedCallback))},enumerable:!0,configurable:!0}),t}(h);i.a.metaData.addClass("selectbase",["hasComment:boolean","hasOther:boolean",{name:"choices:itemvalues",onGetValue:function(e){return s.a.getData(e.choices)},onSetValue:function(e,t){e.choices=t}},{name:"choicesOrder",default:"none",choices:["none","asc","desc","random"]},{name:"choicesByUrl:restfull",className:"ChoicesRestfull",onGetValue:function(e){return e.choicesByUrl.isEmpty?null:e.choicesByUrl},onSetValue:function(e,t){e.choicesByUrl.setData(t)}},{name:"otherText",serializationProperty:"locOtherText"},{name:"otherErrorText",serializationProperty:"locOtherErrorText"},{name:"storeOthersAsComment:boolean",default:!0}],null,"question"),i.a.metaData.addClass("checkboxbase",[{name:"colCount:number",default:1,choices:[0,1,2,3,4]}],null,"selectbase")},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(10)),s=n(12),a=n(4),u=n(24);n.d(t,"a",function(){return l}),n.d(t,"b",function(){return c});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.setQuestion(t.question),n.creator=t.creator,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.creator=e.creator,this.setQuestion(e.question)},t.prototype.setQuestion=function(e){this.questionBase=e,this.question=e instanceof o.a?e:null;var t=this.question?this.question.value:null;this.state={visible:this.questionBase.visible,value:t,error:0,renderWidth:0,visibleIndexValue:-1,isReadOnly:this.questionBase.isReadOnly}},t.prototype.componentDidMount=function(){if(this.questionBase){var e=this;this.questionBase.react=e,this.questionBase.renderWidthChangedCallback=function(){e.state.renderWidth=e.state.renderWidth+1,e.setState(e.state)},this.questionBase.visibleIndexChangedCallback=function(){e.state.visibleIndexValue=e.questionBase.visibleIndex,e.setState(e.state)},this.questionBase.readOnlyChangedCallback=function(){e.state.isReadOnly=e.questionBase.isReadOnly,e.setState(e.state)};var t=this.refs.root;t&&this.questionBase.survey&&this.questionBase.survey.afterRenderQuestion(this.questionBase,t)}},t.prototype.componentWillUnmount=function(){this.refs.root;this.questionBase&&(this.questionBase.react=null,this.questionBase.renderWidthChangedCallback=null,this.questionBase.visibleIndexChangedCallback=null,this.questionBase.readOnlyChangedCallback=null)},t.prototype.render=function(){if(!this.questionBase||!this.creator)return null;if(!this.questionBase.visible)return null;var e=this.questionBase.cssClasses,t=this.renderQuestion(),n=this.questionBase.hasTitle?this.renderTitle(e):null,r="top"==this.creator.questionTitleLocation()?n:null,o="bottom"==this.creator.questionTitleLocation()?n:null,s=this.question&&this.question.hasComment?this.renderComment(e):null,a=this.renderErrors(e),u=this.questionBase.indent>0?this.questionBase.indent*e.indent+"px":null,l=this.questionBase.rightIndent>0?this.questionBase.rightIndent*e.indent+"px":null,c={display:"inline-block",verticalAlign:"top"};return this.questionBase.renderWidth&&(c.width=this.questionBase.renderWidth),u&&(c.paddingLeft=u),l&&(c.paddingRight=l),i.createElement("div",{ref:"root",id:this.questionBase.id,className:e.mainRoot,style:c},r,a,t,s,o)},t.prototype.renderQuestion=function(){return this.questionBase.customWidget?i.createElement(u.a,{creator:this.creator,question:this.questionBase}):this.creator.createQuestionElement(this.questionBase)},t.prototype.renderTitle=function(e){var t=a.a.renderLocString(this.question.locTitle);return i.createElement("h5",{className:e.title},t)},t.prototype.renderComment=function(e){var t=a.a.renderLocString(this.question.locCommentText);return i.createElement("div",null,i.createElement("div",null,t),i.createElement(s.a,{question:this.question,cssClasses:e}))},t.prototype.renderErrors=function(e){return i.createElement(c,{question:this.question,cssClasses:e,creator:this.creator})},t}(i.Component),c=function(e){function t(t){var n=e.call(this,t)||this;return n.setQuestion(t.question),n.creator=t.creator,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.setQuestion(e.question),this.creator=e.creator},t.prototype.setQuestion=function(e){if(this.question=e instanceof o.a?e:null,this.question){var t=this;this.question.errorsChangedCallback=function(){t.state.error=t.state.error+1,t.setState(t.state)}}this.state={error:0}},t.prototype.render=function(){if(!this.question||0==this.question.errors.length)return null;for(var e=[],t=0;t<this.question.errors.length;t++){var n=this.question.errors[t].getText(),r="error"+t;e.push(this.creator.renderError(r,n,this.cssClasses))}return i.createElement("div",{className:this.cssClasses.error.root},e)},t}(a.c)},function(e,t,n){"use strict";var r=n(0),i=n(25);n.d(t,"a",function(){return o});var o=function(e){function t(t){return void 0===t&&(t=null),e.call(this,t)||this}return r.b(t,e),t.prototype.render=function(){this.renderCallback&&this.renderCallback()},t.prototype.mergeCss=function(e,t){this.mergeValues(e,t)},t.prototype.doAfterRenderSurvey=function(e){this.afterRenderSurvey(e)},t.prototype.onLoadSurveyFromService=function(){this.render()},t.prototype.onLoadingSurveyFromService=function(){this.render()},t.prototype.setCompletedState=function(t,n){e.prototype.setCompletedState.call(this,t,n),this.render()},t}(i.a)},function(e,t,n){"use strict";var r=n(32),i=n(20);n.d(t,"b",function(){return o}),n.d(t,"c",function(){return s}),n.d(t,"a",function(){return a});var o=function(){function e(){this.opValue="equal",this.left=null,this.right=null}return Object.defineProperty(e,"operators",{get:function(){return null!=e.operatorsValue?e.operatorsValue:(e.operatorsValue={empty:function(e,t){return null==e||!e},notempty:function(e,t){return null!=e&&!!e},equal:function(e,t){return!(null==e&&null!=t||null!=e&&null==t)&&(null==e&&null==t||e==t)},notequal:function(e,t){return null==e&&null!=t||null!=e&&null==t||(null!=e||null!=t)&&e!=t},contains:function(e,t){return null!=e&&e.indexOf&&e.indexOf(t)>-1},notcontains:function(e,t){return null==e||!e.indexOf||-1==e.indexOf(t)},greater:function(e,t){return null!=e&&(null==t||e>t)},less:function(e,t){return null!=t&&(null==e||e<t)},greaterorequal:function(e,t){return(null!=e||null==t)&&(null==t||e>=t)},lessorequal:function(e,t){return(null==e||null!=t)&&(null==e||e<=t)}},e.operatorsValue)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"operator",{get:function(){return this.opValue},set:function(t){t&&(t=t.toLowerCase(),e.operators[t]&&(this.opValue=t))},enumerable:!0,configurable:!0}),e.prototype.perform=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=null),e||(e=this.left),t||(t=this.right),this.performExplicit(e,t)},e.prototype.performExplicit=function(t,n){return e.operators[this.operator](this.getPureValue(t),this.getPureValue(n))},e.prototype.getPureValue=function(e){if(void 0===e)return null;if(!e||"string"!=typeof e)return e;e.length>0&&("'"==e[0]||'"'==e[0])&&(e=e.substr(1));var t=e.length;return t>0&&("'"==e[t-1]||'"'==e[t-1])&&(e=e.substr(0,t-1)),e},e}();o.operatorsValue=null;var s=function(){function e(){this.connectiveValue="and",this.children=[]}return Object.defineProperty(e.prototype,"connective",{get:function(){return this.connectiveValue},set:function(e){e&&(e=e.toLowerCase(),"&"!=e&&"&&"!=e||(e="and"),"|"!=e&&"||"!=e||(e="or"),"and"!=e&&"or"!=e||(this.connectiveValue=e))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isEmpty",{get:function(){return 0==this.children.length},enumerable:!0,configurable:!0}),e.prototype.clear=function(){this.children=[],this.connective="and"},e}(),a=function(){function e(e){this.root=new s,this.expression=e,this.processValue=new i.a}return Object.defineProperty(e.prototype,"expression",{get:function(){return this.expressionValue},set:function(e){this.expression!=e&&(this.expressionValue=e,(new r.a).parse(this.expressionValue,this.root))},enumerable:!0,configurable:!0}),e.prototype.run=function(e){return this.values=e,this.runNode(this.root)},e.prototype.runNode=function(e){for(var t="and"==e.connective,n=0;n<e.children.length;n++){var r=this.runNodeCondition(e.children[n]);if(!r&&t)return!1;if(r&&!t)return!0}return t},e.prototype.runNodeCondition=function(e){return e.children?this.runNode(e):!!e.left&&this.runCondition(e)},e.prototype.runCondition=function(e){var t=e.left,n=this.getValueName(t);n&&(t=this.getValueByName(n));var r=e.right;return n=this.getValueName(r),n&&(r=this.getValueByName(n)),e.performExplicit(t,r)},e.prototype.getValueByName=function(e){return this.processValue.hasValue(e,this.values)?this.processValue.getValue(e,this.values):null},e.prototype.getValueName=function(e){return e?"string"!=typeof e?null:e.length<3||"{"!=e[0]||"}"!=e[e.length-1]?null:e.substr(1,e.length-2):null},e}()},function(e,t,n){"use strict";var r=n(0),i=n(3);n.n(i);n.d(t,"a",function(){return o});var o=function(e){function t(t){var n=e.call(this,t)||this;return n.updateStateFunction=null,n.survey=t.survey,n.css=t.css,n.state={update:0},n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.survey=e.survey,this.css=e.css},t.prototype.componentDidMount=function(){if(this.survey){var e=this;this.updateStateFunction=function(){e.state.update=e.state.update+1,e.setState(e.state)},this.survey.onPageVisibleChanged.add(this.updateStateFunction)}},t.prototype.componentWillUnmount=function(){this.survey&&this.updateStateFunction&&(this.survey.onPageVisibleChanged.remove(this.updateStateFunction),this.updateStateFunction=null)},t}(i.Component)},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(11),s=n(2),a=n(1),u=n(9);n.d(t,"a",function(){return l});var l=function(e){function t(){var t=e.call(this)||this;return t.lastObjHash="",t.processedUrl="",t.processedPath="",t.url="",t.path="",t.valueName="",t.titleName="",t.error=null,t}return r.b(t,e),t.getCachedItemsResult=function(e){var n=e.objHash,r=t.itemsResult[n];return!!r&&(e.getResultCallback&&e.getResultCallback(r),!0)},t.prototype.run=function(e){if(void 0===e&&(e=null),this.url&&this.getResultCallback){if(this.processedText(e),!this.processedUrl)return void this.getResultCallback([]);this.lastObjHash!=this.objHash&&(this.lastObjHash=this.objHash,t.getCachedItemsResult(this)||(this.error=null,this.sendRequest()))}},t.prototype.processedText=function(e){if(e){var t=e.processTextEx(this.url),n=e.processTextEx(this.path);t.hasAllValuesOnLastRun&&n.hasAllValuesOnLastRun?(this.processedUrl=t.text,this.processedPath=n.text):(this.processedUrl="",this.processedPath="")}else this.processedUrl=this.url,this.processedPath=this.path},t.prototype.sendRequest=function(){var e=new XMLHttpRequest;e.open("GET",this.processedUrl),e.setRequestHeader("Content-Type","application/x-www-form-urlencoded");var t=this;e.onload=function(){200==e.status?t.onLoad(JSON.parse(e.response)):t.onError(e.statusText,e.responseText)},e.send()},t.prototype.getType=function(){return"choicesByUrl"},Object.defineProperty(t.prototype,"isEmpty",{get:function(){return!(this.url||this.path||this.valueName||this.titleName)},enumerable:!0,configurable:!0}),t.prototype.setData=function(e){this.clear(),e.url&&(this.url=e.url),e.path&&(this.path=e.path),e.valueName&&(this.valueName=e.valueName),e.titleName&&(this.titleName=e.titleName)},t.prototype.clear=function(){this.url="",this.path="",this.valueName="",this.titleName=""},t.prototype.onLoad=function(e){var n=[];if((e=this.getResultAfterPath(e))&&e.length)for(var r=0;r<e.length;r++){var i=e[r];if(i){var s=this.getValue(i),l=this.getTitle(i);n.push(new o.a(s,l))}}else this.error=new u.c(a.a.getString("urlGetChoicesError"));t.itemsResult[this.objHash]=n,this.getResultCallback(n)},t.prototype.onError=function(e,t){this.error=new u.c(a.a.getString("urlRequestError").format(e,t)),this.getResultCallback([])},t.prototype.getResultAfterPath=function(e){if(!e)return e;if(!this.processedPath)return e;for(var t=this.getPathes(),n=0;n<t.length;n++)if(!(e=e[t[n]]))return null;return e},t.prototype.getPathes=function(){var e=[];return e=this.processedPath.indexOf(";")>-1?this.path.split(";"):this.processedPath.split(","),0==e.length&&e.push(this.processedPath),e},t.prototype.getValue=function(e){return e?this.valueName?this.getValueCore(e,this.valueName):e instanceof Object?Object.keys(e).length<1?null:e[Object.keys(e)[0]]:e:null},t.prototype.getTitle=function(e){return this.titleName?this.getValueCore(e,this.titleName):null},t.prototype.getValueCore=function(e,t){if(!e)return null;if(t.indexOf(".")<0)return e[t];for(var n=t.split("."),r=0;r<n.length;r++)if(!(e=e[n[r]]))return null;return e},Object.defineProperty(t.prototype,"objHash",{get:function(){return this.processedUrl+";"+this.processedPath+";"+this.valueName+";"+this.titleName},enumerable:!0,configurable:!0}),t}(i.b);l.itemsResult={},s.a.metaData.addClass("choicesByUrl",["url","path","valueName","titleName"],function(){return new l})},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(){}return e.prototype.getFirstName=function(e){if(!e)return e;for(var t="",n=0;n<e.length;n++){var r=e[n];if("."==r||"["==r)break;t+=r}return t},e.prototype.hasValue=function(e,t){return this.getValueCore(e,t).hasValue},e.prototype.getValue=function(e,t){return this.getValueCore(e,t).value},e.prototype.getValueCore=function(e,t){var n={hasValue:!1,value:null},r=t;if(!r)return n;for(var i=!0;e&&e.length>0;){if(!i&&"["==e[0]){if(!Array.isArray(r))return n;for(var o=1,s="";o<e.length&&"]"!=e[o];)s+=e[o],o++;if(e=o<e.length?e.substr(o+1):"",(o=this.getIntValue(s))<0||o>=r.length)return n;r=r[o]}else{i||(e=e.substr(1));var a=this.getFirstName(e);if(!a)return n;if(!r[a])return n;r=r[a],e=e.substr(a.length)}i=!1}return n.value=r,n.hasValue=!0,n},e.prototype.getIntValue=function(e){return"0"==e||(0|e)>0&&e%1==0?Number(e):-1},e}()},function(e,t,n){"use strict";var r=n(6);n.d(t,"b",function(){return i}),n.d(t,"a",function(){return o});var i=function(){function e(e,t){this.name=e,this.widgetJson=t,this.htmlTemplate=t.htmlTemplate?t.htmlTemplate:""}return e.prototype.afterRender=function(e,t){this.widgetJson.afterRender&&this.widgetJson.afterRender(e,t)},e.prototype.willUnmount=function(e,t){this.widgetJson.willUnmount&&this.widgetJson.willUnmount(e,t)},e.prototype.isFit=function(e){return!!this.widgetJson.isFit&&this.widgetJson.isFit(e)},e}(),o=function(){function e(){this.widgetsValues=[],this.onCustomWidgetAdded=new r.c}return Object.defineProperty(e.prototype,"widgets",{get:function(){return this.widgetsValues},enumerable:!0,configurable:!0}),e.prototype.addCustomWidget=function(e){var t=e.name;t||(t="widget_"+this.widgets.length+1);var n=new i(t,e);this.widgetsValues.push(n),this.onCustomWidgetAdded.fire(n,null)},e.prototype.clear=function(){this.widgetsValues=[]},e.prototype.getCustomWidget=function(e){for(var t=0;t<this.widgetsValues.length;t++)if(this.widgetsValues[t].isFit(e))return this.widgetsValues[t];return null},e}();o.Instance=new o},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(10),s=n(6),a=n(11),u=n(1),l=n(14),c=n(19),h=n(7),p=n(8),d=n(21);n.d(t,"b",function(){return f}),n.d(t,"a",function(){return m}),n.d(t,"c",function(){return g}),n.d(t,"d",function(){return y});var f=function(e){function t(t,n){void 0===n&&(n=null);var r=e.call(this)||this;r.isRequiredValue=!1,r.hasOtherValue=!1,r.minWidth="",r.cellTypeValue="default",r.inputTypeValue="text",r.choicesOrderValue="none",r.colOwner=null,r.validators=new Array,r.colCountValue=-1,r.nameValue=t,r.choicesValue=a.a.createArray(r),r.locTitleValue=new p.a(r,!0);var i=r;return r.locTitleValue.onRenderedHtmlCallback=function(e){return i.getFullTitle(e)},r.locOptionsCaptionValue=new p.a(r),r.locPlaceHolderValue=new p.a(r),r.choicesByUrl=new c.a,n&&(r.title=n),r}return r.b(t,e),t.prototype.getType=function(){return"matrixdropdowncolumn"},Object.defineProperty(t.prototype,"name",{get:function(){return this.nameValue},set:function(e){e!=this.name&&(this.nameValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"choicesOrder",{get:function(){return this.choicesOrderValue},set:function(e){e=e.toLocaleLowerCase(),this.choicesOrder!=e&&(this.choicesOrderValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputType",{get:function(){return this.inputTypeValue},set:function(e){e=e.toLocaleLowerCase(),this.inputTypeValue!=e&&(this.inputTypeValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cellType",{get:function(){return this.cellTypeValue},set:function(e){e=e.toLocaleLowerCase(),this.cellTypeValue!=e&&(this.cellTypeValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text?this.locTitle.text:this.name},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullTitle",{get:function(){return this.getFullTitle(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),t.prototype.getFullTitle=function(e){if(e||(e=this.name),this.isRequired){var t=this.colOwner?this.colOwner.getRequiredText():"";t&&(t+=" "),e=t+e}return e},Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"optionsCaption",{get:function(){return this.locOptionsCaption.text},set:function(e){this.locOptionsCaption.text=e,this.onPropertiesChanged()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOptionsCaption",{get:function(){return this.locOptionsCaptionValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e,this.onPropertiesChanged()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"choices",{get:function(){return this.choicesValue},set:function(e){a.a.setData(this.choicesValue,e),this.onPropertiesChanged()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colCount",{get:function(){return this.colCountValue},set:function(e){e<-1||e>4||(this.colCountValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isRequired",{get:function(){return this.isRequiredValue},set:function(e){this.isRequired!=e&&(this.isRequiredValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasOther",{get:function(){return this.hasOtherValue},set:function(e){this.hasOther!=e&&(this.hasOtherValue=e,this.onPropertiesChanged())},enumerable:!0,configurable:!0}),t.prototype.getLocale=function(){return this.colOwner?this.colOwner.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.colOwner?this.colOwner.getMarkdownHtml(e):null},t.prototype.onLocaleChanged=function(){this.locTitle.onChanged(),this.locOptionsCaption.onChanged(),a.a.NotifyArrayOnLocaleChanged(this.choices)},t.prototype.onPropertiesChanged=function(){null!=this.colOwner&&this.colOwner.onColumnPropertiesChanged(this)},t}(s.b),m=function(){function e(e,t,n){var r=this;this.column=e,this.row=t,this.questionValue=n.createQuestion(this.row,this.column),this.questionValue.setData(t),this.questionValue.validateValueCallback=function(){return n.validateCell(t,e.name,t.value)},i.a.metaData.getProperties(e.getType()).forEach(function(t){var n=t.name;void 0!==e[n]&&void 0===r.questionValue[n]&&(r.questionValue[n]=e[n])}),Object.keys(e).forEach(function(e){}),this.questionValue.customWidget=d.a.Instance.getCustomWidget(this.questionValue)}return Object.defineProperty(e.prototype,"question",{get:function(){return this.questionValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.question.value},set:function(e){this.question.value=e},enumerable:!0,configurable:!0}),e}(),g=function(){function e(t,n){this.rowValues={},this.rowComments={},this.isSettingValue=!1,this.cells=[],this.data=t,this.value=n;for(var r=0;r<this.data.columns.length;r++)void 0===this.rowValues[this.data.columns[r].name]&&(this.rowValues[this.data.columns[r].name]=null);this.idValue=e.getId(),this.buildCells()}return e.getId=function(){return"srow_"+e.idCounter++},Object.defineProperty(e.prototype,"id",{get:function(){return this.idValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rowName",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this.rowValues},set:function(e){if(this.isSettingValue=!0,this.rowValues={},null!=e)for(var t in e)this.rowValues[t]=e[t];for(var n=0;n<this.cells.length;n++)this.cells[n].question.onSurveyValueChanged(this.getValue(this.cells[n].column.name));this.isSettingValue=!1},enumerable:!0,configurable:!0}),e.prototype.getValue=function(e){return this.rowValues[e]},e.prototype.setValue=function(e,t){this.isSettingValue||(""===t&&(t=null),null!=t?this.rowValues[e]=t:delete this.rowValues[e],this.data.onRowChanged(this,e,this.value))},e.prototype.getComment=function(e){return this.rowComments[e]},e.prototype.setComment=function(e,t){this.rowComments[e]=t},Object.defineProperty(e.prototype,"isEmpty",{get:function(){var e=this.value;if(s.b.isValueEmpty(e))return!0;for(var t in e)if(void 0!==e[t]&&null!==e[t])return!1;return!0},enumerable:!0,configurable:!0}),e.prototype.getLocale=function(){return this.data?this.data.getLocale():""},e.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},e.prototype.onLocaleChanged=function(){for(var e=0;e<this.cells.length;e++)this.cells[e].question.onLocaleChanged()},e.prototype.buildCells=function(){for(var e=this.data.columns,t=0;t<e.length;t++){var n=e[t];this.cells.push(this.createCell(n))}},e.prototype.createCell=function(e){return new m(e,this,this.data)},e}();g.idCounter=1;var y=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.columnsValue=[],n.isRowChanging=!1,n.generatedVisibleRows=null,n.cellTypeValue="dropdown",n.columnColCountValue=0,n.columnMinWidth="",n.horizontalScroll=!1,n.choicesValue=a.a.createArray(n),n.locOptionsCaptionValue=new p.a(n),n.overrideColumnsMethods(),n}return r.b(t,e),t.addDefaultColumns=function(e){for(var t=h.a.DefaultColums,n=0;n<t.length;n++)e.addColumn(t[n])},t.prototype.getType=function(){return"matrixdropdownbase"},Object.defineProperty(t.prototype,"columns",{get:function(){return this.columnsValue},set:function(e){this.columnsValue=e,this.overrideColumnsMethods(),this.fireCallback(this.columnsChangedCallback)},enumerable:!0,configurable:!0}),t.prototype.onMatrixRowCreated=function(e){if(this.survey)for(var t={rowValue:e.value,row:e,column:null,columnName:null,cell:null,cellQuestion:null,value:null},n=0;n<this.columns.length;n++){t.column=this.columns[n],t.columnName=t.column.name;var r=e.cells[n];t.cell=r,t.cellQuestion=r.question,t.value=r.value,this.survey.matrixCellCreated(this,t)}},t.prototype.overrideColumnsMethods=function(){var e=this;this.columnsValue.push=function(t){var n=Array.prototype.push.call(this,t);return e.generatedVisibleRows=null,t.colOwner=e,null!=e.data&&e.fireCallback(e.columnsChangedCallback),n},this.columnsValue.splice=function(t,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];var o=(a=Array.prototype.splice).call.apply(a,[this,t,n].concat(r));e.generatedVisibleRows=null,r||(r=[]);for(var s=0;s<r.length;s++)r[s].colOwner=e;return null!=e.data&&e.fireCallback(e.columnsChangedCallback),o;var a}},Object.defineProperty(t.prototype,"cellType",{get:function(){return this.cellTypeValue},set:function(e){e=e.toLowerCase(),this.cellType!=e&&(this.cellTypeValue=e,this.fireCallback(this.updateCellsCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"columnColCount",{get:function(){return this.columnColCountValue},set:function(e){e<0||e>4||(this.columnColCountValue=e,this.fireCallback(this.updateCellsCallback))},enumerable:!0,configurable:!0}),t.prototype.getRequiredText=function(){return this.survey?this.survey.requiredText:""},t.prototype.onColumnPropertiesChanged=function(e){if(this.generatedVisibleRows)for(var t=0;t<this.generatedVisibleRows.length;t++)for(var n=this.generatedVisibleRows[t],r=0;r<n.cells.length;r++)if(n.cells[r].column===e){this.setQuestionProperties(n.cells[r].question,e);break}},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.locOptionsCaption.onChanged();for(var t=0;t<this.columns.length;t++)this.columns[t].onLocaleChanged();for(var n=this.visibleRows,t=0;t<n.length;t++)n[t].onLocaleChanged();this.fireCallback(this.updateCellsCallback)},t.prototype.getColumnWidth=function(e){return e.minWidth?e.minWidth:this.columnMinWidth},Object.defineProperty(t.prototype,"choices",{get:function(){return this.choicesValue},set:function(e){a.a.setData(this.choicesValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"optionsCaption",{get:function(){return this.locOptionsCaption.text?this.locOptionsCaption.text:u.a.getString("optionsCaption")},set:function(e){this.locOptionsCaption.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOptionsCaption",{get:function(){return this.locOptionsCaptionValue},enumerable:!0,configurable:!0}),t.prototype.addColumn=function(e,t){void 0===t&&(t=null);var n=new f(e,t);return this.columnsValue.push(n),n},Object.defineProperty(t.prototype,"visibleRows",{get:function(){if(!this.isLoadingFromJson)return this.generatedVisibleRows||(this.generatedVisibleRows=this.generateRows()),this.generatedVisibleRows},enumerable:!0,configurable:!0}),t.prototype.onSurveyLoad=function(){e.prototype.onSurveyLoad.call(this),this.generatedVisibleRows=null},t.prototype.getRowValue=function(e){if(e<0)return null;var t=this.visibleRows;if(e>=t.length)return null;var n=this.createNewValue(this.value);return this.getRowValueCore(t[e],n)},t.prototype.setRowValue=function(e,t){if(e<0)return null;var n=this.visibleRows;if(e>=n.length)return null;this.onRowChanged(n[e],"",t),this.onValueChanged()},t.prototype.generateRows=function(){return null},t.prototype.createNewValue=function(e){return e||{}},t.prototype.getRowValueCore=function(e,t,n){void 0===n&&(n=!1);var r=t[e.rowName]?t[e.rowName]:null;return!r&&n&&(r={},t[e.rowName]=r),r},t.prototype.onBeforeValueChanged=function(e){},t.prototype.onValueChanged=function(){if(!this.isRowChanging&&(this.onBeforeValueChanged(this.value),this.generatedVisibleRows&&0!=this.generatedVisibleRows.length)){this.isRowChanging=!0;for(var e=this.createNewValue(this.value),t=0;t<this.generatedVisibleRows.length;t++){var n=this.generatedVisibleRows[t];this.generatedVisibleRows[t].value=this.getRowValueCore(n,e)}this.isRowChanging=!1}},t.prototype.supportGoNextPageAutomatic=function(){var e=this.generatedVisibleRows;if(e||(e=this.visibleRows),!e)return!0;for(var t=0;t<e.length;t++){var n=this.generatedVisibleRows[t].cells;if(n)for(var r=0;r<n.length;r++){var i=n[r].question;if(i&&(!i.supportGoNextPageAutomatic()||!i.value))return!1}}return!0},t.prototype.hasErrors=function(t){void 0===t&&(t=!0);var n=this.hasErrorInColumns(t);return e.prototype.hasErrors.call(this,t)||n},t.prototype.hasErrorInColumns=function(e){if(!this.generatedVisibleRows)return!1;for(var t=!1,n=0;n<this.columns.length;n++)for(var r=0;r<this.generatedVisibleRows.length;r++){var i=this.generatedVisibleRows[r].cells;t=i&&i[n]&&i[n].question&&i[n].question.hasErrors(e)||t}return t},t.prototype.getFirstInputElementId=function(){var t=this.getFirstCellQuestion(!1);return t?t.inputId:e.prototype.getFirstInputElementId.call(this)},t.prototype.getFirstErrorInputElementId=function(){var t=this.getFirstCellQuestion(!0);return t?t.inputId:e.prototype.getFirstErrorInputElementId.call(this)},t.prototype.getFirstCellQuestion=function(e){if(!this.generatedVisibleRows)return null;for(var t=0;t<this.generatedVisibleRows.length;t++)for(var n=this.generatedVisibleRows[t].cells,r=0;r<this.columns.length;r++){if(!e)return n[r].question;if(n[r].question.currentErrorCount>0)return n[r].question}return null},t.prototype.createQuestion=function(e,t){return this.createQuestionCore(e,t)},t.prototype.createQuestionCore=function(e,t){var n="default"==t.cellType?this.cellType:t.cellType,r=this.createCellQuestion(n,t.name);return r.setData(this.survey),this.setQuestionProperties(r,t),r},t.prototype.getColumnChoices=function(e){return e.choices&&e.choices.length>0?e.choices:this.choices},t.prototype.getColumnOptionsCaption=function(e){return e.optionsCaption?e.optionsCaption:this.optionsCaption},t.prototype.setQuestionProperties=function(e,t){if(e){e.name=t.name,e.isRequired=t.isRequired,e.hasOther=t.hasOther,e.readOnly=this.readOnly,e.validators=t.validators,t.hasOther&&e instanceof l.b&&(e.storeOthersAsComment=!1);var n=e.getType();"checkbox"!=n&&"radiogroup"!=n||(e.colCount=t.colCount>-1?t.colCount:this.columnColCount,this.setSelectBaseProperties(e,t)),"dropdown"==n&&(e.optionsCaption=this.getColumnOptionsCaption(t),this.setSelectBaseProperties(e,t)),"text"==n&&(e.inputType=t.inputType,e.placeHolder=t.placeHolder),"comment"==n&&(e.placeHolder=t.placeHolder)}},t.prototype.setSelectBaseProperties=function(e,t){e.choicesOrder=t.choicesOrder,e.choices=this.getColumnChoices(t),e.choicesByUrl.setData(t.choicesByUrl),e.choicesByUrl.isEmpty||e.choicesByUrl.run()},t.prototype.createCellQuestion=function(e,t){return h.a.Instance.createQuestion(e,t)},t.prototype.deleteRowValue=function(e,t){return delete e[t.rowName],0==Object.keys(e).length?null:e},t.prototype.onCellValueChanged=function(e,t,n){if(this.survey){var r=this,i=function(t){for(var n=0;r.columns.length;n++)if(r.columns[n].name==t)return e.cells[n].question;return null},o={row:e,columnName:t,rowValue:n,value:n[t],getCellQuestion:i};this.survey.matrixCellValueChanged(this,o)}},t.prototype.validateCell=function(e,t,n){if(this.survey){var r={row:e,columnName:t,rowValue:n,value:n[t]};return this.survey.matrixCellValidate(this,r)}},t.prototype.onRowChanged=function(e,t,n){var r=this.createNewValue(this.value),i=this.getRowValueCore(e,r,!0);for(var o in i)delete i[o];if(n){n=JSON.parse(JSON.stringify(n));for(var o in n)i[o]=n[o]}0==Object.keys(i).length&&(r=this.deleteRowValue(r,e)),this.isRowChanging=!0,this.setNewValue(r),this.isRowChanging=!1,t&&this.onCellValueChanged(e,t,i)},t}(o.a);i.a.metaData.addClass("matrixdropdowncolumn",["name",{name:"title",serializationProperty:"locTitle"},{name:"choices:itemvalues",onGetValue:function(e){return a.a.getData(e.choices)},onSetValue:function(e,t){e.choices=t}},{name:"optionsCaption",serializationProperty:"locOptionsCaption"},{name:"cellType",default:"default",choices:["default","dropdown","checkbox","radiogroup","text","comment"]},{name:"colCount",default:-1,choices:[-1,0,1,2,3,4]},"isRequired:boolean","hasOther:boolean","minWidth",{name:"placeHolder",serializationProperty:"locPlaceHolder"},{name:"choicesOrder",default:"none",choices:["none","asc","desc","random"]},{name:"choicesByUrl:restfull",className:"ChoicesRestfull",onGetValue:function(e){return e.choicesByUrl.isEmpty?null:e.choicesByUrl},onSetValue:function(e,t){e.choicesByUrl.setData(t)}},{name:"inputType",default:"text",choices:["color","date","datetime","datetime-local","email","month","number","password","range","tel","text","time","url","week"]},{name:"validators:validators",baseClassName:"surveyvalidator",classNamePart:"validator"}],function(){return new f("")}),i.a.metaData.addClass("matrixdropdownbase",[{name:"columns:matrixdropdowncolumns",className:"matrixdropdowncolumn"},"horizontalScroll:boolean",{name:"choices:itemvalues",onGetValue:function(e){return a.a.getData(e.choices)},onSetValue:function(e,t){e.choices=t}},{name:"optionsCaption",serializationProperty:"locOptionsCaption"},{name:"cellType",default:"dropdown",choices:["dropdown","checkbox","radiogroup","text","comment"]},{name:"columnColCount",default:0,choices:[0,1,2,3,4]},"columnMinWidth"],function(){return new y("")},"question")},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(2),s=n(17),a=n(13);n.d(t,"a",function(){return u});var u=function(e){function t(n){var r=e.call(this)||this;return r.name=n,r.data=null,r.surveyValue=null,r.conditionRunner=null,r.customWidgetData={isNeedRender:!0},r.visibleIf="",r.visibleValue=!0,r.startWithNewLineValue=!0,r.visibleIndexValue=-1,r.width="",r.renderWidthValue="",r.rightIndentValue=0,r.indentValue=0,r.localeChanged=new i.c,r.idValue=t.getQuestionId(),r.onCreating(),r}return r.b(t,e),t.getQuestionId=function(){return"sq_"+t.questionCounter++},Object.defineProperty(t.prototype,"isPanel",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visible",{get:function(){return this.visibleValue},set:function(e){e!=this.visible&&(this.visibleValue=e,this.fireCallback(this.visibilityChangedCallback),this.fireCallback(this.rowVisibilityChangedCallback),this.survey&&this.survey.questionVisibilityChanged(this,this.visible))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isVisible",{get:function(){return this.visible||this.survey&&this.survey.isDesignMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isReadOnly",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleIndex",{get:function(){return this.visibleIndexValue},enumerable:!0,configurable:!0}),t.prototype.hasErrors=function(e){return void 0===e&&(e=!0),!1},Object.defineProperty(t.prototype,"currentErrorCount",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasTitle",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasInput",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasComment",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"id",{get:function(){return this.idValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"startWithNewLine",{get:function(){return this.startWithNewLineValue},set:function(e){this.startWithNewLine!=e&&(this.startWithNewLineValue=e,this.startWithNewLineChangedCallback&&this.startWithNewLineChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cssClasses",{get:function(){var e=this.css,t={error:{}};return this.copyCssClasses(t,e.question),this.copyCssClasses(t.error,e.error),this.updateCssClasses(t,e),this.survey&&this.survey.updateQuestionCssClasses(this,t),t},enumerable:!0,configurable:!0}),t.prototype.getRootCss=function(e){return e.question.root},t.prototype.updateCssClasses=function(e,t){var n=t[this.getType()];if(void 0!==n&&null!==n)if("string"==typeof n||n instanceof String)e.root=n;else for(var r in n)e[r]=n[r]},t.prototype.copyCssClasses=function(e,t){if(t)if("string"==typeof t||t instanceof String)e.root=t;else for(var n in t)e[n]=t[n]},Object.defineProperty(t.prototype,"css",{get:function(){return a.b.getCss()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderWidth",{get:function(){return this.renderWidthValue},set:function(e){e!=this.renderWidth&&(this.renderWidthValue=e,this.fireCallback(this.renderWidthChangedCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"indent",{get:function(){return this.indentValue},set:function(e){e!=this.indent&&(this.indentValue=e,this.fireCallback(this.renderWidthChangedCallback))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightIndent",{get:function(){return this.rightIndentValue},set:function(e){e!=this.rightIndent&&(this.rightIndentValue=e,this.fireCallback(this.renderWidthChangedCallback))},enumerable:!0,configurable:!0}),t.prototype.focus=function(e){void 0===e&&(e=!1)},t.prototype.setData=function(e){this.data=e,e&&e.questionAdded&&(this.surveyValue=e),this.onSetData()},Object.defineProperty(t.prototype,"survey",{get:function(){return this.surveyValue},enumerable:!0,configurable:!0}),t.prototype.fireCallback=function(e){e&&e()},t.prototype.onSetData=function(){},t.prototype.onCreating=function(){},t.prototype.runCondition=function(e){this.visibleIf&&(this.conditionRunner||(this.conditionRunner=new s.a(this.visibleIf)),this.conditionRunner.expression=this.visibleIf,this.visible=this.conditionRunner.run(e))},t.prototype.onSurveyValueChanged=function(e){},t.prototype.onSurveyLoad=function(){this.fireCallback(this.surveyLoadCallback)},Object.defineProperty(t.prototype,"isLoadingFromJson",{get:function(){return this.survey&&this.survey.isLoadingFromJson},enumerable:!0,configurable:!0}),t.prototype.setVisibleIndex=function(e){this.visibleIndexValue!=e&&(this.visibleIndexValue=e,this.fireCallback(this.visibleIndexChangedCallback))},t.prototype.supportGoNextPageAutomatic=function(){return!1},t.prototype.clearUnusedValues=function(){},t.prototype.onLocaleChanged=function(){this.localeChanged.fire(this,this.getLocale())},t.prototype.onReadOnlyChanged=function(){},t.prototype.onAnyValueChanged=function(e){},t.prototype.getLocale=function(){return this.data?this.data.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},t}(i.b);u.questionCounter=100,o.a.metaData.addClass("questionbase",["!name",{name:"visible:boolean",default:!0},"visibleIf:expression",{name:"width"},{name:"startWithNewLine:boolean",default:!0},{name:"indent:number",default:0,choices:[0,1,2,3]}])},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.localeChangedHandler=function(e){return e.customWidgetData.isNeedRender=!0},n}return r.b(t,e),t.prototype._afterRender=function(){var e=this.refs.root;this.questionBase.customWidget&&(e=this.refs.widget)&&(this.questionBase.customWidget.afterRender(this.questionBase,e),this.questionBase.customWidgetData.isNeedRender=!1)},t.prototype.componentDidMount=function(){this.questionBase&&(this._afterRender(),this.questionBase.localeChanged.add(this.localeChangedHandler))},t.prototype.componentDidUpdate=function(){this.questionBase&&this._afterRender()},t.prototype.componentWillUnmount=function(){var e=this.refs.root;this.questionBase.customWidget&&(e=this.refs.widget)&&this.questionBase.customWidget.willUnmount(this.questionBase,e),this.questionBase.localeChanged.remove(this.localeChangedHandler)},t.prototype.render=function(){if(!this.questionBase||!this.creator)return null;if(!this.questionBase.visible)return null;var e=this.questionBase.customWidget;if(e.widgetJson.isDefaultRender)return i.createElement("div",{ref:"widget"},this.creator.createQuestionElement(this.questionBase));var t=null;if(e.widgetJson.render)t=e.widgetJson.render(this.questionBase);else if(e.htmlTemplate){var n={__html:e.htmlTemplate};return i.createElement("div",{ref:"widget",dangerouslySetInnerHTML:n})}return i.createElement("div",{ref:"widget"},t)},t}(o.b)},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(6),s=n(34),a=n(26),u=n(20),l=n(33),c=n(1),h=n(9),p=n(21),d=n(8);n.d(t,"a",function(){return f});var f=function(e){function t(t){void 0===t&&(t=null);var n=e.call(this)||this;n.surveyId=null,n.surveyPostId=null,n.surveyShowDataSaving=!1,n.clientId=null,n.cookieName=null,n.sendResultOnPageNext=!1,n.commentPrefix="-Comment",n.focusFirstQuestionAutomatic=!0,n.showNavigationButtons=!0,n.showTitle=!0,n.showPageTitles=!0,n.showCompletedPage=!0,n.requiredText="*",n.questionStartIndex="",n.showProgressBarValue="off",n.storeOthersAsComment=!0,n.goNextPageAutomatic=!1,n.pages=new Array,n.triggers=new Array,n.clearInvisibleValues=!1,n.currentPageValue=null,n.valuesHash={},n.variablesHash={},n.showPageNumbersValue=!1,n.showQuestionNumbersValue="on",n.questionTitleLocationValue="top",n.localeValue="",n.isCompleted=!1,n.isLoading=!1,n.processedTextValues={},n.isValidatingOnServerValue=!1,n.modeValue="edit",n.isDesignModeValue=!1,n.completedStateValue="",n.completedStateTextValue="",n.onComplete=new o.c,n.onPartialSend=new o.c,n.onCurrentPageChanged=new o.c,n.onValueChanged=new o.c,n.onVisibleChanged=new o.c,n.onPageVisibleChanged=new o.c,n.onQuestionAdded=new o.c,n.onQuestionRemoved=new o.c,n.onPanelAdded=new o.c,n.onPanelRemoved=new o.c,n.onValidateQuestion=new o.c,n.onProcessHtml=new o.c,n.onTextMarkdown=new o.c,n.onSendResult=new o.c,n.onGetResult=new o.c,n.onUploadFile=new o.c,n.onUpdateQuestionCssClasses=new o.c,n.onAfterRenderSurvey=new o.c,n.onAfterRenderPage=new o.c,n.onAfterRenderQuestion=new o.c,n.onAfterRenderPanel=new o.c,n.onMatrixRowAdded=new o.c,n.onMatrixCellCreated=new o.c,n.onMatrixCellValueChanged=new o.c,n.onMatrixCellValidate=new o.c,n.jsonErrors=null,n.isLoadingFromJsonValue=!1;var r=n;return n.locTitleValue=new d.a(n,!0),n.locTitleValue.onRenderedHtmlCallback=function(e){return r.processedTitle},n.locCompletedHtmlValue=new d.a(n),n.locPagePrevTextValue=new d.a(n),n.locPageNextTextValue=new d.a(n),n.locCompleteTextValue=new d.a(n),n.locQuestionTitleTemplateValue=new d.a(n,!0),n.textPreProcessor=new a.a,n.textPreProcessor.onHasValue=function(e){return r.hasProcessedTextValue(e)},n.textPreProcessor.onProcess=function(e){return r.getProcessedTextValue(e)},n.pages.push=function(e){return e.data=r,Array.prototype.push.call(this,e)},n.triggers.push=function(e){return e.setOwner(r),Array.prototype.push.call(this,e)},n.updateProcessedTextValues(),n.onBeforeCreating(),t&&(n.setJsonObject(t),n.surveyId&&n.loadSurveyFromService(n.surveyId)),n.onCreating(),n}return r.b(t,e),t.prototype.getType=function(){return"survey"},Object.defineProperty(t.prototype,"locale",{get:function(){return this.localeValue},set:function(e){this.localeValue=e,c.a.currentLocale=e;for(var t=0;t<this.pages.length;t++)this.pages[t].onLocaleChanged()},enumerable:!0,configurable:!0}),t.prototype.getLocale=function(){return this.locale},t.prototype.getMarkdownHtml=function(e){var t={text:e,html:null};return this.onTextMarkdown.fire(this,t),t.html},t.prototype.getLocString=function(e){return c.a.getString(e)},Object.defineProperty(t.prototype,"emptySurveyText",{get:function(){return this.getLocString("emptySurvey")},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"completedHtml",{get:function(){return this.locCompletedHtml.text},set:function(e){this.locCompletedHtml.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locCompletedHtml",{get:function(){return this.locCompletedHtmlValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pagePrevText",{get:function(){return this.locPagePrevText.text?this.locPagePrevText.text:this.getLocString("pagePrevText")},set:function(e){this.locPagePrevText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPagePrevText",{get:function(){return this.locPagePrevTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pageNextText",{get:function(){return this.locPageNextText.text?this.locPageNextText.text:this.getLocString("pageNextText")},set:function(e){this.locPageNextText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPageNextText",{get:function(){return this.locPageNextTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"completeText",{get:function(){return this.locCompleteText.text?this.locCompleteText.text:this.getLocString("completeText")},set:function(e){this.locCompleteText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locCompleteText",{get:function(){return this.locCompleteTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"questionTitleTemplate",{get:function(){return this.locQuestionTitleTemplate.text},set:function(e){this.locQuestionTitleTemplate.text=e},enumerable:!0,configurable:!0}),t.prototype.getQuestionTitleTemplate=function(){return this.locQuestionTitleTemplate.textOrHtml},Object.defineProperty(t.prototype,"locQuestionTitleTemplate",{get:function(){return this.locQuestionTitleTemplateValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"showPageNumbers",{get:function(){return this.showPageNumbersValue},set:function(e){e!==this.showPageNumbers&&(this.showPageNumbersValue=e,this.updateVisibleIndexes())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"showQuestionNumbers",{get:function(){return this.showQuestionNumbersValue},set:function(e){e=e.toLowerCase(),(e="onpage"===e?"onPage":e)!==this.showQuestionNumbers&&(this.showQuestionNumbersValue=e,this.updateVisibleIndexes())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"showProgressBar",{get:function(){return this.showProgressBarValue},set:function(e){this.showProgressBarValue=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"processedTitle",{get:function(){return this.processText(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"questionTitleLocation",{get:function(){return this.questionTitleLocationValue},set:function(e){(e=e.toLowerCase())!==this.questionTitleLocationValue&&(this.questionTitleLocationValue=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mode",{get:function(){return this.modeValue},set:function(e){if((e=e.toLowerCase())!=this.mode&&("edit"==e||"display"==e)){this.modeValue=e;for(var t=this.getAllQuestions(),n=0;n<t.length;n++)t[n].onReadOnlyChanged()}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"data",{get:function(){var e={};for(var t in this.valuesHash)e[t]=this.valuesHash[t];return e},set:function(e){if(this.valuesHash={},e)for(var t in e)this._setDataValue(e,t),this.checkTriggers(t,e[t],!1),this.processedTextValues[t.toLowerCase()]||(this.processedTextValues[t.toLowerCase()]="value");this.notifyAllQuestionsOnValueChanged(),this.runConditions()},enumerable:!0,configurable:!0}),t.prototype._setDataValue=function(e,t){this.valuesHash[t]=e[t]},Object.defineProperty(t.prototype,"comments",{get:function(){var e={};for(var t in this.valuesHash)t.indexOf(this.commentPrefix)>0&&(e[t]=this.valuesHash[t]);return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visiblePages",{get:function(){if(this.isDesignMode)return this.pages;for(var e=new Array,t=0;t<this.pages.length;t++)this.pages[t].isVisible&&e.push(this.pages[t]);return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isEmpty",{get:function(){return 0==this.pages.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"PageCount",{get:function(){return this.pageCount},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pageCount",{get:function(){return this.pages.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visiblePageCount",{get:function(){return this.visiblePages.length},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentPage",{get:function(){var e=this.visiblePages;return null!=this.currentPageValue&&e.indexOf(this.currentPageValue)<0&&(this.currentPage=null),null==this.currentPageValue&&e.length>0&&(this.currentPage=e[0]),this.currentPageValue},set:function(e){var t=this.visiblePages;if(!(null!=e&&t.indexOf(e)<0)&&e!=this.currentPageValue){var n=this.currentPageValue;this.currentPageValue=e,this.updateCustomWidgets(e),this.currentPageChanged(e,n)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentPageNo",{get:function(){return this.visiblePages.indexOf(this.currentPage)},set:function(e){this.visiblePages;e<0||e>=this.visiblePages.length||(this.currentPage=this.visiblePages[e])},enumerable:!0,configurable:!0}),t.prototype.focusFirstQuestion=function(){this.currentPageValue&&(this.currentPageValue.scrollToTop(),this.currentPageValue.focusFirstQuestion())},Object.defineProperty(t.prototype,"state",{get:function(){return this.isLoading?"loading":this.isCompleted?"completed":this.currentPage?"running":"empty"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"completedState",{get:function(){return this.completedStateValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"completedStateText",{get:function(){return this.completedStateTextValue},enumerable:!0,configurable:!0}),t.prototype.setCompletedState=function(e,t){this.completedStateValue=e,t||("saving"==e&&(t=this.getLocString("savingData")),"error"==e&&(t=this.getLocString("savingDataError")),"success"==e&&(t=this.getLocString("savingDataSuccess"))),this.completedStateTextValue=t},t.prototype.clear=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!0),e&&(this.data=null,this.variablesHash={}),this.isCompleted=!1,t&&this.visiblePageCount>0&&(this.currentPage=this.visiblePages[0])},t.prototype.mergeValues=function(e,t){if(t&&e)for(var n in e){var r=e[n];r&&"object"==typeof r?(t[n]||(t[n]={}),this.mergeValues(r,t[n])):t[n]=r}},t.prototype.updateCustomWidgets=function(e){if(e)for(var t=0;t<e.questions.length;t++)e.questions[t].customWidget=p.a.Instance.getCustomWidget(e.questions[t])},t.prototype.currentPageChanged=function(e,t){this.onCurrentPageChanged.fire(this,{oldCurrentPage:t,newCurrentPage:e})},t.prototype.getProgress=function(){if(null==this.currentPage)return 0;var e=this.visiblePages.indexOf(this.currentPage)+1;return Math.ceil(100*e/this.visiblePageCount)},Object.defineProperty(t.prototype,"isNavigationButtonsShowing",{get:function(){if(this.isDesignMode)return!1;var e=this.currentPage;return!!e&&("show"==e.navigationButtonsVisibility||"hide"!=e.navigationButtonsVisibility&&this.showNavigationButtons)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isEditMode",{get:function(){return"edit"==this.mode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDisplayMode",{get:function(){return"display"==this.mode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDesignMode",{get:function(){return this.isDesignModeValue},enumerable:!0,configurable:!0}),t.prototype.setDesignMode=function(e){this.isDesignModeValue=e},Object.defineProperty(t.prototype,"hasCookie",{get:function(){if(!this.cookieName)return!1;var e=document.cookie;return e&&e.indexOf(this.cookieName+"=true")>-1},enumerable:!0,configurable:!0}),t.prototype.setCookie=function(){this.cookieName&&(document.cookie=this.cookieName+"=true; expires=Fri, 31 Dec 9999 0:0:0 GMT")},t.prototype.deleteCookie=function(){this.cookieName&&(document.cookie=this.cookieName+"=;")},t.prototype.nextPage=function(){return!this.isLastPage&&((!this.isEditMode||!this.isCurrentPageHasErrors)&&(!this.doServerValidation()&&(this.doNextPage(),!0)))},Object.defineProperty(t.prototype,"isCurrentPageHasErrors",{get:function(){return null==this.currentPage||this.currentPage.hasErrors(!0,!0)},enumerable:!0,configurable:!0}),t.prototype.prevPage=function(){if(this.isFirstPage)return!1;var e=this.visiblePages,t=e.indexOf(this.currentPage);this.currentPage=e[t-1]},t.prototype.completeLastPage=function(){return(!this.isEditMode||!this.isCurrentPageHasErrors)&&(!this.doServerValidation()&&(this.doComplete(),!0))},Object.defineProperty(t.prototype,"isFirstPage",{get:function(){return null==this.currentPage||0==this.visiblePages.indexOf(this.currentPage)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isLastPage",{get:function(){if(null==this.currentPage)return!0;var e=this.visiblePages;return e.indexOf(this.currentPage)==e.length-1},enumerable:!0,configurable:!0}),t.prototype.doComplete=function(){var e=this.hasCookie;this.clearUnusedValues(),this.setCookie(),this.setCompleted();var t=this,n={showDataSaving:function(e){t.setCompletedState("saving",e)},showDataSavingError:function(e){t.setCompletedState("error",e)},showDataSavingSuccess:function(e){t.setCompletedState("success",e)},showDataSavingClear:function(e){t.setCompletedState("","")}};this.onComplete.fire(this,n),!e&&this.surveyPostId&&this.sendResult()},Object.defineProperty(t.prototype,"isValidatingOnServer",{get:function(){return this.isValidatingOnServerValue},enumerable:!0,configurable:!0}),t.prototype.setIsValidatingOnServer=function(e){e!=this.isValidatingOnServer&&(this.isValidatingOnServerValue=e,this.onIsValidatingOnServerChanged())},t.prototype.onIsValidatingOnServerChanged=function(){},t.prototype.doServerValidation=function(){if(!this.onServerValidateQuestions)return!1;for(var e=this,t={data:{},errors:{},survey:this,complete:function(){e.completeServerValidation(t)}},n=0;n<this.currentPage.questions.length;n++){var r=this.currentPage.questions[n];if(r.visible){var i=this.getValue(r.name);o.b.isValueEmpty(i)||(t.data[r.name]=i)}}return this.setIsValidatingOnServer(!0),this.onServerValidateQuestions(this,t),!0},t.prototype.completeServerValidation=function(e){if(this.setIsValidatingOnServer(!1),e||e.survey){var t=e.survey,n=!1;if(e.errors)for(var r in e.errors){var i=t.getQuestionByName(r);i&&i.errors&&(n=!0,i.addError(new h.c(e.errors[r])))}n||(t.isLastPage?t.doComplete():t.doNextPage())}},t.prototype.doNextPage=function(){this.checkOnPageTriggers(),this.sendResultOnPageNext&&this.sendResult(this.surveyPostId,this.clientId,!0);var e=this.visiblePages,t=e.indexOf(this.currentPage);this.currentPage=e[t+1]},t.prototype.setCompleted=function(){this.isCompleted=!0},Object.defineProperty(t.prototype,"processedCompletedHtml",{get:function(){return this.completedHtml?this.processHtml(this.completedHtml):"<h3>"+this.getLocString("completingSurvey")+"</h3>"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"processedLoadingHtml",{get:function(){return"<h3>"+this.getLocString("loadingSurvey")+"</h3>"},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"progressText",{get:function(){if(null==this.currentPage)return"";var e=this.visiblePages,t=e.indexOf(this.currentPage)+1;return this.getLocString("progressText").format(t,e.length)},enumerable:!0,configurable:!0}),t.prototype.afterRenderSurvey=function(e){this.onAfterRenderSurvey.fire(this,{survey:this,htmlElement:e})},t.prototype.updateQuestionCssClasses=function(e,t){this.onUpdateQuestionCssClasses.fire(this,{question:e,cssClasses:t})},t.prototype.afterRenderPage=function(e){this.onAfterRenderPage.isEmpty||this.onAfterRenderPage.fire(this,{page:this.currentPage,htmlElement:e})},t.prototype.afterRenderQuestion=function(e,t){this.onAfterRenderQuestion.fire(this,{question:e,htmlElement:t})},t.prototype.afterRenderPanel=function(e,t){this.onAfterRenderPanel.fire(this,{panel:e,htmlElement:t})},t.prototype.matrixRowAdded=function(e){this.onMatrixRowAdded.fire(this,{question:e})},t.prototype.matrixCellCreated=function(e,t){t.question=e,this.onMatrixCellCreated.fire(this,t)},t.prototype.matrixCellValueChanged=function(e,t){t.question=e,this.onMatrixCellValueChanged.fire(this,t)},t.prototype.matrixCellValidate=function(e,t){return t.question=e,this.onMatrixCellValidate.fire(this,t),t.error?new h.c(t.error):null},t.prototype.uploadFile=function(e,t,n,r){var i=!0;return this.onUploadFile.fire(this,{name:e,file:t,accept:i}),!!i&&(!n&&this.surveyPostId&&this.uploadFileCore(e,t,r),!0)},t.prototype.uploadFileCore=function(e,t,n){var r=this;n&&n("uploading"),(new l.a).sendFile(this.surveyPostId,t,function(t,i){n&&n(t?"success":"error"),t&&r.setValue(e,i)})},t.prototype.getPage=function(e){return this.pages[e]},t.prototype.addPage=function(e){null!=e&&(this.pages.push(e),this.updateVisibleIndexes())},t.prototype.addNewPage=function(e){var t=this.createNewPage(e);return this.addPage(t),t},t.prototype.removePage=function(e){var t=this.pages.indexOf(e);t<0||(this.pages.splice(t,1),this.currentPageValue==e&&(this.currentPage=this.pages.length>0?this.pages[0]:null),this.updateVisibleIndexes())},t.prototype.getQuestionByName=function(e,t){void 0===t&&(t=!1);var n=this.getAllQuestions();t&&(e=e.toLowerCase());for(var r=0;r<n.length;r++){var i=n[r].name;if(t&&(i=i.toLowerCase()),i==e)return n[r]}return null},t.prototype.getQuestionsByNames=function(e,t){void 0===t&&(t=!1);var n=[];if(!e)return n;for(var r=0;r<e.length;r++)if(e[r]){var i=this.getQuestionByName(e[r],t);i&&n.push(i)}return n},t.prototype.getPageByElement=function(e){for(var t=0;t<this.pages.length;t++){var n=this.pages[t];if(n.containsElement(e))return n}return null},t.prototype.getPageByQuestion=function(e){return this.getPageByElement(e)},t.prototype.getPageByName=function(e){for(var t=0;t<this.pages.length;t++)if(this.pages[t].name==e)return this.pages[t];return null},t.prototype.getPagesByNames=function(e){var t=[];if(!e)return t;for(var n=0;n<e.length;n++)if(e[n]){var r=this.getPageByName(e[n]);r&&t.push(r)}return t},t.prototype.getAllQuestions=function(e){void 0===e&&(e=!1);for(var t=new Array,n=0;n<this.pages.length;n++)this.pages[n].addQuestionsToList(t,e);return t},t.prototype.createNewPage=function(e){return new s.a(e)},t.prototype.notifyQuestionOnValueChanged=function(e,t){for(var n=this.getAllQuestions(),r=null,i=0;i<n.length;i++)n[i].name==e&&(r=n[i],this.doSurveyValueChanged(r,t),this.onValueChanged.fire(this,{name:e,question:r,value:t}));r||this.onValueChanged.fire(this,{name:e,question:null,value:t}),this.notifyQuestionsOnAnyValueOrVariableChanged(n,e)},t.prototype.notifyQuestionsOnAnyValueOrVariableChanged=function(e,t){e||(e=this.getAllQuestions());for(var n=0;n<e.length;n++)e[n].onAnyValueChanged(t)},t.prototype.notifyAllQuestionsOnValueChanged=function(){for(var e=this.getAllQuestions(),t=0;t<e.length;t++)this.doSurveyValueChanged(e[t],this.getValue(e[t].name))},t.prototype.doSurveyValueChanged=function(e,t){e.onSurveyValueChanged(t)},t.prototype.checkOnPageTriggers=function(){for(var e=this.getCurrentPageQuestions(),t=0;t<e.length;t++){var n=e[t],r=this.getValue(n.name);this.checkTriggers(n.name,r,!0)}},t.prototype.getCurrentPageQuestions=function(){var e=[],t=this.currentPage;if(!t)return e;for(var n=0;n<t.questions.length;n++){var r=t.questions[n];r.visible&&r.name&&e.push(r)}return e},t.prototype.checkTriggers=function(e,t,n){for(var r=0;r<this.triggers.length;r++){var i=this.triggers[r];i.name==e&&i.isOnNextPage==n&&i.check(t)}},t.prototype.doElementsOnLoad=function(){for(var e=0;e<this.pages.length;e++)this.pages[e].onSurveyLoad()},t.prototype.runConditions=function(){for(var e=this.pages,t=0;t<e.length;t++)e[t].runCondition(this.valuesHash)},t.prototype.sendResult=function(e,t,n){if(void 0===e&&(e=null),void 0===t&&(t=null),void 0===n&&(n=!1),this.isEditMode&&(n&&this.onPartialSend&&this.onPartialSend.fire(this,null),!e&&this.surveyPostId&&(e=this.surveyPostId),e&&(t&&(this.clientId=t),!n||this.clientId))){var r=this;this.surveyShowDataSaving&&this.setCompletedState("saving",""),(new l.a).sendResult(e,this.data,function(e,t){r.surveyShowDataSaving&&(e?r.setCompletedState("success",""):r.setCompletedState("error","")),r.onSendResult.fire(r,{success:e,response:t})},this.clientId,n)}},t.prototype.getResult=function(e,t){var n=this;(new l.a).getResult(e,t,function(e,t,r,i){n.onGetResult.fire(n,{success:e,data:t,dataList:r,response:i})})},t.prototype.loadSurveyFromService=function(e){void 0===e&&(e=null),e&&(this.surveyId=e);var t=this;this.isLoading=!0,this.onLoadingSurveyFromService(),(new l.a).loadSurvey(this.surveyId,function(e,n,r){t.isLoading=!1,e&&n&&(t.setJsonObject(n),t.notifyAllQuestionsOnValueChanged(),t.onLoadSurveyFromService())})},t.prototype.onLoadingSurveyFromService=function(){},t.prototype.onLoadSurveyFromService=function(){},t.prototype.checkPageVisibility=function(e,t){var n=this.getPageByQuestion(e);if(n){var r=n.isVisible;(r!=n.getIsPageVisible(e)||t)&&this.pageVisibilityChanged(n,r)}},t.prototype.updateVisibleIndexes=function(){if(this.updatePageVisibleIndexes(this.showPageNumbers),"onPage"==this.showQuestionNumbers)for(var e=this.visiblePages,t=0;t<e.length;t++)this.updateQuestionVisibleIndexes(e[t].questions,!0);else this.updateQuestionVisibleIndexes(this.getAllQuestions(!1),"on"==this.showQuestionNumbers)},t.prototype.updatePageVisibleIndexes=function(e){for(var t=0,n=0;n<this.pages.length;n++)this.pages[n].visibleIndex=this.pages[n].visible?t++:-1,this.pages[n].num=e&&this.pages[n].visible?this.pages[n].visibleIndex+1:-1},t.prototype.updateQuestionVisibleIndexes=function(e,t){for(var n=0,r=0;r<e.length;r++)e[r].setVisibleIndex(t&&e[r].visible&&e[r].hasTitle?n++:-1)},Object.defineProperty(t.prototype,"isLoadingFromJson",{get:function(){return this.isLoadingFromJsonValue},enumerable:!0,configurable:!0}),t.prototype.setJsonObject=function(e){if(e){this.jsonErrors=null,this.isLoadingFromJsonValue=!0;var t=new i.a;t.toObject(e,this),t.errors.length>0&&(this.jsonErrors=t.errors),this.runConditions(),this.updateVisibleIndexes(),this.updateProcessedTextValues(),this.isLoadingFromJsonValue=!1,this.hasCookie&&this.doComplete(),this.doElementsOnLoad()}},t.prototype.onBeforeCreating=function(){},t.prototype.onCreating=function(){},t.prototype.updateProcessedTextValues=function(){this.processedTextValues={};var e=this;this.processedTextValues.pageno=function(t){return null!=e.currentPage?e.visiblePages.indexOf(e.currentPage)+1:0},this.processedTextValues.pagecount=function(t){return e.visiblePageCount};for(var t=this.getAllQuestions(),n=0;n<t.length;n++)this.addQuestionToProcessedTextValues(t[n])},t.prototype.addQuestionToProcessedTextValues=function(e){this.processedTextValues[e.name.toLowerCase()]="question"},t.prototype.hasProcessedTextValue=function(e){var t=(new u.a).getFirstName(e);return this.processedTextValues[t.toLowerCase()]},t.prototype.getProcessedTextValue=function(e){var t=(new u.a).getFirstName(e),n=this.processedTextValues[t.toLowerCase()];if(!n)return null;if("variable"==n)return this.getVariable(e.toLowerCase());if("question"==n){var r=this.getQuestionByName(t,!0);return r?(e=r.name+e.substr(t.length),(new u.a).getValue(e,this.valuesHash)):null}return"value"==n?(new u.a).getValue(e,this.valuesHash):n(e)},t.prototype.clearUnusedValues=function(){for(var e=this.getAllQuestions(),t=0;t<e.length;t++)e[t].clearUnusedValues();this.clearInvisibleValues&&this.clearInvisibleQuestionValues()},t.prototype.clearInvisibleQuestionValues=function(){for(var e=this.getAllQuestions(),t=0;t<e.length;t++)e[t].visible||this.clearValue(e[t].name)},t.prototype.getVariable=function(e){return e?this.variablesHash[e]:null},t.prototype.setVariable=function(e,t){e&&(this.variablesHash[e]=t,this.processedTextValues[e.toLowerCase()]="variable",this.notifyQuestionsOnAnyValueOrVariableChanged(null,e))},t.prototype.getUnbindValue=function(e){return e&&e instanceof Object?JSON.parse(JSON.stringify(e)):e},t.prototype.getValue=function(e){if(!e||0==e.length)return null;var t=this.valuesHash[e];return this.getUnbindValue(t)},t.prototype.setValue=function(e,t){this.isValueEqual(e,t)||(""===t||null===t?delete this.valuesHash[e]:(t=this.getUnbindValue(t),this.valuesHash[e]=t,this.processedTextValues[e.toLowerCase()]="value"),this.notifyQuestionOnValueChanged(e,t),this.checkTriggers(e,t,!1),this.runConditions(),this.tryGoNextPageAutomatic(e))},t.prototype.isValueEqual=function(e,t){""==t&&(t=null);var n=this.getValue(e);return null===t||null===n?t===n:this.isTwoValueEquals(t,n)},t.prototype.tryGoNextPageAutomatic=function(e){if(this.goNextPageAutomatic&&this.currentPage){var t=this.getQuestionByName(e);if(!t||t.visible&&t.supportGoNextPageAutomatic()){for(var n=this.getCurrentPageQuestions(),r=0;r<n.length;r++){var i=this.getValue(n[r].name);if(n[r].hasInput&&o.b.isValueEmpty(i))return}this.currentPage.hasErrors(!0,!1)||(this.isLastPage?this.completeLastPage():this.nextPage())}}},t.prototype.getComment=function(e){var t=this.data[e+this.commentPrefix];return null==t&&(t=""),t},t.prototype.setComment=function(e,t){var n=e+this.commentPrefix;""===t||null===t?delete this.valuesHash[n]:(this.valuesHash[n]=t,this.tryGoNextPageAutomatic(e));var r=this.getQuestionByName(e);r&&this.onValueChanged.fire(this,{name:n,question:r,value:t})},t.prototype.clearValue=function(e){this.setValue(e,null),this.setComment(e,null)},t.prototype.questionVisibilityChanged=function(e,t){this.updateVisibleIndexes(),this.onVisibleChanged.fire(this,{question:e,name:e.name,visible:t}),this.checkPageVisibility(e,!t)},t.prototype.pageVisibilityChanged=function(e,t){this.updateVisibleIndexes(),this.onPageVisibleChanged.fire(this,{page:e,visible:t})},t.prototype.questionAdded=function(e,t,n,r){this.updateVisibleIndexes(),this.addQuestionToProcessedTextValues(e),this.onQuestionAdded.fire(this,{question:e,name:e.name,index:t,parentPanel:n,rootPanel:r})},t.prototype.questionRemoved=function(e){this.updateVisibleIndexes(),this.onQuestionRemoved.fire(this,{question:e,name:e.name})},t.prototype.panelAdded=function(e,t,n,r){this.updateVisibleIndexes(),this.onPanelAdded.fire(this,{panel:e,name:e.name,index:t,parentPanel:n,rootPanel:r})},t.prototype.panelRemoved=function(e){this.updateVisibleIndexes(),this.onPanelRemoved.fire(this,{panel:e,name:e.name})},t.prototype.validateQuestion=function(e){if(this.onValidateQuestion.isEmpty)return null;var t={name:e,value:this.getValue(e),error:null};return this.onValidateQuestion.fire(this,t),t.error?new h.c(t.error):null},t.prototype.processHtml=function(e){var t={html:e};return this.onProcessHtml.fire(this,t),this.processText(t.html)},t.prototype.processText=function(e){return this.textPreProcessor.process(e)},t.prototype.processTextEx=function(e){var t={text:this.textPreProcessor.process(e),hasAllValuesOnLastRun:!0};return t.hasAllValuesOnLastRun=this.textPreProcessor.hasAllValuesOnLastRun,t},t.prototype.getObjects=function(e,t){var n=[];return Array.prototype.push.apply(n,this.getPagesByNames(e)),Array.prototype.push.apply(n,this.getQuestionsByNames(t)),n},t.prototype.setTriggerValue=function(e,t,n){e&&(n?this.setVariable(e,t):this.setValue(e,t))},t}(o.b);i.a.metaData.addClass("survey",[{name:"locale",choices:function(){return c.a.getLocales()}},{name:"title",serializationProperty:"locTitle"},{name:"focusFirstQuestionAutomatic:boolean",default:!0},{name:"completedHtml:html",serializationProperty:"locCompletedHtml"},{name:"pages",className:"page",visible:!1},{name:"questions",alternativeName:"elements",baseClassName:"question",visible:!1,onGetValue:function(e){return null},onSetValue:function(e,t,n){var r=e.addNewPage("");n.toObject({questions:t},r)}},{name:"triggers:triggers",baseClassName:"surveytrigger",classNamePart:"trigger"},{name:"surveyId",visible:!1},{name:"surveyPostId",visible:!1},{name:"surveyShowDataSaving",visible:!1},"cookieName","sendResultOnPageNext:boolean",{name:"showNavigationButtons:boolean",default:!0},{name:"showTitle:boolean",default:!0},{name:"showPageTitles:boolean",default:!0},{name:"showCompletedPage:boolean",default:!0},"showPageNumbers:boolean",{name:"showQuestionNumbers",default:"on",choices:["on","onPage","off"]},{name:"questionTitleLocation",default:"top",choices:["top","bottom"]},{name:"showProgressBar",default:"off",choices:["off","top","bottom"]},{name:"mode",default:"edit",choices:["edit","display"]},{name:"storeOthersAsComment:boolean",default:!0},"goNextPageAutomatic:boolean","clearInvisibleValues:boolean",{name:"pagePrevText",serializationProperty:"locPagePrevText"},{name:"pageNextText",serializationProperty:"locPageNextText"},{name:"completeText",serializationProperty:"locCompleteText"},{name:"requiredText",default:"*"},"questionStartIndex",{name:"questionTitleTemplate",serializationProperty:"locQuestionTitleTemplate"}])},function(e,t,n){"use strict";n.d(t,"a",function(){return i});var r=function(){function e(){}return e}(),i=function(){function e(){this.hasAllValuesOnLastRunValue=!1}return e.prototype.process=function(e){if(this.hasAllValuesOnLastRunValue=!0,!e)return e;if(!this.onProcess)return e;for(var t=this.getItems(e),n=t.length-1;n>=0;n--){var r=t[n],i=this.getName(e.substring(r.start+1,r.end));if(this.canProcessName(i))if(!this.onHasValue||this.onHasValue(i)){var o=this.onProcess(i);null==o&&(o="",this.hasAllValuesOnLastRunValue=!1),e=e.substr(0,r.start)+o+e.substr(r.end+1)}else this.hasAllValuesOnLastRunValue=!1}return e},Object.defineProperty(e.prototype,"hasAllValuesOnLastRun",{get:function(){return this.hasAllValuesOnLastRunValue},enumerable:!0,configurable:!0}),e.prototype.getItems=function(e){for(var t=[],n=e.length,i=-1,o="",s=0;s<n;s++)if(o=e[s],"{"==o&&(i=s),"}"==o){if(i>-1){var a=new r;a.start=i,a.end=s,t.push(a)}i=-1}return t},e.prototype.getName=function(e){if(e)return e.trim()},e.prototype.canProcessName=function(e){if(!e)return!1;for(var t=0;t<e.length;t++){var n=e[t];if(" "==n||"-"==n||"&"==n)return!1}return!0},e}()},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(9),s=n(1),a=n(2);n.d(t,"h",function(){return u}),n.d(t,"f",function(){return l}),n.d(t,"a",function(){return c}),n.d(t,"d",function(){return h}),n.d(t,"g",function(){return p}),n.d(t,"b",function(){return d}),n.d(t,"e",function(){return f}),n.d(t,"c",function(){return m});var u=function(){function e(e,t){void 0===t&&(t=null),this.value=e,this.error=t}return e}(),l=function(e){function t(){var t=e.call(this)||this;return t.text="",t}return r.b(t,e),t.prototype.getErrorText=function(e){return this.text?this.text:this.getDefaultErrorText(e)},t.prototype.getDefaultErrorText=function(e){return""},t.prototype.validate=function(e,t){return void 0===t&&(t=null),null},t}(i.b),c=function(){function e(){}return e.prototype.run=function(e){for(var t=0;t<e.validators.length;t++){var n=e.validators[t].validate(e.value,e.getValidatorTitle());if(null!=n){if(n.error)return n.error;n.value&&(e.value=n.value)}}return null},e}(),h=function(e){function t(t,n){void 0===t&&(t=null),void 0===n&&(n=null);var r=e.call(this)||this;return r.minValue=t,r.maxValue=n,r}return r.b(t,e),t.prototype.getType=function(){return"numericvalidator"},t.prototype.validate=function(e,t){if(void 0===t&&(t=null),!this.isNumber(e))return new u(null,new o.b);var n=new u(parseFloat(e));return null!==this.minValue&&this.minValue>n.value?(n.error=new o.c(this.getErrorText(t)),n):null!==this.maxValue&&this.maxValue<n.value?(n.error=new o.c(this.getErrorText(t)),n):"number"==typeof e?null:n},t.prototype.getDefaultErrorText=function(e){var t=e||"value";return null!==this.minValue&&null!==this.maxValue?s.a.getString("numericMinMax").format(t,this.minValue,this.maxValue):null!==this.minValue?s.a.getString("numericMin").format(t,this.minValue):s.a.getString("numericMax").format(t,this.maxValue)},t.prototype.isNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},t}(l),p=function(e){function t(t,n){void 0===t&&(t=0),void 0===n&&(n=0);var r=e.call(this)||this;return r.minLength=t,r.maxLength=n,r}return r.b(t,e),t.prototype.getType=function(){return"textvalidator"},t.prototype.validate=function(e,t){return void 0===t&&(t=null),this.minLength>0&&e.length<this.minLength?new u(null,new o.c(this.getErrorText(t))):this.maxLength>0&&e.length>this.maxLength?new u(null,new o.c(this.getErrorText(t))):null},t.prototype.getDefaultErrorText=function(e){return this.minLength>0&&this.maxLength>0?s.a.getString("textMinMaxLength").format(this.minLength,this.maxLength):this.minLength>0?s.a.getString("textMinLength").format(this.minLength):s.a.getString("textMaxLength").format(this.maxLength)},t}(l),d=function(e){function t(t,n){void 0===t&&(t=null),void 0===n&&(n=null);var r=e.call(this)||this;return r.minCount=t,r.maxCount=n,r}return r.b(t,e),t.prototype.getType=function(){return"answercountvalidator"},t.prototype.validate=function(e,t){if(void 0===t&&(t=null),null==e||e.constructor!=Array)return null;var n=e.length;return this.minCount&&n<this.minCount?new u(null,new o.c(this.getErrorText(s.a.getString("minSelectError").format(this.minCount)))):this.maxCount&&n>this.maxCount?new u(null,new o.c(this.getErrorText(s.a.getString("maxSelectError").format(this.maxCount)))):null},t.prototype.getDefaultErrorText=function(e){return e},t}(l),f=function(e){function t(t){void 0===t&&(t=null);var n=e.call(this)||this;return n.regex=t,n}return r.b(t,e),t.prototype.getType=function(){return"regexvalidator"},t.prototype.validate=function(e,t){return void 0===t&&(t=null),this.regex&&e?new RegExp(this.regex).test(e)?null:new u(e,new o.c(this.getErrorText(t))):null},t}(l),m=function(e){function t(){var t=e.call(this)||this;return t.re=/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i,t}return r.b(t,e),t.prototype.getType=function(){return"emailvalidator"},t.prototype.validate=function(e,t){return void 0===t&&(t=null),e?this.re.test(e)?null:new u(e,new o.c(this.getErrorText(t))):null},t.prototype.getDefaultErrorText=function(e){return s.a.getString("invalidEmail")},t}(l);a.a.metaData.addClass("surveyvalidator",["text"]),a.a.metaData.addClass("numericvalidator",["minValue:number","maxValue:number"],function(){return new h},"surveyvalidator"),a.a.metaData.addClass("textvalidator",["minLength:number","maxLength:number"],function(){return new p},"surveyvalidator"),a.a.metaData.addClass("answercountvalidator",["minCount:number","maxCount:number"],function(){return new d},"surveyvalidator"),a.a.metaData.addClass("regexvalidator",["regex"],function(){return new f},"surveyvalidator"),a.a.metaData.addClass("emailvalidator",[],function(){return new m},"surveyvalidator")},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(16)),s=n(31),a=n(29),u=n(5),l=n(13),c=n(30),h=n(6),p=n(4);n.d(t,"a",function(){return d});var d=function(e){function t(t){var n=e.call(this,t)||this;return n.isCurrentPageChanged=!1,n.handleTryAgainClick=n.handleTryAgainClick.bind(n),n.updateSurvey(t),n}return r.b(t,e),Object.defineProperty(t,"cssType",{get:function(){return l.b.currentType},set:function(e){l.b.currentType=e},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(e){this.updateSurvey(e)},t.prototype.componentDidUpdate=function(){this.isCurrentPageChanged&&(this.isCurrentPageChanged=!1,this.survey.focusFirstQuestionAutomatic&&this.survey.focusFirstQuestion())},t.prototype.componentDidMount=function(){var e=this.refs.root;e&&this.survey&&this.survey.doAfterRenderSurvey(e)},t.prototype.render=function(){return"completed"==this.survey.state?this.renderCompleted():"loading"==this.survey.state?this.renderLoading():this.renderSurvey()},Object.defineProperty(t.prototype,"css",{get:function(){return l.b.getCss()},set:function(e){this.survey.mergeCss(e,this.css)},enumerable:!0,configurable:!0}),t.prototype.handleTryAgainClick=function(e){this.survey.doComplete()},t.prototype.renderCompleted=function(){if(!this.survey.showCompletedPage)return null;var e=null;if(this.survey.completedState){var t=null;if("error"==this.survey.completedState){var n=this.survey.getLocString("saveAgainButton");t=i.createElement("input",{type:"button",value:n,className:this.css.saveData.saveAgainButton,onClick:this.handleTryAgainClick})}var r=this.css.saveData[this.survey.completedState];e=i.createElement("div",{className:this.css.saveData.root},i.createElement("div",{className:r},i.createElement("span",null,this.survey.completedStateText),t))}var o={__html:this.survey.processedCompletedHtml};return i.createElement("div",null,i.createElement("div",{dangerouslySetInnerHTML:o}),e)},t.prototype.renderLoading=function(){var e={__html:this.survey.processedLoadingHtml};return i.createElement("div",{dangerouslySetInnerHTML:e})},t.prototype.renderSurvey=function(){var e=this.survey.title&&this.survey.showTitle?this.renderTitle():null,t=this.survey.currentPage?this.renderPage():null,n="top"==this.survey.showProgressBar?this.renderProgress(!0):null,r="bottom"==this.survey.showProgressBar?this.renderProgress(!1):null,o=t&&this.survey.showNavigationButtons?this.renderNavigation():null;return t||(t=this.renderEmptySurvey()),i.createElement("div",{ref:"root",className:this.css.root},e,i.createElement("div",{id:h.e,className:this.css.body},n,t,r),o)},t.prototype.renderTitle=function(){var e=p.a.renderLocString(this.survey.locTitle);return i.createElement("div",{className:this.css.header},i.createElement("h3",null,e))},t.prototype.renderPage=function(){return i.createElement(s.a,{survey:this.survey,page:this.survey.currentPage,css:this.css,creator:this})},t.prototype.renderProgress=function(e){return i.createElement(c.a,{survey:this.survey,css:this.css,isTop:e})},t.prototype.renderNavigation=function(){return i.createElement(a.a,{survey:this.survey,css:this.css})},t.prototype.renderEmptySurvey=function(){return i.createElement("span",null,this.survey.emptySurveyText)},t.prototype.updateSurvey=function(e){e?e.model?this.survey=e.model:e.json&&(this.survey=new o.a(e.json)):this.survey=new o.a,e&&(e.clientId&&(this.survey.clientId=e.clientId),e.data&&(this.survey.data=e.data),e.css&&this.survey.mergeCss(e.css,this.css));this.survey.currentPage;this.state={pageIndexChange:0,isCompleted:!1,modelChanged:0},this.setSurveyEvents(e)},t.prototype.setSurveyEvents=function(e){var t=this;this.survey.renderCallback=function(){t.state.modelChanged=t.state.modelChanged+1,t.setState(t.state)},this.survey.onComplete.add(function(e){t.state.isCompleted=!0,t.setState(t.state)}),this.survey.onPartialSend.add(function(e){t.setState(t.state)}),this.survey.onCurrentPageChanged.add(function(n,r){t.isCurrentPageChanged=!0,t.state.pageIndexChange=t.state.pageIndexChange+1,t.setState(t.state),e&&e.onCurrentPageChanged&&e.onCurrentPageChanged(n,r)}),this.survey.onVisibleChanged.add(function(e,t){if(t.question&&t.question.react){var n=t.question.react.state;n.visible=t.question.visible,t.question.react.setState(n)}}),this.survey.onValueChanged.add(function(e,t){if(t.question&&t.question.react){var n=t.question.react.state;n.value=t.value,t.question.react.setState(n)}}),e&&(this.survey.onValueChanged.add(function(t,n){e.data&&(e.data[n.name]=n.value),e.onValueChanged&&e.onValueChanged(t,n)}),e.onVisibleChanged&&this.survey.onVisibleChanged.add(function(t){e.onVisibleChanged(t)}),e.onComplete&&this.survey.onComplete.add(function(t,n){e.onComplete(t,n)}),e.onPartialSend&&this.survey.onPartialSend.add(function(t){e.onPartialSend(t)}),this.survey.onPageVisibleChanged.add(function(t,n){e.onPageVisibleChanged&&e.onPageVisibleChanged(t,n)}),e.onServerValidateQuestions&&(this.survey.onServerValidateQuestions=e.onServerValidateQuestions),e.onQuestionAdded&&this.survey.onQuestionAdded.add(function(t,n){e.onQuestionAdded(t,n)}),e.onQuestionRemoved&&this.survey.onQuestionRemoved.add(function(t,n){e.onQuestionRemoved(t,n)}),e.onValidateQuestion&&this.survey.onValidateQuestion.add(function(t,n){e.onValidateQuestion(t,n)}),e.onSendResult&&this.survey.onSendResult.add(function(t,n){e.onSendResult(t,n)}),e.onGetResult&&this.survey.onGetResult.add(function(t,n){e.onGetResult(t,n)}),e.onProcessHtml&&this.survey.onProcessHtml.add(function(t,n){e.onProcessHtml(t,n)}),e.onAfterRenderSurvey&&this.survey.onAfterRenderSurvey.add(function(t,n){e.onAfterRenderSurvey(t,n)}),e.onAfterRenderPage&&this.survey.onAfterRenderPage.add(function(t,n){e.onAfterRenderPage(t,n)}),e.onAfterRenderQuestion&&this.survey.onAfterRenderQuestion.add(function(t,n){e.onAfterRenderQuestion(t,n)}),e.onTextMarkdown&&this.survey.onTextMarkdown.add(function(t,n){e.onTextMarkdown(t,n)}),e.onMatrixRowAdded&&this.survey.onMatrixRowAdded.add(function(t,n){e.onMatrixRowAdded(t,n)}),e.onMatrixCellCreated&&this.survey.onMatrixCellCreated.add(function(t,n){e.onMatrixCellCreated(t,n)}),e.onMatrixCellValueChanged&&this.survey.onMatrixCellValueChanged.add(function(t,n){e.onMatrixCellValueChanged(t,n)}))},t.prototype.createQuestionElement=function(e){return u.a.Instance.createQuestion(e.getType(),{question:e,isDisplayMode:e.isReadOnly,creator:this})},t.prototype.renderError=function(e,t,n){return i.createElement("div",{key:e,className:n.error.item},t)},t.prototype.questionTitleLocation=function(){return this.survey.questionTitleLocation},t}(i.Component)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(18));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.handlePrevClick=n.handlePrevClick.bind(n),n.handleNextClick=n.handleNextClick.bind(n),n.handleCompleteClick=n.handleCompleteClick.bind(n),n}return r.b(t,e),t.prototype.handlePrevClick=function(e){this.survey.prevPage()},t.prototype.handleNextClick=function(e){this.survey.nextPage()},t.prototype.handleCompleteClick=function(e){this.survey.completeLastPage()},t.prototype.render=function(){if(!this.survey||!this.survey.isNavigationButtonsShowing)return null;var e=this.survey.isFirstPage?null:this.renderButton(this.handlePrevClick,this.survey.pagePrevText,this.css.navigation.prev),t=this.survey.isLastPage?null:this.renderButton(this.handleNextClick,this.survey.pageNextText,this.css.navigation.next),n=this.survey.isLastPage&&this.survey.isEditMode?this.renderButton(this.handleCompleteClick,this.survey.completeText,this.css.navigation.complete):null;return i.createElement("div",{className:this.css.footer},e,t,n)},t.prototype.renderButton=function(e,t,n){var r={marginRight:"5px"},o=this.css.navigationButton+(n?" "+n:"");return i.createElement("input",{className:o,style:r,type:"button",onClick:e,value:t})},t}(o.a)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(18));n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this,t)||this;return n.isTop=t.isTop,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.isTop=t.isTop},Object.defineProperty(t.prototype,"progress",{get:function(){return this.survey.getProgress()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"progressText",{get:function(){return this.survey.progressText},enumerable:!0,configurable:!0}),t.prototype.render=function(){var e=this.isTop?{width:"60%"}:{width:"60%",marginTop:"10px"},t={width:"auto",minWidth:this.progress+"%",paddingLeft:"2px",paddingRight:"2px"};return i.createElement("div",{className:this.css.progress,style:e},i.createElement("div",{style:t,className:this.css.progressBar,role:"progressbar","aria-valuemin":"0","aria-valuemax":"100"},i.createElement("span",null,this.progressText)))},t}(o.a)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(15)),s=n(4);n.d(t,"a",function(){return a}),n.d(t,"b",function(){return l});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.page=t.page,n.survey=t.survey,n.creator=t.creator,n.css=t.css,n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.page=e.page,this.survey=e.survey,this.creator=e.creator,this.css=e.css},t.prototype.componentDidMount=function(){var e=this.refs.root;e&&this.survey&&this.survey.afterRenderPage(e)},t.prototype.render=function(){if(null==this.page||null==this.survey||null==this.creator)return null;for(var e=this.renderTitle(),t=[],n=this.page.rows,r=0;r<n.length;r++)t.push(this.createRow(n[r],r));return i.createElement("div",{ref:"root"},e,t)},t.prototype.createRow=function(e,t){var n="row"+(t+1);return i.createElement(l,{key:n,row:e,survey:this.survey,creator:this.creator,css:this.css})},t.prototype.renderTitle=function(){if(!this.page.title||!this.survey.showPageTitles)return null;var e=s.a.renderLocString(this.page.locTitle);return i.createElement("h4",{className:this.css.pageTitle},e)},t}(i.Component),u=function(e){function t(t){var n=e.call(this,t)||this;return n.panel=t.panel,n.survey=t.survey,n.creator=t.creator,n.css=t.css,n.state={modelChanged:0},n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.panel=e.panel,this.survey=e.survey,this.creator=e.creator,this.css=e.css},t.prototype.componentDidMount=function(){var e=this,t=this.refs.root;t&&this.survey&&this.survey.afterRenderPage(t),this.panel.panelVisibilityChanged=function(t,n){e.state.modelChanged=e.state.modelChanged+1,e.setState(e.state)}},t.prototype.render=function(){if(null==this.panel||null==this.survey||null==this.creator)return null;for(var e=this.renderTitle(),t=[],n=this.panel.rows,r=0;r<n.length;r++)t.push(this.createRow(n[r],r));var o={paddingLeft:this.panel.innerIndent*this.css.question.indent+"px"},s={verticalAlign:"top",display:this.panel.isVisible?"inline-block":"none"};return this.panel.renderWidth&&(s.width=this.panel.renderWidth),i.createElement("div",{ref:"root",style:s},e,i.createElement("div",{style:o},t))},t.prototype.createRow=function(e,t){var n="row"+(t+1);return i.createElement(l,{key:n,row:e,survey:this.survey,creator:this.creator,css:this.css})},t.prototype.renderTitle=function(){if(!this.panel.title)return null;var e=s.a.renderLocString(this.panel.locTitle);return i.createElement("h4",{className:this.css.pageTitle},e)},t}(i.Component),l=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(e){this.setProperties(e)},t.prototype.setProperties=function(e){if(this.row=e.row,this.row){var t=this;this.row.visibilityChangedCallback=function(){t.setState({visible:t.row.visible})}}this.survey=e.survey,this.creator=e.creator,this.css=e.css},t.prototype.render=function(){if(null==this.row||null==this.survey||null==this.creator)return null;var e=null;if(this.row.visible){e=[];for(var t=0;t<this.row.elements.length;t++){var n=this.row.elements[t];e.push(this.createQuestion(n))}}var r=this.row.visible?{}:{display:"none"};return i.createElement("div",{className:this.css.row,style:r},e)},t.prototype.createQuestion=function(e){return e.isPanel?i.createElement(u,{key:e.name,panel:e,creator:this.creator,survey:this.survey,css:this.css}):i.createElement(o.a,{key:e.name,question:e,creator:this.creator,css:this.css})},t}(i.Component)},function(e,t,n){"use strict";var r=n(17);n.d(t,"a",function(){return i});var i=function(){function e(){}return e.prototype.parse=function(e,t){return this.text=e,this.root=t,this.root.clear(),this.at=0,this.length=this.text.length,this.parseText()},e.prototype.toString=function(e){return this.root=e,this.nodeToString(e)},e.prototype.toStringCore=function(e){return e?e.children?this.nodeToString(e):e.left?this.conditionToString(e):"":""},e.prototype.nodeToString=function(e){if(e.isEmpty)return"";for(var t="",n=0;n<e.children.length;n++){var r=this.toStringCore(e.children[n]);r&&(t&&(t+=" "+e.connective+" "),t+=r)}return e!=this.root&&e.children.length>1&&(t="("+t+")"),t},e.prototype.conditionToString=function(e){if(!e.right||!e.operator)return"";var t=e.left;t&&!this.isNumeric(t)&&(t="'"+t+"'");var n=t+" "+this.operationToString(e.operator);if(this.isNoRightOperation(e.operator))return n;var r=e.right;return r&&!this.isNumeric(r)&&(r="'"+r+"'"),n+" "+r},e.prototype.operationToString=function(e){return"equal"==e?"=":"notequal"==e?"!=":"greater"==e?">":"less"==e?"<":"greaterorequal"==e?">=":"lessorequal"==e?"<=":e},e.prototype.isNumeric=function(e){var t=parseFloat(e);return!isNaN(t)&&isFinite(t)},e.prototype.parseText=function(){return this.node=this.root,this.expressionNodes=[],this.expressionNodes.push(this.node),this.readConditions()&&this.at>=this.length},e.prototype.readConditions=function(){var e=this.readCondition();if(!e)return e;var t=this.readConnective();return!t||(this.addConnective(t),this.readConditions())},e.prototype.readCondition=function(){var e=this.readExpression();if(e<0)return!1;if(1==e)return!0;var t=this.readString();if(!t)return!1;var n=this.readOperator();if(!n)return!1;var i=new r.b;if(i.left=t,i.operator=n,!this.isNoRightOperation(n)){var o=this.readString();if(!o)return!1;i.right=o}return this.addCondition(i),!0},e.prototype.readExpression=function(){if(this.skip(),this.at>=this.length||"("!=this.ch)return 0;this.at++,this.pushExpression();var e=this.readConditions();return e?(this.skip(),e=")"==this.ch,this.at++,this.popExpression(),1):-1},Object.defineProperty(e.prototype,"ch",{get:function(){return this.text.charAt(this.at)},enumerable:!0,configurable:!0}),e.prototype.skip=function(){for(;this.at<this.length&&this.isSpace(this.ch);)this.at++},e.prototype.isSpace=function(e){return" "==e||"\n"==e||"\t"==e||"\r"==e},e.prototype.isQuotes=function(e){return"'"==e||'"'==e},e.prototype.isOperatorChar=function(e){return">"==e||"<"==e||"="==e||"!"==e},e.prototype.isBrackets=function(e){return"("==e||")"==e},e.prototype.readString=function(){if(this.skip(),this.at>=this.length)return null;var e=this.at,t=this.isQuotes(this.ch);t&&this.at++;for(var n=this.isOperatorChar(this.ch);this.at<this.length&&(t||!this.isSpace(this.ch));){if(this.isQuotes(this.ch)){t&&this.at++;break}if(!t){if(n!=this.isOperatorChar(this.ch))break;if(this.isBrackets(this.ch))break}this.at++}if(this.at<=e)return null;var r=this.text.substr(e,this.at-e);if(r&&r.length>1&&this.isQuotes(r[0])){var i=r.length-1;this.isQuotes(r[r.length-1])&&i--,r=r.substr(1,i)}return r},e.prototype.isNoRightOperation=function(e){return"empty"==e||"notempty"==e},e.prototype.readOperator=function(){var e=this.readString();return e?(e=e.toLowerCase(),">"==e&&(e="greater"),"<"==e&&(e="less"),">="!=e&&"=>"!=e||(e="greaterorequal"),"<="!=e&&"=<"!=e||(e="lessorequal"),"="!=e&&"=="!=e||(e="equal"),"<>"!=e&&"!="!=e||(e="notequal"),"contain"==e&&(e="contains"),"notcontain"==e&&(e="notcontains"),e):null},e.prototype.readConnective=function(){var e=this.readString();return e?(e=e.toLowerCase(),"&"!=e&&"&&"!=e||(e="and"),"|"!=e&&"||"!=e||(e="or"),"and"!=e&&"or"!=e&&(e=null),e):null},e.prototype.pushExpression=function(){var e=new r.c;this.expressionNodes.push(e),this.node=e},e.prototype.popExpression=function(){var e=this.expressionNodes.pop();this.node=this.expressionNodes[this.expressionNodes.length-1],this.node.children.push(e)},e.prototype.addCondition=function(e){this.node.children.push(e)},e.prototype.addConnective=function(e){if(this.node.children.length<2)this.node.connective=e;else if(this.node.connective!=e){var t=this.node.connective,n=this.node.children;this.node.clear(),this.node.connective=e;var i=new r.c;i.connective=t,i.children=n,this.node.children.push(i);var o=new r.c;this.node.children.push(o),this.node=o}},e}()},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r=function(){function e(){}return e.prototype.loadSurvey=function(t,n){var r=new XMLHttpRequest;r.open("GET",e.serviceUrl+"/getSurvey?surveyId="+t),r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.onload=function(){var e=JSON.parse(r.response);n(200==r.status,e,r.response)},r.send()},e.prototype.sendResult=function(t,n,r,i,o){void 0===i&&(i=null),void 0===o&&(o=!1);var s=new XMLHttpRequest;s.open("POST",e.serviceUrl+"/post/"),s.setRequestHeader("Content-Type","application/json; charset=utf-8");var a={postId:t,surveyResult:JSON.stringify(n)};i&&(a.clientId=i),o&&(a.isPartialCompleted=!0);var u=JSON.stringify(a);s.onload=s.onerror=function(){r&&r(200==s.status,s.response)},s.send(u)},e.prototype.sendFile=function(t,n,r){var i=new XMLHttpRequest;i.onload=i.onerror=function(){r&&r(200==i.status,JSON.parse(i.response))},i.open("POST",e.serviceUrl+"/upload/",!0);var o=new FormData;o.append("file",n),o.append("postId",t),i.send(o)},e.prototype.getResult=function(t,n,r){var i=new XMLHttpRequest,o="resultId="+t+"&name="+n;i.open("GET",e.serviceUrl+"/getResult?"+o),i.setRequestHeader("Content-Type","application/x-www-form-urlencoded");i.onload=function(){var e=null,t=null;if(200==i.status){e=JSON.parse(i.response),t=[];for(var n in e.QuestionResult){var o={name:n,value:e.QuestionResult[n]};t.push(o)}}r(200==i.status,e,t,i.response)},i.send()},e.prototype.isCompleted=function(t,n,r){var i=new XMLHttpRequest,o="resultId="+t+"&clientId="+n;i.open("GET",e.serviceUrl+"/isCompleted?"+o),i.setRequestHeader("Content-Type","application/x-www-form-urlencoded");i.onload=function(){var e=null;200==i.status&&(e=JSON.parse(i.response)),r(200==i.status,e,i.response)},i.send()},e}();r.serviceUrl="https://dxsurveyapi.azurewebsites.net/api/Survey"},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(6),s=n(35);n.d(t,"a",function(){return a});var a=function(e){function t(t){void 0===t&&(t="");var n=e.call(this,t)||this;return n.name=t,n.numValue=-1,n.navigationButtonsVisibilityValue="inherit",n.visibleIndex=-1,n}return r.b(t,e),t.prototype.getType=function(){return"page"},Object.defineProperty(t.prototype,"num",{get:function(){return this.numValue},set:function(e){this.numValue!=e&&(this.numValue=e,this.onNumChanged(e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"navigationButtonsVisibility",{get:function(){return this.navigationButtonsVisibilityValue},set:function(e){this.navigationButtonsVisibilityValue=e.toLowerCase()},enumerable:!0,configurable:!0}),t.prototype.getRendredTitle=function(t){return t=e.prototype.getRendredTitle.call(this,t),this.num>0&&(t=this.num+". "+t),t},t.prototype.focusFirstQuestion=function(){for(var e=0;e<this.questions.length;e++){var t=this.questions[e];if(t.visible&&t.hasInput){this.questions[e].focus();break}}},t.prototype.focusFirstErrorQuestion=function(){for(var e=0;e<this.questions.length;e++)if(this.questions[e].visible&&0!=this.questions[e].currentErrorCount){this.questions[e].focus(!0);break}},t.prototype.scrollToTop=function(){o.a.ScrollElementToTop(o.e)},t.prototype.onNumChanged=function(e){},t.prototype.onVisibleChanged=function(){e.prototype.onVisibleChanged.call(this),null!=this.data&&this.data.pageVisibilityChanged(this,this.visible)},t}(s.a);i.a.metaData.addClass("page",[{name:"navigationButtonsVisibility",default:"inherit",choices:["inherit","show","hide"]}],function(){return new a},"panel")},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(6),s=n(17),a=n(7),u=n(8);n.d(t,"c",function(){return l}),n.d(t,"a",function(){return c}),n.d(t,"b",function(){return h});var l=function(){function e(e){this.panel=e,this.elements=[],this.visibleValue=e.data&&e.data.isDesignMode}return Object.defineProperty(e.prototype,"questions",{get:function(){return this.elements},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"visible",{get:function(){return this.visibleValue},set:function(e){e!=this.visible&&(this.visibleValue=e,this.onVisibleChanged())},enumerable:!0,configurable:!0}),e.prototype.updateVisible=function(){this.visible=this.calcVisible(),this.setWidth()},e.prototype.addElement=function(e){this.elements.push(e),this.updateVisible()},e.prototype.onVisibleChanged=function(){this.visibilityChangedCallback&&this.visibilityChangedCallback()},e.prototype.setWidth=function(){var e=this.getVisibleCount();if(0!=e)for(var t=0,n=0;n<this.elements.length;n++)if(this.elements[n].isVisible){var r=this.elements[n];r.renderWidth=r.width?r.width:Math.floor(100/e)+"%",r.rightIndent=t<e-1?1:0,t++}},e.prototype.getVisibleCount=function(){for(var e=0,t=0;t<this.elements.length;t++)this.elements[t].isVisible&&e++;return e},e.prototype.calcVisible=function(){return this.getVisibleCount()>0},e}(),c=function(e){function t(n){void 0===n&&(n="");var r=e.call(this)||this;r.name=n,r.dataValue=null,r.rowValues=null,r.conditionRunner=null,r.elementsValue=new Array,r.isQuestionsReady=!1,r.questionsValue=new Array,r.parent=null,r.visibleIf="",r.visibleValue=!0,r.idValue=t.getPanelId(),r.locTitleValue=new u.a(r,!0);var i=r;return r.locTitleValue.onRenderedHtmlCallback=function(e){return i.getRendredTitle(e)},r.elementsValue.push=function(e){return i.doOnPushElement(this,e)},r.elementsValue.splice=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return i.doSpliceElements.apply(i,[this,e,t].concat(n))},r}return r.b(t,e),t.getPanelId=function(){return"sp_"+t.panelCounter++},Object.defineProperty(t.prototype,"data",{get:function(){return this.dataValue},set:function(e){if(this.dataValue!==e){this.dataValue=e,e&&e.isDesignMode&&this.onVisibleChanged();for(var t=0;t<this.elements.length;t++)this.elements[t].setData(e)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),t.prototype.getLocale=function(){return this.data?this.data.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},Object.defineProperty(t.prototype,"id",{get:function(){return this.idValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isPanel",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"questions",{get:function(){if(!this.isQuestionsReady){this.questionsValue=[];for(var e=0;e<this.elements.length;e++){var t=this.elements[e];if(t.isPanel)for(var n=t.questions,r=0;r<n.length;r++)this.questionsValue.push(n[r]);else this.questionsValue.push(t)}this.isQuestionsReady=!0}return this.questionsValue},enumerable:!0,configurable:!0}),t.prototype.markQuestionListDirty=function(){this.isQuestionsReady=!1,this.parent&&this.parent.markQuestionListDirty()},Object.defineProperty(t.prototype,"elements",{get:function(){return this.elementsValue},enumerable:!0,configurable:!0}),t.prototype.containsElement=function(e){for(var t=0;t<this.elements.length;t++){var n=this.elements[t];if(n==e)return!0;if(n.isPanel&&n.containsElement(e))return!0}return!1},t.prototype.hasErrors=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!1);var n=!1,r=null,i=[];this.addQuestionsToList(i,!0);for(var o=0;o<i.length;o++){var s=i[o];s.isReadOnly||s.hasErrors(e)&&(t&&null==r&&(r=s),n=!0)}return r&&r.focus(!0),n},t.prototype.addQuestionsToList=function(e,t){if(void 0===t&&(t=!1),!t||this.visible)for(var n=0;n<this.elements.length;n++){var r=this.elements[n];t&&!r.visible||(r.isPanel?r.addQuestionsToList(e,t):e.push(r))}},Object.defineProperty(t.prototype,"rows",{get:function(){return this.rowValues||(this.rowValues=this.buildRows()),this.rowValues},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isActive",{get:function(){return!this.data||this.data.currentPage==this.root},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){for(var e=this;e.parent;)e=e.parent;return e},enumerable:!0,configurable:!0}),t.prototype.createRow=function(){return new l(this)},t.prototype.onSurveyLoad=function(){for(var e=0;e<this.elements.length;e++)this.elements[e].onSurveyLoad();this.rowsChangedCallback&&this.rowsChangedCallback()},Object.defineProperty(t.prototype,"isLoadingFromJson",{get:function(){return this.data&&this.data.isLoadingFromJson},enumerable:!0,configurable:!0}),t.prototype.onRowsChanged=function(){this.rowValues=null,this.rowsChangedCallback&&!this.isLoadingFromJson&&this.rowsChangedCallback()},Object.defineProperty(t.prototype,"isDesignMode",{get:function(){return this.data&&this.data.isDesignMode},enumerable:!0,configurable:!0}),t.prototype.doOnPushElement=function(e,t){var n=Array.prototype.push.call(e,t);return this.markQuestionListDirty(),this.onAddElement(t,e.length),this.onRowsChanged(),n},t.prototype.doSpliceElements=function(e,t,n){for(var r=[],i=3;i<arguments.length;i++)r[i-3]=arguments[i];t||(t=0),n||(n=0);for(var o=[],s=0;s<n;s++)s+t>=e.length||o.push(e[s+t]);var a=(u=Array.prototype.splice).call.apply(u,[e,t,n].concat(r));this.markQuestionListDirty(),r||(r=[]);for(var s=0;s<o.length;s++)this.onRemoveElement(o[s]);for(var s=0;s<r.length;s++)this.onAddElement(r[s],t+s);return this.onRowsChanged(),a;var u},t.prototype.onAddElement=function(e,t){if(e.isPanel){var n=e;n.data=this.data,n.parent=this,this.data&&this.data.panelAdded(n,t,this,this.root)}else if(this.data){var r=e;r.setData(this.data),this.data.questionAdded(r,t,this,this.root)}var i=this;e.rowVisibilityChangedCallback=function(){i.onElementVisibilityChanged(e)},e.startWithNewLineChangedCallback=function(){i.onElementStartWithNewLineChanged(e)}},t.prototype.onRemoveElement=function(e){e.isPanel?this.data&&this.data.panelRemoved(e):this.data&&this.data.questionRemoved(e)},t.prototype.onElementVisibilityChanged=function(e){this.rowValues&&this.updateRowsVisibility(e),this.parent&&this.parent.onElementVisibilityChanged(this)},t.prototype.onElementStartWithNewLineChanged=function(e){this.onRowsChanged()},t.prototype.updateRowsVisibility=function(e){for(var t=0;t<this.rowValues.length;t++){var n=this.rowValues[t];if(n.elements.indexOf(e)>-1){n.updateVisible();break}}},t.prototype.buildRows=function(){for(var e=new Array,t=0;t<this.elements.length;t++){var n=this.elements[t],r=0==t||n.startWithNewLine,i=r?this.createRow():e[e.length-1];r&&e.push(i),i.addElement(n)}for(var t=0;t<e.length;t++)e[t].updateVisible();return e},Object.defineProperty(t.prototype,"processedTitle",{get:function(){return this.getRendredTitle(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),t.prototype.getRendredTitle=function(e){return!e&&this.isPanel&&this.isDesignMode?"["+this.name+"]":null!=this.data?this.data.processText(e):e},Object.defineProperty(t.prototype,"visible",{get:function(){return this.visibleValue},set:function(e){e!==this.visible&&(this.visibleValue=e,this.isLoadingFromJson||this.onVisibleChanged(),this.panelVisibilityChanged(this,this.visible))},enumerable:!0,configurable:!0}),t.prototype.panelVisibilityChanged=function(e,t){},t.prototype.onVisibleChanged=function(){},Object.defineProperty(t.prototype,"isVisible",{get:function(){return this.data&&this.data.isDesignMode||this.getIsPageVisible(null)},enumerable:!0,configurable:!0}),t.prototype.getIsPageVisible=function(e){if(!this.visible)return!1;for(var t=0;t<this.questions.length;t++)if(this.questions[t]!=e&&this.questions[t].visible)return!0;return!1},t.prototype.addElement=function(e,t){void 0===t&&(t=-1),null!=e&&(t<0||t>=this.elements.length?this.elements.push(e):this.elements.splice(t,0,e))},t.prototype.addQuestion=function(e,t){void 0===t&&(t=-1),this.addElement(e,t)},t.prototype.addPanel=function(e,t){void 0===t&&(t=-1),this.addElement(e,t)},t.prototype.addNewQuestion=function(e,t){var n=a.a.Instance.createQuestion(e,t);return this.addQuestion(n),n},t.prototype.addNewPanel=function(e){var t=this.createNewPanel(e);return this.addPanel(t),t},t.prototype.createNewPanel=function(e){return new h(e)},t.prototype.removeElement=function(e){var t=this.elements.indexOf(e);if(t<0){for(var n=0;n<this.elements.length;n++){var r=this.elements[n];if(r.isPanel&&r.removeElement(e))return!0}return!1}return this.elements.splice(t,1),!0},t.prototype.removeQuestion=function(e){this.removeElement(e)},t.prototype.runCondition=function(e){for(var t=0;t<this.elements.length;t++)this.elements[t].runCondition(e);this.visibleIf&&(this.conditionRunner||(this.conditionRunner=new s.a(this.visibleIf)),this.conditionRunner.expression=this.visibleIf,this.visible=this.conditionRunner.run(e))},t.prototype.onLocaleChanged=function(){for(var e=0;e<this.elements.length;e++)this.elements[e].onLocaleChanged();this.locTitle.onChanged()},t}(o.b);c.panelCounter=100;var h=function(e){function t(t){void 0===t&&(t="");var n=e.call(this,t)||this;return n.name=t,n.innerIndentValue=0,n.startWithNewLineValue=!0,n}return r.b(t,e),t.prototype.getType=function(){return"panel"},t.prototype.setData=function(e){this.data=e},Object.defineProperty(t.prototype,"isPanel",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"innerIndent",{get:function(){return this.innerIndentValue},set:function(e){e!=this.innerIndentValue&&(this.innerIndentValue=e,this.renderWidthChangedCallback&&this.renderWidthChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderWidth",{get:function(){return this.renderWidthValue},set:function(e){e!=this.renderWidth&&(this.renderWidthValue=e,this.renderWidthChangedCallback&&this.renderWidthChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"startWithNewLine",{get:function(){return this.startWithNewLineValue},set:function(e){this.startWithNewLine!=e&&(this.startWithNewLineValue=e,this.startWithNewLineChangedCallback&&this.startWithNewLineChangedCallback())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightIndent",{get:function(){return this.rightIndentValue},set:function(e){e!=this.rightIndent&&(this.rightIndentValue=e,this.renderWidthChangedCallback&&this.renderWidthChangedCallback())},enumerable:!0,configurable:!0}),t.prototype.onVisibleChanged=function(){this.rowVisibilityChangedCallback&&this.rowVisibilityChangedCallback()},t}(c);i.a.metaData.addClass("panel",["name",{name:"elements",alternativeName:"questions",baseClassName:"question",visible:!1},{name:"startWithNewLine:boolean",default:!0},{name:"visible:boolean",default:!0},"visibleIf:expression",{name:"title:text",serializationProperty:"locTitle"},{name:"innerIndent:number",default:0,choices:[0,1,2,3]}],function(){return new h})},function(e,t,n){"use strict";var r=n(13);n.d(t,"a",function(){return i});var i={root:"",header:"panel-heading",body:"panel-body",footer:"panel-footer",navigationButton:"",navigation:{complete:"sv_complete_btn",prev:"sv_prev_btn",next:"sv_next_btn"},progress:"progress center-block",progressBar:"progress-bar",pageTitle:"",row:"",question:{mainRoot:"",title:"",comment:"form-control",required:"",titleRequired:"",indent:20},error:{root:"alert alert-danger",icon:"glyphicon glyphicon-exclamation-sign",item:""},checkbox:{root:"form-inline",item:"checkbox",other:""},comment:"form-control",dropdown:{root:"",control:"form-control",other:""},matrix:{root:"table"},matrixdropdown:{root:"table"},matrixdynamic:{root:"table",button:"button"},multipletext:{root:"table",itemTitle:"",itemValue:"form-control"},radiogroup:{root:"form-inline",item:"radio",label:"",other:""},rating:{root:"btn-group",item:"btn btn-default"},text:"form-control",saveData:{root:"",saving:"alert alert-info",error:"alert alert-danger",success:"alert alert-success",saveAgainButton:""},window:{root:"modal-content",body:"modal-body",header:{root:"modal-header panel-title",title:"pull-left",button:"glyphicon pull-right",buttonExpanded:"glyphicon pull-right glyphicon-chevron-up",buttonCollapsed:"glyphicon pull-right glyphicon-chevron-down"}}};r.b.bootstrap=i},function(e,t,n){"use strict";var r=n(13);n.d(t,"a",function(){return i});var i={root:"",header:"panel-heading",body:"panel-body",footer:"panel-footer",navigationButton:"",navigation:{complete:"sv_complete_btn",prev:"sv_prev_btn",next:"sv_next_btn"},progress:"progress center-block",progressBar:"progress-bar",pageTitle:"",row:"",question:{mainRoot:"form-group",title:"",comment:"form-control",required:"",titleRequired:"",indent:20},error:{root:"alert alert-danger",icon:"glyphicon glyphicon-exclamation-sign",item:""},checkbox:{root:"form-inline",item:"checkbox",other:""},comment:"form-control",dropdown:{root:"",control:"form-control",other:""},matrix:{root:"table",row:"form-group",label:"radio-inline",itemValue:"form-control"},matrixdropdown:{root:"table",itemValue:"form-group"},matrixdynamic:{root:"table",button:"button"},multipletext:{root:"table",itemTitle:"",row:"form-group",itemValue:"form-control"},radiogroup:{root:"form-inline",item:"radio-inline",label:"radio-inline",other:""},rating:{root:"btn-group",item:"btn btn-default"},text:"form-control",saveData:{root:"",saving:"alert alert-info",error:"alert alert-danger",success:"alert alert-success",saveAgainButton:""},window:{root:"modal-content",body:"modal-body",header:{root:"modal-header panel-title",title:"pull-left",button:"glyphicon pull-right",buttonExpanded:"glyphicon pull-right glyphicon-chevron-up",buttonCollapsed:"glyphicon pull-right glyphicon-chevron-down"}}};r.b.bootstrapmaterial=i},function(e,t,n){"use strict";n(53),n(54),n(55),n(56),n(57),n(58),n(59),n(60),n(61),n(62),n(63),n(64),n(65),n(66),n(67),n(68),n(69),n(70)},function(e,t,n){"use strict";var r=n(52),i=(n.n(r),n(27));n.d(t,"b",function(){return i.b}),n.d(t,"c",function(){return i.c}),n.d(t,"d",function(){return i.d}),n.d(t,"e",function(){return i.e}),n.d(t,"f",function(){return i.f}),n.d(t,"g",function(){return i.g}),n.d(t,"h",function(){return i.h}),n.d(t,"i",function(){return i.a});var o=n(6);n.d(t,"j",function(){return o.b}),n.d(t,"k",function(){return o.c}),n.d(t,"l",function(){return o.d});var s=n(11);n.d(t,"m",function(){return s.a});var a=n(8);n.d(t,"n",function(){return a.a});var u=n(19);n.d(t,"o",function(){return u.a});var l=n(17);n.d(t,"p",function(){return l.b}),n.d(t,"q",function(){return l.c}),n.d(t,"r",function(){return l.a});var c=n(32);n.d(t,"s",function(){return c.a});var h=n(20);n.d(t,"t",function(){return h.a});var p=n(9);n.d(t,"u",function(){return p.c}),n.d(t,"v",function(){return p.d}),n.d(t,"w",function(){return p.b});var d=n(2);n.d(t,"x",function(){return d.b}),n.d(t,"y",function(){return d.c}),n.d(t,"z",function(){return d.d}),n.d(t,"A",function(){return d.e}),n.d(t,"B",function(){return d.f}),n.d(t,"C",function(){return d.g}),n.d(t,"D",function(){return d.a}),n.d(t,"E",function(){return d.h}),n.d(t,"F",function(){return d.i}),n.d(t,"G",function(){return d.j});var f=n(22);n.d(t,"H",function(){return f.a}),n.d(t,"I",function(){return f.b}),n.d(t,"J",function(){return f.c}),n.d(t,"K",function(){return f.d});var m=n(77);n.d(t,"L",function(){return m.a}),n.d(t,"M",function(){return m.b});var g=n(78);n.d(t,"N",function(){return g.a}),n.d(t,"O",function(){return g.b});var y=n(76);n.d(t,"P",function(){return y.a}),n.d(t,"Q",function(){return y.b});var v=n(79);n.d(t,"R",function(){return v.a}),n.d(t,"S",function(){return v.b});var b=n(35);n.d(t,"T",function(){return b.b}),n.d(t,"U",function(){return b.a}),n.d(t,"V",function(){return b.c});var C=n(34);n.d(t,"W",function(){return C.a});var w=n(10);n.d(t,"X",function(){return w.a});var x=n(23);n.d(t,"Y",function(){return x.a});var V=n(14);n.d(t,"Z",function(){return V.a}),n.d(t,"_0",function(){return V.b});var P=n(71);n.d(t,"_1",function(){return P.a});var T=n(72);n.d(t,"_2",function(){return T.a});var O=n(73);n.d(t,"_3",function(){return O.a});var R=n(7);n.d(t,"_4",function(){return R.a}),n.d(t,"_5",function(){return R.b});var q=n(74);n.d(t,"_6",function(){return q.a});var S=n(75);n.d(t,"_7",function(){return S.a});var E=n(80);n.d(t,"_8",function(){return E.a});var k=n(81);n.d(t,"_9",function(){return k.a});var N=n(82);n.d(t,"_10",function(){return N.a});var j=n(25);n.d(t,"_11",function(){return j.a});var M=n(84);n.d(t,"_12",function(){return M.a}),n.d(t,"_13",function(){return M.b}),n.d(t,"_14",function(){return M.c}),n.d(t,"_15",function(){return M.d}),n.d(t,"_16",function(){return M.e});var I=n(83);n.d(t,"_17",function(){return I.a});var L=n(26);n.d(t,"_18",function(){return L.a});var A=n(33);n.d(t,"_19",function(){return A.a});var D=n(1);n.d(t,"_20",function(){return D.a}),n.d(t,"_21",function(){return D.b});var Q=n(21);n.d(t,"_22",function(){return Q.b}),n.d(t,"_23",function(){return Q.a}),n.d(t,"a",function(){return B});var B;B="0.12.19"},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(28)),s=n(4);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.handleOnExpanded=n.handleOnExpanded.bind(n),n}return r.b(t,e),t.prototype.handleOnExpanded=function(e){this.state.expanded=!this.state.expanded,this.setState(this.state)},t.prototype.render=function(){if(this.state.hidden)return null;var e=this.renderHeader(),t=this.state.expanded?this.renderBody():null,n={position:"fixed",bottom:"3px",right:"10px"};return i.createElement("div",{className:this.css.window.root,style:n},e,t)},t.prototype.renderHeader=function(){var e={width:"100%"},t={paddingRight:"10px"},n=this.state.expanded?this.css.window.header.buttonCollapsed:this.css.window.header.buttonExpanded;n="glyphicon pull-right "+n;var r=s.a.renderLocString(this.survey.locTitle);return i.createElement("div",{className:this.css.window.header.root},i.createElement("a",{href:"#",onClick:this.handleOnExpanded,style:e},i.createElement("span",{className:this.css.window.header.title,style:t},r),i.createElement("span",{className:n,"aria-hidden":"true"})))},t.prototype.renderBody=function(){return i.createElement("div",{className:this.css.window.body},this.renderSurvey())},t.prototype.updateSurvey=function(t){e.prototype.updateSurvey.call(this,t);var n=!!t.expanded&&t.expanded;this.state={expanded:n,hidden:!1};var r=this;this.survey.onComplete.add(function(e){r.state.hidden=!0,r.setState(r.state)})},t}(o.a)},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5);n.d(t,"a",function(){return u}),n.d(t,"b",function(){return l});var u=function(e){function t(t){var n=e.call(this,t)||this;n.state={choicesChanged:0};var r=n;return n.question.choicesChangedCallback=function(){r.state.choicesChanged=r.state.choicesChanged+1,r.setState(r.state)},n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;var e=this.question.cssClasses;return i.createElement("div",{className:e.root},this.getItems(e))},t.prototype.getItems=function(e){for(var t=[],n=0;n<this.question.visibleChoices.length;n++){var r=this.question.visibleChoices[n],i="item"+n;t.push(this.renderItem(i,r,0==n,e))}return t},Object.defineProperty(t.prototype,"textStyle",{get:function(){return null},enumerable:!0,configurable:!0}),t.prototype.renderItem=function(e,t,n,r){return i.createElement(l,{key:e,question:this.question,cssClasses:r,isDisplayMode:this.isDisplayMode,item:t,textStyle:this.textStyle,isFirst:n})},t}(o.b),l=function(e){function t(t){var n=e.call(this,t)||this;return n.item=t.item,n.question=t.question,n.textStyle=t.textStyle,n.isFirst=t.isFirst,n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),t.prototype.shouldComponentUpdate=function(){return!this.question.customWidget||!!this.question.customWidgetData.isNeedRender||!!this.question.customWidget.widgetJson.render},t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.item=t.item,this.textStyle=t.textStyle,this.question=t.question,this.isFirst=t.isFirst},t.prototype.handleOnChange=function(e){var t=this.question.value;t||(t=[]);var n=t.indexOf(this.item.value);e.target.checked?n<0&&t.push(this.item.value):n>-1&&t.splice(n,1),this.question.value=t,this.setState({value:this.question.value})},t.prototype.render=function(){if(!this.item||!this.question)return null;var e=this.question.colCount>0?100/this.question.colCount+"%":"",t=0==this.question.colCount?"5px":"0px",n={marginRight:t,display:"inline-block"};e&&(n.width=e);var r=this.question.value&&this.question.value.indexOf(this.item.value)>-1||!1,i=this.item.value===this.question.otherItem.value&&r?this.renderOther():null;return this.renderCheckbox(r,n,i)},Object.defineProperty(t.prototype,"inputStyle",{get:function(){return{marginRight:"3px"}},enumerable:!0,configurable:!0}),t.prototype.renderCheckbox=function(e,t,n){var r=this.isFirst?this.question.inputId:null,o=this.renderLocString(this.item.locText);return i.createElement("div",{className:this.cssClasses.item,style:t},i.createElement("label",{className:this.cssClasses.item},i.createElement("input",{type:"checkbox",value:this.item.value,id:r,style:this.inputStyle,disabled:this.isDisplayMode,checked:e,onChange:this.handleOnChange}),i.createElement("span",{className:"checkbox-material",style:{marginRight:"5px"}},i.createElement("span",{className:"check"})),i.createElement("span",null,o)),n)},t.prototype.renderOther=function(){return i.createElement("div",{className:this.cssClasses.other},i.createElement(s.a,{question:this.question,otherCss:this.cssClasses.other,cssClasses:this.cssClasses,isDisplayMode:this.isDisplayMode}))},t}(o.c);a.a.Instance.registerQuestion("checkbox",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5),u=n(85);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;n.state={value:n.question.value||"",choicesChanged:0};var r=n;return n.question.choicesChangedCallback=function(){r.state.choicesChanged=r.state.choicesChanged+1,r.setState(r.state)},n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.state.value=this.question.value||""},t.prototype.handleOnChange=function(e){this.question.value=e.target.value,this.setState({value:this.question.value||""})},t.prototype.render=function(){if(!this.question)return null;var e=this.question.cssClasses,t=this.question.value===this.question.otherItem.value?this.renderOther(e):null,n=this.renderSelect(e);return i.createElement("div",{className:e.root},n,t)},t.prototype.renderSelect=function(e){if(this.isDisplayMode)return i.createElement("div",{id:this.question.inputId,className:e.control},this.question.value);for(var t=[],r=0;r<this.question.visibleChoices.length;r++){var o=this.question.visibleChoices[r],s="item"+r,a=i.createElement("option",{key:s,value:o.value,selected:this.state.value==o.value},o.text);t.push(a)}var l=null;return(u.a.msie||u.a.firefox&&n.i(u.b)(u.a.version,"51")<0)&&(l=this.handleOnChange),i.createElement("select",{id:this.question.inputId,className:e.control,value:this.state.value,onChange:l,onInput:this.handleOnChange},i.createElement("option",{value:""},this.question.optionsCaption),t)},t.prototype.renderOther=function(e){var t={marginTop:"3px"};return i.createElement("div",{style:t},i.createElement(s.a,{question:this.question,otherCss:e.other,cssClasses:e,isDisplayMode:this.isDisplayMode}))},t}(o.b);a.a.Instance.registerQuestion("dropdown",function(e){return i.createElement(l,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.state={fileLoaded:0},n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.handleOnChange=function(e){var t=e.target||e.srcElement;window.FileReader&&(!t||!t.files||t.files.length<1||(this.question.loadFile(t.files[0]),this.setState({fileLoaded:this.state.fileLoaded+1})))},t.prototype.render=function(){if(!this.question)return null;var e=this.renderImage(),t=null;return this.isDisplayMode||(t=i.createElement("input",{id:this.question.inputId,type:"file",onChange:this.handleOnChange})),i.createElement("div",null,t,e)},t.prototype.renderImage=function(){return this.question.previewValue?i.createElement("div",null," ",i.createElement("img",{src:this.question.previewValue,height:this.question.imageHeight,width:this.question.imageWidth})):null},t}(o.b);s.a.Instance.registerQuestion("file",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a});var a=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question||!this.question.html)return null;var e={__html:this.question.processedHtml};return i.createElement("div",{dangerouslySetInnerHTML:e})},t}(o.b);s.a.Instance.registerQuestion("html",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a}),n.d(t,"b",function(){return u});var a=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.cssClasses,t=this.question.hasRows?i.createElement("th",null):null,n=[],r=0;r<this.question.columns.length;r++){var o=this.question.columns[r],s="column"+r,a=this.renderLocString(o.locText);n.push(i.createElement("th",{key:s},a))}for(var l=[],c=this.question.visibleRows,r=0;r<c.length;r++){var h=c[r],s="row"+r;l.push(i.createElement(u,{key:s,question:this.question,cssClasses:e,isDisplayMode:this.isDisplayMode,row:h,isFirst:0==r}))}return i.createElement("table",{className:e.root},i.createElement("thead",null,i.createElement("tr",null,t,n)),i.createElement("tbody",null,l))},t}(o.b),u=function(e){function t(t){var n=e.call(this,t)||this;return n.question=t.question,n.row=t.row,n.isFirst=t.isFirst,n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),t.prototype.handleOnChange=function(e){this.row.value=e.target.value,this.setState({value:this.row.value})},t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.question=t.question,this.row=t.row,this.isFirst=t.isFirst},t.prototype.render=function(){if(!this.row)return null;var e=null;if(this.question.hasRows){var t=this.renderLocString(this.row.locText);e=i.createElement("td",null,t)}for(var n=[],r=0;r<this.question.columns.length;r++){var o=this.question.columns[r],s="value"+r,a=this.row.value==o.value,u=this.isFirst&&0==r?this.question.inputId:null,l={margin:"0",position:"absolute"},c=i.createElement("td",{key:s},i.createElement("label",{className:this.cssClasses.label,style:l},i.createElement("input",{id:u,type:"radio",className:this.cssClasses.itemValue,name:this.row.fullName,value:o.value,disabled:this.isDisplayMode,checked:a,onChange:this.handleOnChange}),i.createElement("span",{className:"circle"}),i.createElement("span",{className:"check"})));n.push(c)}return i.createElement("tr",null,e,n)},t}(o.c);s.a.Instance.registerQuestion("matrix",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(15),a=n(5),u=n(24);n.d(t,"a",function(){return l}),n.d(t,"b",function(){return c});var l=function(e){function t(t){return e.call(this,t)||this}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.cssClasses,t=[],n=0;n<this.question.columns.length;n++){var r=this.question.columns[n],o="column"+n,s=this.question.getColumnWidth(r),a=s?{minWidth:s}:{},u=this.renderLocString(r.locTitle);t.push(i.createElement("th",{key:o,style:a},u))}for(var l=[],h=this.question.visibleRows,n=0;n<h.length;n++){var p=h[n];l.push(i.createElement(c,{key:n,row:p,cssClasses:e,isDisplayMode:this.isDisplayMode,creator:this.creator}))}var d=this.question.horizontalScroll?{overflowX:"scroll"}:{};return i.createElement("div",{style:d},i.createElement("table",{className:e.root},i.createElement("thead",null,i.createElement("tr",null,i.createElement("th",null),t)),i.createElement("tbody",null,l)))},t}(o.b),c=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.setProperties(t)},t.prototype.setProperties=function(e){this.row=e.row,this.creator=e.creator},t.prototype.render=function(){if(!this.row)return null;for(var e=[],t=0;t<this.row.cells.length;t++){var n=this.row.cells[t],r=i.createElement(s.b,{question:n.question,cssClasses:this.cssClasses,creator:this.creator}),o=this.renderSelect(n);e.push(i.createElement("td",{key:"row"+t,className:this.cssClasses.itemValue},r,o))}var a=this.renderLocString(this.row.locText);return i.createElement("tr",null,i.createElement("td",null,a),e)},t.prototype.renderSelect=function(e){return e.question.visible?e.question.customWidget?i.createElement(u.a,{creator:this.creator,question:e.question}):this.creator.createQuestionElement(e.question):null},t}(o.c);a.a.Instance.registerQuestion("matrixdropdown",function(e){return i.createElement(l,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(15),a=n(5),u=n(24);n.d(t,"a",function(){return l}),n.d(t,"b",function(){return c});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.setProperties(t)},t.prototype.setProperties=function(e){var t=this;this.state={rowCounter:0},this.question.rowCountChangedCallback=function(){t.state.rowCounter=t.state.rowCounter+1,t.setState(t.state)},this.handleOnRowAddClick=this.handleOnRowAddClick.bind(this)},t.prototype.handleOnRowAddClick=function(e){this.question.addRow()},t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.cssClasses,t=[],n=0;n<this.question.columns.length;n++){var r=this.question.columns[n],o="column"+n,s=this.question.getColumnWidth(r),a=s?{minWidth:s}:{},u=this.renderLocString(r.locTitle);t.push(i.createElement("th",{key:o,style:a},u))}for(var l=[],h=this.question.visibleRows,n=0;n<h.length;n++){var p=h[n];l.push(i.createElement(c,{key:n,row:p,question:this.question,index:n,cssClasses:e,isDisplayMode:this.isDisplayMode,creator:this.creator}))}var d=this.question.horizontalScroll?{overflowX:"scroll"}:{},f=this.isDisplayMode?null:i.createElement("th",null);return i.createElement("div",null,i.createElement("div",{style:d},i.createElement("table",{className:e.root},i.createElement("thead",null,i.createElement("tr",null,t,f)),i.createElement("tbody",null,l))),this.renderAddRowButton(e))},t.prototype.renderAddRowButton=function(e){return this.isDisplayMode||!this.question.canAddRow?null:i.createElement("input",{className:e.button,type:"button",onClick:this.handleOnRowAddClick,value:this.question.addRowText})},t}(o.b),c=function(e){function t(t){var n=e.call(this,t)||this;return n.setProperties(t),n}return r.b(t,e),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.setProperties(t)},t.prototype.setProperties=function(e){this.row=e.row,this.question=e.question,this.index=e.index,this.creator=e.creator,this.handleOnRowRemoveClick=this.handleOnRowRemoveClick.bind(this)},t.prototype.handleOnRowRemoveClick=function(e){this.question.removeRow(this.index)},t.prototype.render=function(){if(!this.row)return null;for(var e=[],t=0;t<this.row.cells.length;t++){var n=this.row.cells[t],r=i.createElement(s.b,{question:n.question,cssClasses:this.cssClasses,creator:this.creator}),o=this.renderQuestion(n);e.push(i.createElement("td",{key:"row"+t},r,o))}if(!this.isDisplayMode&&this.question.canRemoveRow){var a=this.renderButton();e.push(i.createElement("td",{key:"row"+this.row.cells.length+1},a))}return i.createElement("tr",null,e)},t.prototype.renderQuestion=function(e){return e.question.visible?e.question.customWidget?i.createElement(u.a,{creator:this.creator,question:e.question}):this.creator.createQuestionElement(e.question):null},t.prototype.renderButton=function(){return i.createElement("input",{className:this.cssClasses.button,type:"button",onClick:this.handleOnRowRemoveClick,value:this.question.removeRowText})},t}(o.c);a.a.Instance.registerQuestion("matrixdynamic",function(e){return i.createElement(l,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a}),n.d(t,"b",function(){return u});var a=function(e){function t(t){var n=e.call(this,t)||this;n.state={colCountChanged:0};var r=n;return n.question.colCountChangedCallback=function(){r.state.colCountChanged=r.state.colCountChanged+1,r.setState(r.state)},n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.cssClasses,t=this.question.getRows(),n=[],r=0;r<t.length;r++)n.push(this.renderRow("item"+r,t[r],e));return i.createElement("table",{className:e.root},i.createElement("tbody",null,n))},t.prototype.renderRow=function(e,t,n){for(var r=[],o=0;o<t.length;o++){var s=t[o],a=this.renderLocString(s.locTitle);r.push(i.createElement("td",{key:"label"+o},i.createElement("span",{className:n.itemTitle},a))),r.push(i.createElement("td",{key:"value"+o},this.renderItem(s,0==o,n)))}return i.createElement("tr",{key:e,className:n.row},r)},t.prototype.renderItem=function(e,t,n){var r=t?this.question.inputId:null;return i.createElement(u,{item:e,cssClasses:n,isDisplayMode:this.isDisplayMode,inputId:r})},t}(o.b),u=function(e){function t(t){var n=e.call(this,t)||this;return n.item=t.item,n.inputId=t.inputId,n.state={value:n.item.value||""},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),t.prototype.handleOnChange=function(e){this.setState({value:e.target.value})},t.prototype.handleOnBlur=function(e){this.item.value=e.target.value,this.setState({value:this.item.value})},t.prototype.componentWillReceiveProps=function(e){this.item=e.item},t.prototype.componentDidMount=function(){if(this.item){var e=this;this.item.onValueChangedCallback=function(t){e.setState({value:t||""})}}},t.prototype.componentWillUnmount=function(){this.item&&(this.item.onValueChangedCallback=null)},t.prototype.render=function(){if(!this.item)return null;var e={float:"left"};return this.isDisplayMode?i.createElement("div",{id:this.inputId,className:this.cssClasses.itemValue,style:e},this.item.value):i.createElement("input",{id:this.inputId,className:this.cssClasses.itemValue,type:this.item.inputType,style:e,value:this.state.value,placeholder:this.item.placeHolder,onBlur:this.handleOnBlur,onChange:this.handleOnChange})},Object.defineProperty(t.prototype,"mainClassName",{get:function(){return""},enumerable:!0,configurable:!0}),t}(o.c);s.a.Instance.registerQuestion("multipletext",function(e){return i.createElement(a,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;n.state={choicesChanged:0};var r=n;return n.question.choicesChangedCallback=function(){r.state.choicesChanged=r.state.choicesChanged+1,r.setState(r.state)},n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.handleOnChange=this.handleOnChange.bind(this)},t.prototype.handleOnChange=function(e){this.question.value=e.target.value,this.setState({value:this.question.value})},t.prototype.render=function(){if(!this.question)return null;var e=this.question.cssClasses;return i.createElement("div",{className:e.root},this.getItems(e))},t.prototype.getItems=function(e){for(var t=[],n=0;n<this.question.visibleChoices.length;n++){var r=this.question.visibleChoices[n],i="item"+n;t.push(this.renderItem(i,r,0==n,e))}return t},Object.defineProperty(t.prototype,"textStyle",{get:function(){return{marginLeft:"3px",display:"inline",position:"static"}},enumerable:!0,configurable:!0}),t.prototype.renderItem=function(e,t,n,r){var i=this.question.colCount>0?100/this.question.colCount+"%":"",o=0==this.question.colCount?"5px":"0px",s={marginRight:o,marginLeft:"0px",display:"inline-block"};i&&(s.width=i);var a=this.question.value==t.value,u=a&&t.value===this.question.otherItem.value?this.renderOther(r):null;return this.renderRadio(e,t,a,s,u,n,r)},t.prototype.renderRadio=function(e,t,n,r,o,s,a){var u=s?this.question.inputId:null,l=this.renderLocString(t.locText,this.textStyle);return i.createElement("div",{key:e,className:a.item,style:r},i.createElement("label",{className:a.label},i.createElement("input",{id:u,type:"radio",name:this.question.name+"_"+this.questionBase.id,checked:n,value:t.value,disabled:this.isDisplayMode,onChange:this.handleOnChange}),i.createElement("span",{className:"circle"}),i.createElement("span",{className:"check"}),l),o)},t.prototype.renderOther=function(e){return i.createElement("div",{className:e.other},i.createElement(s.a,{question:this.question,otherCss:e.other,cssClasses:e,isDisplayMode:this.isDisplayMode}))},t}(o.b);a.a.Instance.registerQuestion("radiogroup",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(12),a=n(5);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.handleOnChange=n.handleOnChange.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.handleOnChange=function(e){this.question.value=e.target.value,this.setState({value:this.question.value})},t.prototype.render=function(){if(!this.question)return null;for(var e=this.question.cssClasses,t=[],n=this.question.minRateDescription?this.renderLocString(this.question.locMinRateDescription):null,r=this.question.maxRateDescription?this.renderLocString(this.question.locMaxRateDescription):null,o=0;o<this.question.visibleRateValues.length;o++){var s=0==o?n:null,a=o==this.question.visibleRateValues.length-1?r:null;t.push(this.renderItem("value"+o,this.question.visibleRateValues[o],s,a,e))}var u=this.question.hasOther?this.renderOther(e):null;return i.createElement("div",{className:e.root},t,u)},t.prototype.renderItem=function(e,t,n,r,o){var s=this.question.value==t.value,a=o.item;s&&(a+=" active");var u=this.renderLocString(t.locText);return i.createElement("label",{key:e,className:a},i.createElement("input",{type:"radio",style:{display:"none"},name:this.question.name,value:t.value,disabled:this.isDisplayMode,checked:this.question.value==t.value,onChange:this.handleOnChange}),n,u,r)},t.prototype.renderOther=function(e){return i.createElement("div",{className:e.other},i.createElement(s.a,{question:this.question,cssClasses:e,isDisplayMode:this.isDisplayMode}))},t}(o.b);a.a.Instance.registerQuestion("rating",function(e){return i.createElement(u,e)})},function(e,t,n){"use strict";var r=n(0),i=n(3),o=(n.n(i),n(4)),s=n(5);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.state={value:n.question.value||""},n.handleOnChange=n.handleOnChange.bind(n),n.handleOnBlur=n.handleOnBlur.bind(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"question",{get:function(){return this.questionBase},enumerable:!0,configurable:!0}),t.prototype.componentWillReceiveProps=function(t){e.prototype.componentWillReceiveProps.call(this,t),this.state={value:this.question.value||""}},t.prototype.handleOnChange=function(e){this.setState({value:e.target.value})},t.prototype.handleOnBlur=function(e){this.question.value=e.target.value,this.setState({value:this.question.value||""})},t.prototype.render=function(){if(!this.question)return null;var e=this.question.cssClasses;return this.isDisplayMode?i.createElement("div",{id:this.question.inputId,className:e.root},this.question.value):i.createElement("input",{id:this.question.inputId,className:e.root,type:this.question.inputType,value:this.state.value,size:this.question.size,placeholder:this.question.placeHolder,onBlur:this.handleOnBlur,onChange:this.handleOnChange})},t}(o.b);s.a.Instance.registerQuestion("text",function(e){return i.createElement(a,e)})},function(e,t){},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"السابق",pageNextText:"التالي",completeText:"انهاء- تم",progressText:"{1} صفحة {0} من",otherItemText:"نص آخر",emptySurvey:"لا توجد صفحة مرئية أو سؤال في المسح",completingSurvey:"شكرا لك لاستكمال الاستبيان!",loadingSurvey:"...يتم تحميل الاستبيان",optionsCaption:"...اختر",requiredError:".يرجى الإجابة على السؤال",requiredInAllRowsError:"يرجى الإجابة على الأسئلة في جميع الصفوف",numericError:"يجب أن تكون القيمة الرقمية.",textMinLength:"الرجاء إدخال ما لا يقل عن {0} حرف",textMaxLength:"الرجاء إدخال أقل من {0} حرف",textMinMaxLength:"يرجى إدخال أكثر من {0} وأقل من {1} حرف",minRowCountError:"يرجى ملء ما لا يقل عن {0} الصفوف",minSelectError:"يرجى تحديد ما لا يقل عن {0} المتغيرات",maxSelectError:"يرجى تحديد ما لا يزيد عن {0} المتغيرات",numericMinMax:"و'{0}' يجب أن تكون مساوية أو أكثر من {1} ويساوي أو أقل من {2}ا",numericMin:"و'{0}' يجب أن تكون مساوية أو أكثر من {1}ا",numericMax:"و'{0}' يجب أن تكون مساوية أو أقل من {1}ا",invalidEmail:"رجاء قم بإدخال بريد الكتروني صحيح",urlRequestError:"طلب إرجاع خطأ '{0}'. {1}ا",urlGetChoicesError:"عاد طلب بيانات فارغة أو 'المسار' ممتلكات غير صحيحة ",exceedMaxSize:"وينبغي ألا يتجاوز حجم الملف {0}ا",otherRequiredError:"الرجاء إدخال قيمة أخرى",uploadingFile:"الملف الخاص بك تحميل. يرجى الانتظار عدة ثوان وحاول مرة أخرى",addRow:"اضافة صف",removeRow:"إزالة صف"};r.a.locales.ar=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Předchozí",pageNextText:"Další",completeText:"Hotovo",otherItemText:"Jiná odpověď (napište)",progressText:"Strana {0} z {1}",emptySurvey:"Průzkumu neobsahuje žádné otázky.",completingSurvey:"Děkujeme za vyplnění průzkumu!",loadingSurvey:"Probíhá načítání průzkumu...",optionsCaption:"Vyber...",requiredError:"Odpovězte prosím na otázku.",requiredInAllRowsError:"Odpovězte prosím na všechny otázky.",numericError:"V tomto poli lze zadat pouze čísla.",textMinLength:"Zadejte prosím alespoň {0} znaků.",textMaxLength:"Zadejte prosím méně než {0} znaků.",textMinMaxLength:"Zadejte prosím více než {0} a méně než {1} znaků.",minRowCountError:"Vyplňte prosím alespoň {0} řádků.",minSelectError:"Vyberte prosím alespoň {0} varianty.",maxSelectError:"Nevybírejte prosím více než {0} variant.",numericMinMax:"Odpověď '{0}' by mělo být větší nebo rovno {1} a menší nebo rovno {2}",numericMin:"Odpověď '{0}' by mělo být větší nebo rovno {1}",numericMax:"Odpověď '{0}' by mělo být menší nebo rovno {1}",invalidEmail:"Zadejte prosím platnou e-mailovou adresu.",urlRequestError:"Požadavek vrátil chybu '{0}'. {1}",urlGetChoicesError:"Požadavek nevrátil data nebo cesta je neplatná",exceedMaxSize:"Velikost souboru by neměla být větší než {0}.",otherRequiredError:"Zadejte prosím jinou hodnotu.",uploadingFile:"Váš soubor se nahrává. Zkuste to prosím za několik sekund.",addRow:"Přidat řádek",removeRow:"Odstranit"};r.a.locales.cz=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Tilbage",pageNextText:"Videre",completeText:"Færdig",progressText:"Side {0} af {1}",emptySurvey:"Der er ingen synlige spørgsmål.",completingSurvey:"Mange tak for din besvarelse!",loadingSurvey:"Spørgeskemaet hentes fra serveren...",otherItemText:"Valgfrit svar...",optionsCaption:"Vælg...",requiredError:"Besvar venligst spørgsmålet.",numericError:"Angiv et tal.",textMinLength:"Angiv mindst {0} tegn.",minSelectError:"Vælg venligst mindst {0} svarmulighed(er).",maxSelectError:"Vælg venligst færre {0} svarmuligheder(er).",numericMinMax:"'{0}' skal være lig med eller større end {1} og lig med eller mindre end {2}",numericMin:"'{0}' skal være lig med eller større end {1}",numericMax:"'{0}' skal være lig med eller mindre end {1}",invalidEmail:"Angiv venligst en gyldig e-mail adresse.",exceedMaxSize:"Filstørrelsen må ikke overstige {0}.",otherRequiredError:"Angiv en værdi for dit valgfrie svar."};r.a.locales.da=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Vorige",pageNextText:"Volgende",completeText:"Afsluiten",otherItemText:"Andere",progressText:"Pagina {0} van {1}",emptySurvey:"Er is geen zichtbare pagina of vraag in deze vragenlijst",completingSurvey:"Bedankt om deze vragenlijst in te vullen",loadingSurvey:"De vragenlijst is aan het laden...",optionsCaption:"Kies...",requiredError:"Gelieve een antwoord in te vullen",numericError:"Het antwoord moet een getal zijn",textMinLength:"Gelieve minsten {0} karakters in te vullen.",minSelectError:"Gelieve minimum {0} antwoorden te selecteren.",maxSelectError:"Gelieve niet meer dan {0} antwoorden te selecteren.",numericMinMax:"Uw antwoord '{0}' moet groter of gelijk zijn aan {1} en kleiner of gelijk aan {2}",numericMin:"Uw antwoord '{0}' moet groter of gelijk zijn aan {1}",numericMax:"Uw antwoord '{0}' moet groter of gelijk zijn aan {1}",invalidEmail:"Gelieve een geldig e-mailadres in te vullen.",exceedMaxSize:"De grootte van het bestand mag niet groter zijn dan {0}.",otherRequiredError:"Gelieve het veld 'Andere' in te vullen"};r.a.locales.nl=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Edellinen",pageNextText:"Seuraava",completeText:"Valmis",otherItemText:"Muu (kuvaile)",progressText:"Sivu {0}/{1}",emptySurvey:"Tässä kyselyssä ei ole yhtäkään näkyvillä olevaa sivua tai kysymystä.",completingSurvey:"Kiitos kyselyyn vastaamisesta!",loadingSurvey:"Kyselyä ladataan palvelimelta...",optionsCaption:"Valitse...",requiredError:"Vastaa kysymykseen, kiitos.",numericError:"Arvon tulee olla numeerinen.",textMinLength:"Ole hyvä ja syötä vähintään {0} merkkiä.",minSelectError:"Ole hyvä ja valitse vähintään {0} vaihtoehtoa.",maxSelectError:"Ole hyvä ja valitse enintään {0} vaihtoehtoa.",numericMinMax:"'{0}' täytyy olla enemmän tai yhtä suuri kuin {1} ja vähemmän tai yhtä suuri kuin {2}",numericMin:"'{0}' täytyy olla enemmän tai yhtä suuri kuin {1}",numericMax:"'{0}' täytyy olla vähemmän tai yhtä suuri kuin {1}",invalidEmail:"Syötä validi sähköpostiosoite.",otherRequiredError:'Ole hyvä ja syötä "Muu (kuvaile)"'};r.a.locales.fi=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Précédent",pageNextText:"Suivant",completeText:"Terminer",otherItemText:"Autre (préciser)",progressText:"Page {0} sur {1}",emptySurvey:"Il n'y a ni page visible ni question visible dans ce questionnaire",completingSurvey:"Merci d'avoir répondu au questionnaire!",loadingSurvey:"Le questionnaire est en cours de chargement...",optionsCaption:"Choisissez...",requiredError:"La réponse à cette question est obligatoire.",requiredInAllRowsError:"Toutes les lignes sont obligatoires",numericError:"La réponse doit être un nombre.",textMinLength:"Merci d'entrer au moins {0} symboles.",minSelectError:"Merci de sélectionner au moins {0}réponses.",maxSelectError:"Merci de sélectionner au plus {0}réponses.",numericMinMax:"Votre réponse '{0}' doit êtresupérieure ou égale à {1} et inférieure ouégale à {2}",numericMin:"Votre réponse '{0}' doit êtresupérieure ou égale à {1}",numericMax:"Votre réponse '{0}' doit êtreinférieure ou égale à {1}",invalidEmail:"Merci d'entrer une adresse mail valide.",exceedMaxSize:"La taille du fichier ne doit pas excéder {0}.",otherRequiredError:"Merci de préciser le champ 'Autre'."};r.a.locales.fr=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Zurück",pageNextText:"Weiter",completeText:"Absenden",progressText:"Seite {0} von {1}",emptySurvey:"Es gibt keine sichtbare Frage.",completingSurvey:"Vielen Dank für die Beantwortung des Fragebogens!",loadingSurvey:"Der Fragebogen wird vom Server geladen...",otherItemText:"Benutzerdefinierte Antwort...",optionsCaption:"Wählen...",requiredError:"Bitte beantworten Sie diese Frage.",numericError:"Der Wert sollte eine Zahl sein.",textMinLength:"Bitte geben Sie mindestens {0} Zeichen ein.",minSelectError:"Bitte wählen Sie mindestens {0} Einträge.",maxSelectError:"Bitte wählen Sie nicht mehr als {0} Einträge.",numericMinMax:"'{0}' sollte gleich oder größer sein als {1} und gleich oder kleiner als {2}.",numericMin:"'{0}' sollte gleich oder größer sein als {1}.",numericMax:"'{0}' sollte gleich oder kleiner als {1} sein.",invalidEmail:"Bitte geben Sie eine gültige E-Mail Adresse ein.",exceedMaxSize:"Die Dateigröße darf {0} KB nicht überschreiten.",otherRequiredError:"Bitte geben Sie Ihre benutzerdefinierte Antwort ein."};r.a.locales.de=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Προηγούμενο",pageNextText:"Επόμενο",completeText:"Ολοκλήρωση",otherItemText:"Άλλο (παρακαλώ διευκρινίστε)",progressText:"Σελίδα {0} από {1}",emptySurvey:"Δεν υπάρχει καμία ορατή σελίδα ή ορατή ερώτηση σε αυτό το ερωτηματολόγιο.",completingSurvey:"Ευχαριστούμε για την συμπλήρωση αυτου του ερωτηματολογίου!",loadingSurvey:"Το ερωτηματολόγιο φορτώνεται απο το διακομιστή...",optionsCaption:"Επιλέξτε...",requiredError:"Παρακαλώ απαντήστε στην ερώτηση.",requiredInAllRowsError:"Παρακαλώ απαντήστε στις ερωτήσεις σε όλες τις γραμμές.",numericError:"Η τιμή πρέπει να είναι αριθμιτική.",textMinLength:"Παρακαλώ συμπληρώστε τουλάχιστον {0} σύμβολα.",minRowCountError:"Παρακαλώ συμπληρώστε τουλάχιστον {0} γραμμές.",minSelectError:"Παρακαλώ επιλέξτε τουλάχιστον {0} παραλλαγές.",maxSelectError:"Παρακαλώ επιλέξτε όχι παραπάνω απο {0} παραλλαγές.",numericMinMax:"Το '{0}' θα πρέπει να είναι ίσο ή μεγαλύτερο απο το {1} και ίσο ή μικρότερο απο το {2}",numericMin:"Το '{0}' πρέπει να είναι μεγαλύτερο ή ισο με το {1}",numericMax:"Το '{0}' πρέπει να είναι μικρότερο ή ίσο απο το {1}",invalidEmail:"Παρακαλώ δώστε μια αποδεκτή διεύθυνση e-mail.",urlRequestError:"Η αίτηση επέστρεψε σφάλμα '{0}'. {1}",urlGetChoicesError:"Η αίτηση επέστρεψε κενά δεδομένα ή η ιδότητα 'μονοπάτι/path' είναι εσφαλέμένη",exceedMaxSize:"Το μέγεθος δεν μπορεί να υπερβένει τα {0}.",otherRequiredError:"Παρακαλώ συμπληρώστε την τιμή για το πεδίο 'άλλο'.",uploadingFile:"Το αρχείο σας ανεβαίνει. Παρακαλώ περιμένετε καποια δευτερόλεπτα και δοκιμάστε ξανά.",addRow:"Προσθήκη γραμμής",removeRow:"Αφαίρεση"};r.a.locales.gr=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Tilbaka",pageNextText:"Áfram",completeText:"Lokið",otherItemText:"Hinn (skýring)",progressText:"Síða {0} of {1}",emptySurvey:"Það er enginn síða eða spurningar í þessari könnun.",completingSurvey:"Takk fyrir að fyllja út þessa könnun!",loadingSurvey:"Könnunin er að hlaða...",optionsCaption:"Veldu...",requiredError:"Vinsamlegast svarið spurningunni.",requiredInAllRowsError:"Vinsamlegast svarið spurningum í öllum röðum.",numericError:"Þetta gildi verður að vera tala.",textMinLength:"Það ætti að vera minnst {0} tákn.",textMaxLength:"Það ætti að vera mest {0} tákn.",textMinMaxLength:"Það ætti að vera fleiri en {0} og færri en {1} tákn.",minRowCountError:"Vinsamlegast fyllið úr að minnsta kosti {0} raðir.",minSelectError:"Vinsamlegast veljið að minnsta kosti {0} möguleika.",maxSelectError:"Vinsamlegast veljið ekki fleiri en {0} möguleika.",numericMinMax:"'{0}' ætti að vera meira en eða jafnt og {1} minna en eða jafnt og {2}",numericMin:"{0}' ætti að vera meira en eða jafnt og {1}",numericMax:"'{0}' ætti að vera minna en eða jafnt og {1}",invalidEmail:"Vinsamlegast sláið inn gilt netfang.",urlRequestError:"Beiðninn skilaði eftirfaranadi villu '{0}'. {1}",urlGetChoicesError:"Beiðninng skilaði engum gögnum eða slóðinn var röng",exceedMaxSize:"Skráinn skal ekki vera stærri en {0}.",otherRequiredError:"Vinamlegast fyllið út hitt gildið.",uploadingFile:"Skráinn þín var send. Vinsamlegast bíðið í nokkrar sekúndur og reynið aftur.",addRow:"Bæta við röð",removeRow:"Fjarlægja",choices_firstItem:"fyrsti hlutur",choices_secondItem:"annar hlutur",choices_thirdItem:"þriðji hlutur",matrix_column:"Dálkur",matrix_row:"Röð"};r.a.locales.is=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Precedente",pageNextText:"Successivo",completeText:"Salva",otherItemText:"Altro (descrivi)",progressText:"Pagina {0} di {1}",emptySurvey:"Non ci sono pagine o domande visibili nel questionario.",completingSurvey:"Grazie per aver completato il questionario!",loadingSurvey:"Caricamento del questionario in corso...",optionsCaption:"Scegli...",requiredError:"Campo obbligatorio",requiredInAllRowsError:"Completare tutte le righe",numericError:"Il valore deve essere numerico",textMinLength:"Inserire almeno {0} caratteri",textMaxLength:"Lunghezza massima consentita {0} caratteri",textMinMaxLength:"Inserire una stringa con minimo {0} e massimo {1} caratteri",minRowCountError:"Completare almeno {0} righe.",minSelectError:"Selezionare almeno {0} varianti.",maxSelectError:"Selezionare massimo {0} varianti.",numericMinMax:"'{0}' deve essere uguale o superiore a {1} e uguale o inferiore a {2}",numericMin:"'{0}' deve essere uguale o superiore a {1}",numericMax:"'{0}' deve essere uguale o inferiore a {1}",invalidEmail:"Inserire indirizzo mail valido",urlRequestError:"La richiesta ha risposto con un errore '{0}'. {1}",urlGetChoicesError:"La richiesta ha risposto null oppure il percorso non è corretto",exceedMaxSize:"Il file non può eccedere {0}",otherRequiredError:"Inserire il valore 'altro'",uploadingFile:"File in caricamento. Attendi alcuni secondi e riprova",addRow:"Aggiungi riga",removeRow:"Rimuovi riga",choices_Item:"Elemento",matrix_column:"Colonna",matrix_row:"Riga"};r.a.locales.it=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Atpakaļ",pageNextText:"Tālāk",completeText:"Pabeigt",progressText:"Lappuse {0} no {1}",emptySurvey:"Nav neviena jautājuma.",completingSurvey:"Pateicamies Jums par anketas aizpildīšanu!",loadingSurvey:"Ielāde no servera...",otherItemText:"Cits (lūdzu, aprakstiet!)",optionsCaption:"Izvēlēties...",requiredError:"Lūdzu, atbildiet uz jautājumu!",numericError:"Atbildei ir jābūt skaitlim.",textMinLength:"Lūdzu, ievadiet vismaz {0} simbolus.",minSelectError:"Lūdzu, izvēlieties vismaz {0} variantu.",maxSelectError:"Lūdzu, izvēlieties ne vairak par {0} variantiem.",numericMinMax:"'{0}' jābūt vienādam vai lielākam nekā {1}, un vienādam vai mazākam, nekā {2}",numericMin:"'{0}' jābūt vienādam vai lielākam {1}",numericMax:"'{0}' jābūt vienādam vai lielākam {1}",invalidEmail:"Lūdzu, ievadiet patiesu e-pasta adresi!",otherRequiredError:'Lūdzu, ievadiet datus laukā "Cits"'};r.a.locales.lv=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Wstecz",pageNextText:"Dalej",completeText:"Gotowe",otherItemText:"Inna odpowiedź (wpisz)",progressText:"Strona {0} z {1}",emptySurvey:"Nie ma widocznych pytań.",completingSurvey:"Dziękujemy za wypełnienie ankiety!",loadingSurvey:"Trwa wczytywanie ankiety...",optionsCaption:"Wybierz...",requiredError:"Proszę odpowiedzieć na to pytanie.",requiredInAllRowsError:"Proszę odpowiedzieć na wszystkie pytania.",numericError:"W tym polu można wpisać tylko liczby.",textMinLength:"Proszę wpisać co najmniej {0} znaków.",textMaxLength:"Proszę wpisać mniej niż {0} znaków.",textMinMaxLength:"Proszę wpisać więcej niż {0} i mniej niż {1} znaków.",minRowCountError:"Proszę uzupełnić przynajmniej {0} wierszy.",minSelectError:"Proszę wybrać co najmniej {0} pozycji.",maxSelectError:"Proszę wybrać nie więcej niż {0} pozycji.",numericMinMax:"Odpowiedź '{0}' powinna być większa lub równa {1} oraz mniejsza lub równa {2}",numericMin:"Odpowiedź '{0}' powinna być większa lub równa {1}",numericMax:"Odpowiedź '{0}' powinna być mniejsza lub równa {1}",invalidEmail:"Proszę podać prawidłowy adres email.",urlRequestError:"Żądanie zwróciło błąd '{0}'. {1}",urlGetChoicesError:"Żądanie nie zwróciło danych albo ścieżka jest nieprawidłowa",exceedMaxSize:"Rozmiar przesłanego pliku nie może przekraczać {0}.",otherRequiredError:"Proszę podać inną odpowiedź.",uploadingFile:"Trwa przenoszenie Twojego pliku, proszę spróbować ponownie za kilka sekund.",addRow:"Dodaj wiersz",removeRow:"Usuń"};r.a.locales.pl=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Anterior",pageNextText:"Próximo",completeText:"Finalizar",otherItemText:"Outros (descrever)",progressText:"Pagina {0} de {1}",emptySurvey:"Não há página visível ou pergunta na pesquisa.",completingSurvey:"Obrigado por finalizar a pesquisa!",loadingSurvey:"A pesquisa está carregando...",optionsCaption:"Selecione...",requiredError:"Por favor, responda a pergunta.",requiredInAllRowsError:"Por favor, responda as perguntas em todas as linhas.",numericError:"O valor deve ser numérico.",textMinLength:"Por favor, insira pelo menos {0} caracteres.",textMaxLength:"Por favor, insira menos de {0} caracteres.",textMinMaxLength:"Por favor, insira mais de {0} e menos de {1} caracteres.",minRowCountError:"Preencha pelo menos {0} linhas.",minSelectError:"Selecione pelo menos {0} opções.",maxSelectError:"Por favor, selecione não mais do que {0} opções.",numericMinMax:"O '{0}' deve ser igual ou superior a {1} e igual ou menor que {2}",numericMin:"O '{0}' deve ser igual ou superior a {1}",numericMax:"O '{0}' deve ser igual ou inferior a {1}",invalidEmail:"Por favor, informe um e-mail válido.",urlRequestError:"A requisição retornou o erro '{0}'. {1}",urlGetChoicesError:"A requisição não retornou dados ou o 'caminho' da requisição não está correto",exceedMaxSize:"O tamanho do arquivo não deve exceder {0}.",otherRequiredError:"Por favor, informe o outro valor.",uploadingFile:"Seu arquivo está sendo carregado. Por favor, aguarde alguns segundos e tente novamente.",addRow:"Adicionar linha",removeRow:"Remover linha",choices_firstItem:"primeiro item",choices_secondItem:"segundo item",choices_thirdItem:"terceiro item",matrix_column:"Coluna",matrix_row:"Linha"};r.a.locales.pt=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Precedent",pageNextText:"Următor",completeText:"Finalizare",otherItemText:"Altul(precizaţi)",progressText:"Pagina {0} din {1}",emptySurvey:"Nu sunt întrebări pentru acest chestionar",completingSurvey:"Vă mulţumim pentru timpul acordat!",loadingSurvey:"Chestionarul se încarcă...",optionsCaption:"Alegeţi...",requiredError:"Răspunsul la această întrebare este obligatoriu.",requiredInAllRowsError:"Toate răspunsurile sunt obligatorii",numericError:"Răspunsul trebuie să fie numeric.",textMinLength:"Trebuie să introduci minim {0} caractere.",minSelectError:"Trebuie să selectezi minim {0} opţiuni.",maxSelectError:"Trebuie să selectezi maxim {0} opţiuni.",numericMinMax:"Răspunsul '{0}' trebuie să fie mai mare sau egal ca {1} şî mai mic sau egal cu {2}",numericMin:"Răspunsul '{0}' trebuie să fie mai mare sau egal ca {1}",numericMax:"Răspunsul '{0}' trebuie să fie mai mic sau egal ca {1}",invalidEmail:"Trebuie să introduceţi o adresa de email validă.",exceedMaxSize:"Dimensiunea fişierului nu trebuie să depăşească {0}.",otherRequiredError:"Trebuie să completezi câmpul 'Altul'."};r.a.locales.ro=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Назад",pageNextText:"Далее",completeText:"Готово",progressText:"Страница {0} из {1}",emptySurvey:"Нет ни одного вопроса.",completingSurvey:"Благодарим Вас за заполнение анкеты!",loadingSurvey:"Загрузка с сервера...",otherItemText:"Другое (пожалуйста, опишите)",optionsCaption:"Выбрать...",requiredError:"Пожалуйста, ответьте на вопрос.",numericError:"Ответ должен быть числом.",textMinLength:"Пожалуйста, введите хотя бы {0} символов.",minSelectError:"Пожалуйста, выберите хотя бы {0} вариантов.",maxSelectError:"Пожалуйста, выберите не более {0} вариантов.",numericMinMax:"'{0}' должно быть равным или больше, чем {1}, и равным или меньше, чем {2}",numericMin:"'{0}' должно быть равным или больше, чем {1}",numericMax:"'{0}' должно быть равным или меньше, чем {1}",invalidEmail:"Пожалуйста, введите действительный адрес электронной почты.",otherRequiredError:'Пожалуйста, введите данные в поле "Другое"'};r.a.locales.ru=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Anterior",pageNextText:"Siguiente",completeText:"Completo",otherItemText:"Otro (describa)",progressText:"Pagina {0} de {1}",emptySurvey:"No hay pagina visible o pregunta en la encuesta.",completingSurvey:"Gracias por completar la encuesta!",loadingSurvey:"La encuesta se esta cargando...",optionsCaption:"Seleccione...",requiredError:"Por favor conteste la pregunta.",requiredInAllRowsError:"Por favor conteste las preguntas en cada hilera.",numericError:"La estimacion debe ser numerica.",textMinLength:"Por favor entre por lo menos {0} symbolos.",textMaxLength:"Por favor entre menos de {0} symbolos.",textMinMaxLength:"Por favor entre mas de {0} y menos de {1} symbolos.",minRowCountError:"Por favor llene por lo menos {0} hileras.",minSelectError:"Por favor seleccione por lo menos {0} variantes.",maxSelectError:"Por favor seleccione no mas de {0} variantes.",numericMinMax:"El '{0}' debe de ser igual o mas de {1} y igual o menos de {2}",numericMin:"El '{0}' debe ser igual o mas de {1}",numericMax:"El '{0}' debe ser igual o menos de {1}",invalidEmail:"Por favor agrege un correo electonico valido.",urlRequestError:"La solicitud regreso error '{0}'. {1}",urlGetChoicesError:"La solicitud regreso vacio de data o la propiedad 'trayectoria' no es correcta",exceedMaxSize:"El tamaño der archivo no debe de exceder {0}.",otherRequiredError:"Por favor agrege la otra estimacion.",uploadingFile:"Su archivo se esta subiendo. Por favor espere unos segundos y intente de nuevo.",addRow:"Agrege hilera",removeRow:"Retire",choices_firstItem:"primer articulo",choices_secondItem:"segundo articulo",choices_thirdItem:"tercer articulo",matrix_column:"Columna",matrix_row:"Hilera"};r.a.locales.es=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Föregående",pageNextText:"Nästa",completeText:"Färdig",otherItemText:"Annat (beskriv)",progressText:"Sida {0} av {1}",emptySurvey:"Det finns ingen synlig sida eller fråga i enkäten.",completingSurvey:"Tack för att du genomfört enkäten!!",loadingSurvey:"Enkäten laddas...",optionsCaption:"Välj...",requiredError:"Var vänlig besvara frågan.",requiredInAllRowsError:"Var vänlig besvara frågorna på alla rader.",numericError:"Värdet ska vara numeriskt.",textMinLength:"Var vänlig ange minst {0} tecken.",minRowCountError:"Var vänlig fyll i minst {0} rader.",minSelectError:"Var vänlig välj åtminstone {0} varianter.",maxSelectError:"Var vänlig välj inte fler än {0} varianter.",numericMinMax:"'{0}' ska vara lika med eller mer än {1} samt lika med eller mindre än {2}",numericMin:"'{0}' ska vara lika med eller mer än {1}",numericMax:"'{0}' ska vara lika med eller mindre än {1}",invalidEmail:"Var vänlig ange en korrekt e-postadress.",urlRequestError:"Förfrågan returnerade felet '{0}'. {1}",urlGetChoicesError:"Antingen returnerade förfrågan ingen data eller så är egenskapen 'path' inte korrekt",exceedMaxSize:"Filstorleken får ej överstiga {0}.",otherRequiredError:"Var vänlig ange det andra värdet.",uploadingFile:"Din fil laddas upp. Var vänlig vänta några sekunder och försök sedan igen.",addRow:"Lägg till rad",removeRow:"Ta bort"};r.a.locales.sv=i},function(e,t,n){"use strict";var r=n(1),i={pagePrevText:"Geri",pageNextText:"İleri",completeText:"Anketi Tamamla",otherItemText:"Diğer (açıklayınız)",progressText:"Sayfa {0} / {1}",emptySurvey:"Ankette görüntülenecek sayfa ya da soru mevcut değil.",completingSurvey:"Anketimizi tamamladığınız için teşekkür ederiz.",loadingSurvey:"Anket sunucudan yükleniyor ...",optionsCaption:"Seçiniz ...",requiredError:"Lütfen soruya cevap veriniz",numericError:"Girilen değer numerik olmalıdır",textMinLength:"En az {0} sembol giriniz.",minRowCountError:"Lütfen en az {0} satırı doldurun.",minSelectError:"Lütfen en az {0} seçeneği seçiniz.",maxSelectError:"Lütfen {0} adetten fazla seçmeyiniz.",numericMinMax:"The '{0}' should be equal or more than {1} and equal or less than {2}",numericMin:"'{0}' değeri {1} değerine eşit veya büyük olmalıdır",numericMax:"'{0}' değeri {1} değerine eşit ya da küçük olmalıdır.",invalidEmail:"Lütfen geçerli bir eposta adresi giriniz.",urlRequestError:"Talebi şu hatayı döndü '{0}'. {1}",urlGetChoicesError:"Talep herhangi bir veri dönmedi ya da 'path' özelliği hatalı.",exceedMaxSize:"Dosya boyutu {0} değerini geçemez.",otherRequiredError:"Lütfen diğer değerleri giriniz.",uploadingFile:"Dosyanız yükleniyor. LÜtfen birkaç saniye bekleyin ve tekrar deneyin.",addRow:"Satır Ekle",removeRow:"Kaldır"};r.a.locales.tr=i},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(7),s=n(14);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n}return r.b(t,e),t.prototype.getHasOther=function(e){return!(!e||!Array.isArray(e))&&e.indexOf(this.otherItem.value)>=0},t.prototype.valueFromData=function(t){return t?Array.isArray(t)?e.prototype.valueFromData.call(this,t):[t]:t},t.prototype.valueFromDataCore=function(e){for(var t=0;t<e.length;t++){if(e[t]==this.otherItem.value)return e;if(this.hasUnknownValue(e[t])){this.comment=e[t];var n=e.slice();return n[t]=this.otherItem.value,n}}return e},t.prototype.valueToDataCore=function(e){if(!e||!e.length)return e;for(var t=0;t<e.length;t++)if(e[t]==this.otherItem.value&&this.getComment()){var n=e.slice();return n[t]=this.getComment(),n}return e},t.prototype.getType=function(){return"checkbox"},t}(s.a);i.a.metaData.addClass("checkbox",[],function(){return new a("")},"checkboxbase"),o.a.Instance.registerQuestion("checkbox",function(e){var t=new a(e);return t.choices=o.a.DefaultChoices,t})},function(e,t,n){"use strict";var r=n(0),i=n(10),o=n(2),s=n(7),a=n(8);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.rows=4,n.cols=50,n.locPlaceHolderValue=new a.a(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),t.prototype.getType=function(){return"comment"},t.prototype.isEmpty=function(){return e.prototype.isEmpty.call(this)||""===this.value},t}(i.a);o.a.metaData.addClass("comment",[{name:"cols:number",default:50},{name:"rows:number",default:4},{name:"placeHolder",serializationProperty:"locPlaceHolder"}],function(){return new u("")},"question"),s.a.Instance.registerQuestion("comment",function(e){return new u(e)})},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(7),s=n(14),a=n(1),u=n(8);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.locOptionsCaptionValue=new u.a(n),n}return r.b(t,e),Object.defineProperty(t.prototype,"optionsCaption",{get:function(){return this.locOptionsCaption.text?this.locOptionsCaption.text:a.a.getString("optionsCaption")},set:function(e){this.locOptionsCaption.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locOptionsCaption",{get:function(){return this.locOptionsCaptionValue},enumerable:!0,configurable:!0}),t.prototype.getType=function(){return"dropdown"},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),this.locOptionsCaption.onChanged()},t.prototype.supportGoNextPageAutomatic=function(){return!0},t}(s.b);i.a.metaData.addClass("dropdown",[{name:"optionsCaption",serializationProperty:"locOptionsCaption"}],function(){return new l("")},"selectbase"),o.a.Instance.registerQuestion("dropdown",function(e){var t=new l(e);return t.choices=o.a.DefaultChoices,t})},function(e,t,n){"use strict";var r=n(0),i=n(10),o=n(2),s=n(7),a=n(9),u=n(1);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.showPreviewValue=!1,n.isUploading=!1,n}return r.b(t,e),t.prototype.getType=function(){return"file"},Object.defineProperty(t.prototype,"showPreview",{get:function(){return this.showPreviewValue},set:function(e){this.showPreviewValue=e},enumerable:!0,configurable:!0}),t.prototype.loadFile=function(e){var t=this;this.survey&&!this.survey.uploadFile(this.name,e,this.storeDataAsText,function(e){t.isUploading="uploading"==e})||this.setFileValue(e)},t.prototype.setFileValue=function(e){if(FileReader&&(this.showPreview||this.storeDataAsText)&&!this.checkFileForErrors(e)){var t=new FileReader,n=this;t.onload=function(r){n.showPreview&&(n.previewValue=n.isFileImage(e)?t.result:null,n.fireCallback(n.previewValueLoadedCallback)),n.storeDataAsText&&(n.value=t.result)},t.readAsDataURL(e)}},t.prototype.onCheckForErrors=function(t){e.prototype.onCheckForErrors.call(this,t),this.isUploading&&this.errors.push(new a.c(u.a.getString("uploadingFile")))},t.prototype.checkFileForErrors=function(e){var t=this.errors?this.errors.length:0;return this.errors=[],this.maxSize>0&&e.size>this.maxSize&&this.errors.push(new a.d(this.maxSize)),(t!=this.errors.length||this.errors.length>0)&&this.fireCallback(this.errorsChangedCallback),this.errors.length>0},t.prototype.isFileImage=function(e){if(e&&e.type){return 0==e.type.toLowerCase().indexOf("image")}},t}(i.a);o.a.metaData.addClass("file",["showPreview:boolean","imageHeight","imageWidth","storeDataAsText:boolean","maxSize:number"],function(){return new l("")},"question"),s.a.Instance.registerQuestion("file",function(e){return new l(e)})},function(e,t,n){"use strict";var r=n(0),i=n(23),o=n(2),s=n(7),a=n(8);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.locHtmlValue=new a.a(n),n}return r.b(t,e),t.prototype.getType=function(){return"html"},Object.defineProperty(t.prototype,"html",{get:function(){return this.locHtml.text},set:function(e){this.locHtml.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locHtml",{get:function(){return this.locHtmlValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"processedHtml",{get:function(){return this.survey?this.survey.processHtml(this.html):this.html},enumerable:!0,configurable:!0}),t}(i.a);o.a.metaData.addClass("html",[{name:"html:html",serializationProperty:"locHtml"}],function(){return new u("")},"questionbase"),s.a.Instance.registerQuestion("html",function(e){return new u(e)})},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(11),s=n(10),a=n(2),u=n(1),l=n(9),c=n(7);n.d(t,"a",function(){return h}),n.d(t,"b",function(){return p});var h=function(e){function t(t,n,r,i){var o=e.call(this)||this;return o.fullName=n,o.item=t,o.data=r,o.rowValue=i,o}return r.b(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return this.item.value},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"text",{get:function(){return this.item.text},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locText",{get:function(){return this.item.locText},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){return this.rowValue},set:function(e){this.rowValue=e,this.data&&this.data.onMatrixRowChanged(this),this.onValueChanged()},enumerable:!0,configurable:!0}),t.prototype.onValueChanged=function(){},t}(i.b),p=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.isRowChanging=!1,n.isAllRowRequired=!1,n.columnsValue=o.a.createArray(n),n.rowsValue=o.a.createArray(n),n}return r.b(t,e),t.prototype.getType=function(){return"matrix"},Object.defineProperty(t.prototype,"hasRows",{get:function(){return this.rowsValue.length>0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"columns",{get:function(){return this.columnsValue},set:function(e){o.a.setData(this.columnsValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rows",{get:function(){return this.rowsValue},set:function(e){o.a.setData(this.rowsValue,e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleRows",{get:function(){var e=new Array,t=this.value;t||(t={});for(var n=0;n<this.rows.length;n++)this.rows[n].value&&e.push(this.createMatrixRow(this.rows[n],this.name+"_"+this.rows[n].value.toString(),t[this.rows[n].value]));return 0==e.length&&e.push(this.createMatrixRow(new o.a(null),this.name,t)),this.generatedVisibleRows=e,e},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),o.a.NotifyArrayOnLocaleChanged(this.columns),o.a.NotifyArrayOnLocaleChanged(this.rows)},t.prototype.supportGoNextPageAutomatic=function(){return this.hasValuesInAllRows()},t.prototype.onCheckForErrors=function(t){e.prototype.onCheckForErrors.call(this,t),this.hasErrorInRows()&&this.errors.push(new l.c(u.a.getString("requiredInAllRowsError")))},t.prototype.hasErrorInRows=function(){return!!this.isAllRowRequired&&!this.hasValuesInAllRows()},t.prototype.hasValuesInAllRows=function(){var e=this.generatedVisibleRows;if(e||(e=this.visibleRows),!e)return!0;for(var t=0;t<e.length;t++){if(!e[t].value)return!1}return!0},t.prototype.createMatrixRow=function(e,t,n){return new h(e,t,this,n)},t.prototype.onValueChanged=function(){if(!this.isRowChanging&&this.generatedVisibleRows&&0!=this.generatedVisibleRows.length){this.isRowChanging=!0;var e=this.value;if(e||(e={}),0==this.rows.length)this.generatedVisibleRows[0].value=e;else for(var t=0;t<this.generatedVisibleRows.length;t++){var n=this.generatedVisibleRows[t],r=e[n.name]?e[n.name]:null;this.generatedVisibleRows[t].value=r}this.isRowChanging=!1}},t.prototype.onMatrixRowChanged=function(e){if(!this.isRowChanging){if(this.isRowChanging=!0,this.hasRows){var t=this.value;t||(t={}),t[e.name]=e.value,this.setNewValue(t)}else this.setNewValue(e.value);this.isRowChanging=!1}},t}(s.a);a.a.metaData.addClass("matrix",[{name:"columns:itemvalues",onGetValue:function(e){return o.a.getData(e.columns)},onSetValue:function(e,t){e.columns=t}},{name:"rows:itemvalues",onGetValue:function(e){return o.a.getData(e.rows)},onSetValue:function(e,t){e.rows=t}},"isAllRowRequired:boolean"],function(){return new p("")},"question"),c.a.Instance.registerQuestion("matrix",function(e){var t=new p(e);return t.rows=c.a.DefaultRows,t.columns=c.a.DefaultColums,t})},function(e,t,n){"use strict";var r=n(0),i=n(22),o=n(2),s=n(11),a=n(7);n.d(t,"a",function(){return u}),n.d(t,"b",function(){return l});var u=function(e){function t(t,n,r,i){var o=e.call(this,r,i)||this;return o.name=t,o.item=n,o}return r.b(t,e),Object.defineProperty(t.prototype,"rowName",{get:function(){return this.name},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"text",{get:function(){return this.item.text},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locText",{get:function(){return this.item.locText},enumerable:!0,configurable:!0}),t}(i.c),l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.rowsValue=s.a.createArray(n),n}return r.b(t,e),t.prototype.getType=function(){return"matrixdropdown"},Object.defineProperty(t.prototype,"rows",{get:function(){return this.rowsValue},set:function(e){s.a.setData(this.rowsValue,e),this.generatedVisibleRows=null},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this),s.a.NotifyArrayOnLocaleChanged(this.rowsValue)},t.prototype.generateRows=function(){var e=new Array;if(!this.rows||0===this.rows.length)return e;var t=this.value;t||(t={});for(var n=0;n<this.rows.length;n++)this.rows[n].value&&e.push(this.createMatrixRow(this.rows[n],t[this.rows[n].value]));return e},t.prototype.createMatrixRow=function(e,t){var n=new u(e.value,e,this,t);return this.onMatrixRowCreated(n),n},t}(i.d);o.a.metaData.addClass("matrixdropdown",[{name:"rows:itemvalues",onGetValue:function(e){return s.a.getData(e.rows)},onSetValue:function(e,t){e.rows=t}}],function(){return new l("")},"matrixdropdownbase"),a.a.Instance.registerQuestion("matrixdropdown",function(e){var t=new l(e);return t.choices=[1,2,3,4,5],t.rows=a.a.DefaultColums,i.d.addDefaultColumns(t),t})},function(e,t,n){"use strict";var r=n(0),i=n(22),o=n(2),s=n(7),a=n(1),u=n(9),l=n(8);n.d(t,"a",function(){return c}),n.d(t,"b",function(){return h});var c=function(e){function t(t,n,r){var i=e.call(this,n,r)||this;return i.index=t,i}return r.b(t,e),Object.defineProperty(t.prototype,"rowName",{get:function(){return this.id},enumerable:!0,configurable:!0}),t}(i.c),h=function(e){function t(n){var r=e.call(this,n)||this;return r.name=n,r.rowCounter=0,r.rowCountValue=2,r.minRowCountValue=0,r.maxRowCountValue=t.MaxRowCount,r.locAddRowTextValue=new l.a(r),r.locRemoveRowTextValue=new l.a(r),r}return r.b(t,e),t.prototype.getType=function(){return"matrixdynamic"},Object.defineProperty(t.prototype,"rowCount",{get:function(){return this.rowCountValue},set:function(e){if(!(e<0||e>t.MaxRowCount)){var n=this.rowCountValue;if(this.rowCountValue=e,this.value&&this.value.length>e){var r=this.value;r.splice(e),this.value=r}if(this.generatedVisibleRows){this.generatedVisibleRows.splice(e);for(var i=n;i<e;i++)this.generatedVisibleRows.push(this.createMatrixRow(null))}this.fireCallback(this.rowCountChangedCallback)}},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"minRowCount",{get:function(){return this.minRowCountValue},set:function(e){e<0&&(e=0),e==this.minRowCount||e>this.maxRowCount||(this.minRowCountValue=e,this.rowCount<e&&(this.rowCount=e))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxRowCount",{get:function(){return this.maxRowCountValue},set:function(e){e<=0||(e>t.MaxRowCount&&(e=t.MaxRowCount),e==this.maxRowCount||e<this.minRowCount||(this.maxRowCountValue=e,this.rowCount>e&&(this.rowCount=e)))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"canAddRow",{get:function(){return this.rowCount<this.maxRowCount},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"canRemoveRow",{get:function(){return this.rowCount>this.minRowCount},enumerable:!0,configurable:!0}),t.prototype.addRow=function(){if(this.canAddRow){var e=this.rowCount;this.rowCount=this.rowCount+1,this.survey&&e+1==this.rowCount&&this.survey.matrixRowAdded(this)}},t.prototype.removeRow=function(e){if(this.canRemoveRow&&!(e<0||e>=this.rowCount)){if(this.generatedVisibleRows&&e<this.generatedVisibleRows.length&&this.generatedVisibleRows.splice(e,1),this.value){var t=this.createNewValue(this.value);t.splice(e,1),t=this.deleteRowValue(t,null),this.value=t}this.rowCountValue--,this.fireCallback(this.rowCountChangedCallback)}},Object.defineProperty(t.prototype,"addRowText",{get:function(){return this.locAddRowText.text?this.locAddRowText.text:a.a.getString("addRow")},set:function(e){this.locAddRowText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locAddRowText",{get:function(){return this.locAddRowTextValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"removeRowText",{get:function(){return this.locRemoveRowText.text?this.locRemoveRowText.text:a.a.getString("removeRow")},set:function(e){this.locRemoveRowText.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locRemoveRowText",{get:function(){return this.locRemoveRowTextValue},enumerable:!0,configurable:!0}),t.prototype.supportGoNextPageAutomatic=function(){return!1},t.prototype.onCheckForErrors=function(t){e.prototype.onCheckForErrors.call(this,t),this.hasErrorInRows()&&t.push(new u.c(a.a.getString("minRowCountError").format(this.minRowCount)))},t.prototype.hasErrorInRows=function(){if(this.minRowCount<=0||!this.generatedVisibleRows)return!1;for(var e=0,t=0;t<this.generatedVisibleRows.length;t++){this.generatedVisibleRows[t].isEmpty||e++}return e<this.minRowCount},t.prototype.generateRows=function(){var e=new Array;if(0===this.rowCount)return e;for(var t=this.createNewValue(this.value),n=0;n<this.rowCount;n++)e.push(this.createMatrixRow(this.getRowValueByIndex(t,n)));return e},t.prototype.createMatrixRow=function(e){var t=new c(this.rowCounter++,this,e);return this.onMatrixRowCreated(t),t},t.prototype.onBeforeValueChanged=function(e){var t=e&&Array.isArray(e)?e.length:0;t<=this.rowCount||(this.rowCountValue=t,this.generatedVisibleRows&&(this.generatedVisibleRows=null,this.generatedVisibleRows=this.visibleRows))},t.prototype.createNewValue=function(e){var t=e;t||(t=[]);t.length>this.rowCount&&t.splice(this.rowCount-1);for(var n=t.length;n<this.rowCount;n++)t.push({});return t},t.prototype.deleteRowValue=function(e,t){for(var n=!0,r=0;r<e.length;r++)if(Object.keys(e[r]).length>0){n=!1;break}return n?null:e},t.prototype.getRowValueByIndex=function(e,t){return t>=0&&t<e.length?e[t]:null},t.prototype.getRowValueCore=function(e,t,n){return void 0===n&&(n=!1),this.getRowValueByIndex(t,this.generatedVisibleRows.indexOf(e))},t}(i.d);h.MaxRowCount=100,o.a.metaData.addClass("matrixdynamic",[{name:"rowCount:number",default:2},{name:"minRowCount:number",default:0},{name:"maxRowCount:number",default:h.MaxRowCount},{name:"addRowText",serializationProperty:"locAddRowText"},{name:"removeRowText",serializationProperty:"locRemoveRowText"}],function(){return new h("")},"matrixdropdownbase"),s.a.Instance.registerQuestion("matrixdynamic",function(e){var t=new h(e);return t.choices=[1,2,3,4,5],i.d.addDefaultColumns(t),t})},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(27),s=n(10),a=n(2),u=n(7),l=n(9),c=n(8);n.d(t,"a",function(){return h}),n.d(t,"b",function(){return p});var h=function(e){function t(t,n){void 0===t&&(t=null),void 0===n&&(n=null);var r=e.call(this)||this;r.isRequired=!1,r.inputTypeValue="text",r.validators=new Array,r.nameValue=t,r.locTitleValue=new c.a(r,!0);var i=r;return r.locTitleValue.onRenderedHtmlCallback=function(e){return i.getFullTitle(e)},r.title=n,r.locPlaceHolderValue=new c.a(r),r}return r.b(t,e),t.prototype.getType=function(){return"multipletextitem"},Object.defineProperty(t.prototype,"name",{get:function(){return this.nameValue},set:function(e){this.name!==e&&(this.nameValue=e,this.locTitleValue.onChanged())},enumerable:!0,configurable:!0}),t.prototype.setData=function(e){this.data=e},Object.defineProperty(t.prototype,"inputType",{get:function(){return this.inputTypeValue},set:function(e){this.inputTypeValue=e.toLowerCase()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.locTitle.text?this.locTitle.text:this.name},set:function(e){this.locTitle.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.locTitleValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fullTitle",{get:function(){return this.getFullTitle(this.locTitle.textOrHtml)},enumerable:!0,configurable:!0}),t.prototype.getFullTitle=function(e){return e||(e=this.name),this.isRequired&&this.data&&(e=this.data.getIsRequiredText()+" "+e),e},Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),t.prototype.onLocaleChanged=function(){this.locTitle.onChanged()},Object.defineProperty(t.prototype,"value",{get:function(){return this.data?this.data.getMultipleTextValue(this.name):null},set:function(e){null!=this.data&&this.data.setMultipleTextValue(this.name,e)},enumerable:!0,configurable:!0}),t.prototype.onValueChanged=function(e){this.onValueChangedCallback&&this.onValueChangedCallback(e)},t.prototype.getValidatorTitle=function(){return this.title},t.prototype.getLocale=function(){return this.data?this.data.getLocale():""},t.prototype.getMarkdownHtml=function(e){return this.data?this.data.getMarkdownHtml(e):null},t}(i.b),p=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.colCountValue=1,n.itemSize=25,n.itemsValues=new Array,n.isMultipleItemValueChanging=!1,n.setItemsOverriddenMethods(),n}return r.b(t,e),t.prototype.getType=function(){return"multipletext"},Object.defineProperty(t.prototype,"items",{get:function(){return this.itemsValues},set:function(e){this.itemsValues=e,this.setItemsOverriddenMethods(),this.fireCallback(this.colCountChangedCallback)},enumerable:!0,configurable:!0}),t.prototype.addItem=function(e,t){void 0===t&&(t=null);var n=this.createTextItem(e,t);return this.items.push(n),n},t.prototype.onLocaleChanged=function(){e.prototype.onLocaleChanged.call(this);for(var t=0;t<this.items.length;t++)this.items[t].onLocaleChanged()},t.prototype.setItemsOverriddenMethods=function(){var e=this;this.itemsValues.push=function(t){t.setData(e);var n=Array.prototype.push.call(this,t);return e.fireCallback(e.colCountChangedCallback),n},this.itemsValues.splice=function(t,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];t||(t=0),n||(n=0);var o=(a=Array.prototype.splice).call.apply(a,[e.itemsValues,t,n].concat(r));r||(r=[]);for(var s=0;s<r.length;s++)r[s].setData(e);return e.fireCallback(e.colCountChangedCallback),o;var a}},t.prototype.supportGoNextPageAutomatic=function(){for(var e=0;e<this.items.length;e++)if(!this.items[e].value)return!1;return!0},Object.defineProperty(t.prototype,"colCount",{get:function(){return this.colCountValue},set:function(e){e<1||e>4||(this.colCountValue=e,this.fireCallback(this.colCountChangedCallback))},enumerable:!0,configurable:!0}),t.prototype.getRows=function(){for(var e=this.colCount,t=this.items,n=[],r=0,i=0;i<t.length;i++)0==r&&n.push([]),n[n.length-1].push(t[i]),++r>=e&&(r=0);return n},t.prototype.onValueChanged=function(){e.prototype.onValueChanged.call(this),this.onItemValueChanged()},t.prototype.createTextItem=function(e,t){return new h(e,t)},t.prototype.onItemValueChanged=function(){if(!this.isMultipleItemValueChanging)for(var e=0;e<this.items.length;e++){var t=null;this.value&&this.items[e].name in this.value&&(t=this.value[this.items[e].name]),this.items[e].onValueChanged(t)}},t.prototype.runValidators=function(){var t=e.prototype.runValidators.call(this);if(null!=t)return t;for(var n=0;n<this.items.length;n++)if(null!=(t=(new o.a).run(this.items[n])))return t;return null},t.prototype.hasErrors=function(t){void 0===t&&(t=!0);var n=e.prototype.hasErrors.call(this,t);return n||(n=this.hasErrorInItems(t)),n},t.prototype.hasErrorInItems=function(e){for(var t=0;t<this.items.length;t++){var n=this.items[t];if(n.isRequired&&!n.value)return this.errors.push(new l.a),e&&this.fireCallback(this.errorsChangedCallback),!0}return!1},t.prototype.getMultipleTextValue=function(e){return this.value?this.value[e]:null},t.prototype.setMultipleTextValue=function(e,t){this.isMultipleItemValueChanging=!0;var n=this.value;n||(n={}),n[e]=t,this.setNewValue(n),this.isMultipleItemValueChanging=!1},t.prototype.getIsRequiredText=function(){return this.survey?this.survey.requiredText:""},t}(s.a);a.a.metaData.addClass("multipletextitem",["name","isRequired:boolean",{name:"placeHolder",serializationProperty:"locPlaceHolder"},{name:"inputType",default:"text",choices:["color","date","datetime","datetime-local","email","month","number","password","range","tel","text","time","url","week"]},{name:"title",serializationProperty:"locTitle"},{name:"validators:validators",baseClassName:"surveyvalidator",classNamePart:"validator"}],function(){return new h("")}),a.a.metaData.addClass("multipletext",[{name:"!items:textitems",className:"multipletextitem"},{name:"itemSize:number",default:25},{name:"colCount:number",default:1,choices:[1,2,3,4]}],function(){return new p("")},"question"),u.a.Instance.registerQuestion("multipletext",function(e){var t=new p(e);return t.addItem("text1"),t.addItem("text2"),t})},function(e,t,n){"use strict";var r=n(0),i=n(2),o=n(7),s=n(14);n.d(t,"a",function(){return a});var a=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n}return r.b(t,e),t.prototype.getType=function(){return"radiogroup"},t.prototype.supportGoNextPageAutomatic=function(){return!0},t}(s.a);i.a.metaData.addClass("radiogroup",[],function(){return new a("")},"checkboxbase"),o.a.Instance.registerQuestion("radiogroup",function(e){var t=new a(e);return t.choices=o.a.DefaultChoices,t})},function(e,t,n){"use strict";var r=n(0),i=n(11),o=n(10),s=n(2),a=n(7),u=n(8);n.d(t,"a",function(){return l});var l=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.rates=i.a.createArray(n),n.locMinRateDescriptionValue=new u.a(n,!0),n.locMaxRateDescriptionValue=new u.a(n,!0),n.locMinRateDescriptionValue.onRenderedHtmlCallback=function(e){return e?e+" ":e},n.locMaxRateDescriptionValue.onRenderedHtmlCallback=function(e){return e?" "+e:e},n}return r.b(t,e),Object.defineProperty(t.prototype,"rateValues",{get:function(){return this.rates},set:function(e){i.a.setData(this.rates,e),this.fireCallback(this.rateValuesChangedCallback)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibleRateValues",{get:function(){return this.rateValues.length>0?this.rateValues:t.defaultRateValues},enumerable:!0,configurable:!0}),t.prototype.getType=function(){return"rating"},t.prototype.supportGoNextPageAutomatic=function(){return!0},t.prototype.supportComment=function(){return!0},t.prototype.supportOther=function(){return!0},Object.defineProperty(t.prototype,"minRateDescription",{get:function(){return this.locMinRateDescription.text},set:function(e){this.locMinRateDescription.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locMinRateDescription",{get:function(){return this.locMinRateDescriptionValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxRateDescription",{get:function(){return this.locMaxRateDescription.text},set:function(e){this.locMaxRateDescription.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locMaxRateDescription",{get:function(){return this.locMaxRateDescriptionValue},enumerable:!0,configurable:!0}),t}(o.a);l.defaultRateValues=[],i.a.setData(l.defaultRateValues,[1,2,3,4,5]),s.a.metaData.addClass("rating",["hasComment:boolean",{name:"rateValues:itemvalues",onGetValue:function(e){return i.a.getData(e.rateValues)},onSetValue:function(e,t){e.rateValues=t}},{name:"minRateDescription",alternativeName:"mininumRateDescription",serializationProperty:"locMinRateDescription"},{name:"maxRateDescription",alternativeName:"maximumRateDescription",serializationProperty:"locMaxRateDescription"}],function(){return new l("")},"question"),a.a.Instance.registerQuestion("rating",function(e){return new l(e)})},function(e,t,n){"use strict";var r=n(0),i=n(7),o=n(2),s=n(10),a=n(8);n.d(t,"a",function(){return u});var u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=t,n.size=25,n.inputTypeValue="text",n.locPlaceHolderValue=new a.a(n),n}return r.b(t,e),t.prototype.getType=function(){return"text"},Object.defineProperty(t.prototype,"inputType",{get:function(){return this.inputTypeValue},set:function(e){var t=e.toLowerCase();this.inputTypeValue="datetime_local"===t?"datetime-local":t},enumerable:!0,configurable:!0}),t.prototype.isEmpty=function(){return e.prototype.isEmpty.call(this)||""===this.value},t.prototype.supportGoNextPageAutomatic=function(){return!0},Object.defineProperty(t.prototype,"placeHolder",{get:function(){return this.locPlaceHolder.text},set:function(e){this.locPlaceHolder.text=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locPlaceHolder",{get:function(){return this.locPlaceHolderValue},enumerable:!0,configurable:!0}),t.prototype.setNewValue=function(t){t=this.correctValueType(t),e.prototype.setNewValue.call(this,t)},t.prototype.correctValueType=function(e){return e&&("number"==this.inputType||"range"==this.inputType)?this.isNumber(e)?parseFloat(e):"":e},t.prototype.isNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},t}(s.a);o.a.metaData.addClass("text",[{name:"inputType",default:"text",choices:["color","date","datetime","datetime-local","email","month","number","password","range","tel","text","time","url","week"]},{name:"size:number",default:25},{name:"placeHolder",serializationProperty:"locPlaceHolder"}],function(){return new u("")},"question"),i.a.Instance.registerQuestion("text",function(e){return new u(e)})},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(25);n.d(t,"a",function(){return s});var s=function(e){function t(t){var n=e.call(this)||this;return n.surveyValue=n.createSurvey(t),n.surveyValue.showTitle=!1,"undefined"!=typeof document&&(n.windowElement=document.createElement("div")),n}return r.b(t,e),t.prototype.getType=function(){return"window"},Object.defineProperty(t.prototype,"survey",{get:function(){return this.surveyValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isShowing",{get:function(){return this.isShowingValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isExpanded",{get:function(){return this.isExpandedValue},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"title",{get:function(){return this.survey.title},set:function(e){this.survey.title=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"locTitle",{get:function(){return this.survey.locTitle},enumerable:!0,configurable:!0}),t.prototype.expand=function(){this.expandcollapse(!0)},t.prototype.collapse=function(){this.expandcollapse(!1)},t.prototype.createSurvey=function(e){return new o.a(e)},t.prototype.expandcollapse=function(e){this.isExpandedValue=e},t}(i.b);s.surveyElementName="windowSurveyJS"},function(e,t,n){"use strict";var r=n(0),i=n(6),o=n(2);n.d(t,"e",function(){return s}),n.d(t,"a",function(){return a}),n.d(t,"d",function(){return u}),n.d(t,"b",function(){return l}),n.d(t,"c",function(){return c});var s=function(e){function t(){var t=e.call(this)||this;return t.opValue="equal",t}return r.b(t,e),Object.defineProperty(t,"operators",{get:function(){return null!=t.operatorsValue?t.operatorsValue:(t.operatorsValue={empty:function(e,t){return!e},notempty:function(e,t){return!!e},equal:function(e,t){return e==t},notequal:function(e,t){return e!=t},contains:function(e,t){return e&&e.indexOf&&e.indexOf(t)>-1},notcontains:function(e,t){return!e||!e.indexOf||-1==e.indexOf(t)},greater:function(e,t){return e>t},less:function(e,t){return e<t},greaterorequal:function(e,t){return e>=t},lessorequal:function(e,t){return e<=t}},t.operatorsValue)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"operator",{get:function(){return this.opValue},set:function(e){e&&(e=e.toLowerCase(),t.operators[e]&&(this.opValue=e))},enumerable:!0,configurable:!0}),t.prototype.check=function(e){t.operators[this.operator](e,this.value)?this.onSuccess():this.onFailure()},t.prototype.onSuccess=function(){},t.prototype.onFailure=function(){},t}(i.b);s.operatorsValue=null;var a=function(e){function t(){var t=e.call(this)||this;return t.owner=null,t}return r.b(t,e),t.prototype.setOwner=function(e){this.owner=e},Object.defineProperty(t.prototype,"isOnNextPage",{get:function(){return!1},enumerable:!0,configurable:!0}),t}(s),u=function(e){function t(){var t=e.call(this)||this;return t.pages=[],t.questions=[],t}return r.b(t,e),t.prototype.getType=function(){return"visibletrigger"},t.prototype.onSuccess=function(){this.onTrigger(this.onItemSuccess)},t.prototype.onFailure=function(){this.onTrigger(this.onItemFailure)},t.prototype.onTrigger=function(e){if(this.owner)for(var t=this.owner.getObjects(this.pages,this.questions),n=0;n<t.length;n++)e(t[n])},t.prototype.onItemSuccess=function(e){e.visible=!0},t.prototype.onItemFailure=function(e){e.visible=!1},t}(a),l=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getType=function(){return"completetrigger"},Object.defineProperty(t.prototype,"isOnNextPage",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.onSuccess=function(){this.owner&&this.owner.doComplete()},t}(a),c=function(e){function t(){return e.call(this)||this}return r.b(t,e),t.prototype.getType=function(){return"setvaluetrigger"},t.prototype.onSuccess=function(){this.setToName&&this.owner&&this.owner.setTriggerValue(this.setToName,this.setValue,this.isVariable)},t}(a);o.a.metaData.addClass("trigger",["operator","!value"]),o.a.metaData.addClass("surveytrigger",["!name"],null,"trigger"),o.a.metaData.addClass("visibletrigger",["pages","questions"],function(){return new u},"surveytrigger"),o.a.metaData.addClass("completetrigger",[],function(){return new l},"surveytrigger"),o.a.metaData.addClass("setvaluetrigger",["!setToName","setValue","isVariable:boolean"],function(){return new c},"surveytrigger")},function(e,t,n){"use strict";function r(e,t){var n,r,i=/(\.0+)+$/,o=e.replace(i,"").split("."),s=t.replace(i,"").split("."),a=Math.min(o.length,s.length);for(n=0;n<a;n++)if(r=parseInt(o[n],10)-parseInt(s[n],10))return r;return o.length-s.length}n.d(t,"a",function(){return c}),n.d(t,"b",function(){return r});var i=/(webkit)[ \/]([\w.]+)/,o=/(msie) (\d{1,2}\.\d)/,s=/(trident).*rv:(\d{1,2}\.\d)/,a=/(edge)\/((\d+)?[\w\.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))/,l=function(e){e=e.toLowerCase();var t={},n=o.exec(e)||s.exec(e)||a.exec(e)||e.indexOf("compatible")<0&&u.exec(e)||i.exec(e)||[],r=n[1],l=n[2];return"trident"===r||"edge"===r?r="msie":"mozilla"===r&&(r="firefox"),r&&(t[r]=!0,t.version=l),t},c=l(navigator.userAgent)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(39);n.d(t,"Version",function(){return r.a}),n.d(t,"AnswerCountValidator",function(){return r.b}),n.d(t,"EmailValidator",function(){return r.c}),n.d(t,"NumericValidator",function(){return r.d}),n.d(t,"RegexValidator",function(){return r.e}),n.d(t,"SurveyValidator",function(){return r.f}),n.d(t,"TextValidator",function(){return r.g}),n.d(t,"ValidatorResult",function(){return r.h}),n.d(t,"ValidatorRunner",function(){return r.i}),n.d(t,"Base",function(){return r.j}),n.d(t,"Event",function(){return r.k}),n.d(t,"SurveyError",function(){return r.l}),n.d(t,"ItemValue",function(){return r.m}),n.d(t,"LocalizableString",function(){return r.n}),n.d(t,"ChoicesRestfull",function(){return r.o}),n.d(t,"Condition",function(){return r.p}),n.d(t,"ConditionNode",function(){return r.q}),n.d(t,"ConditionRunner",function(){return r.r}),n.d(t,"ConditionsParser",function(){return r.s}),n.d(t,"ProcessValue",function(){return r.t}),n.d(t,"CustomError",function(){return r.u}),n.d(t,"ExceedSizeError",function(){return r.v}),n.d(t,"RequreNumericError",function(){return r.w}),n.d(t,"JsonError",function(){return r.x}),n.d(t,"JsonIncorrectTypeError",function(){return r.y}),n.d(t,"JsonMetadata",function(){return r.z}),n.d(t,"JsonMetadataClass",function(){return r.A}),n.d(t,"JsonMissingTypeError",function(){return r.B}),n.d(t,"JsonMissingTypeErrorBase",function(){return r.C}),n.d(t,"JsonObject",function(){return r.D}),n.d(t,"JsonObjectProperty",function(){return r.E}),n.d(t,"JsonRequiredPropertyError",function(){return r.F}),n.d(t,"JsonUnknownPropertyError",function(){return r.G}),n.d(t,"MatrixDropdownCell",function(){return r.H}),n.d(t,"MatrixDropdownColumn",function(){return r.I}),n.d(t,"MatrixDropdownRowModelBase",function(){return r.J}),n.d(t,"QuestionMatrixDropdownModelBase",function(){return r.K}),n.d(t,"MatrixDropdownRowModel",function(){return r.L}),n.d(t,"QuestionMatrixDropdownModel",function(){return r.M}),n.d(t,"MatrixDynamicRowModel",function(){return r.N}),n.d(t,"QuestionMatrixDynamicModel",function(){return r.O}),n.d(t,"MatrixRowModel",function(){return r.P}),n.d(t,"QuestionMatrixModel",function(){return r.Q}),n.d(t,"MultipleTextItemModel",function(){return r.R}),n.d(t,"QuestionMultipleTextModel",function(){return r.S}),n.d(t,"PanelModel",function(){return r.T}),n.d(t,"PanelModelBase",function(){return r.U}),n.d(t,"QuestionRowModel",function(){return r.V}),n.d(t,"PageModel",function(){return r.W}),n.d(t,"Question",function(){return r.X}),n.d(t,"QuestionBase",function(){return r.Y}),n.d(t,"QuestionCheckboxBase",function(){return r.Z}),n.d(t,"QuestionSelectBase",function(){return r._0}),n.d(t,"QuestionCheckboxModel",function(){return r._1}),n.d(t,"QuestionCommentModel",function(){return r._2}),n.d(t,"QuestionDropdownModel",function(){return r._3}),n.d(t,"ElementFactory",function(){return r._5}),n.d(t,"QuestionFileModel",function(){return r._6}),n.d(t,"QuestionHtmlModel",function(){return r._7}),n.d(t,"QuestionRadiogroupModel",function(){return r._8}),n.d(t,"QuestionRatingModel",function(){return r._9}),n.d(t,"QuestionTextModel",function(){return r._10}),n.d(t,"SurveyModel",function(){return r._11}),n.d(t,"SurveyTrigger",function(){return r._12}),n.d(t,"SurveyTriggerComplete",function(){return r._13}),n.d(t,"SurveyTriggerSetValue",function(){return r._14}),n.d(t,"SurveyTriggerVisible",function(){return r._15}),n.d(t,"Trigger",function(){return r._16}),n.d(t,"SurveyWindowModel",function(){return r._17}),n.d(t,"TextPreProcessor",function(){return r._18}),n.d(t,"dxSurveyService",function(){return r._19}),n.d(t,"surveyLocalization",function(){return r._20}),n.d(t,"surveyStrings",function(){return r._21}),n.d(t,"QuestionCustomWidget",function(){return r._22}),n.d(t,"CustomWidgetCollection",function(){return r._23});var i=(n(38),n(0));n.d(t,"__assign",function(){return i.a}),n.d(t,"__extends",function(){return i.b}),n.d(t,"__decorate",function(){return i.c});var o=n(13);n.d(t,"defaultStandardCss",function(){return o.a});var s=n(36);n.d(t,"defaultBootstrapCss",function(){return s.a});var a=n(37);n.d(t,"defaultBootstrapMaterialCss",function(){return a.a});var u=n(28);n.d(t,"Survey",function(){return u.a});var l=n(16);n.d(t,"ReactSurveyModel",function(){return l.a}),n.d(t,"Model",function(){return l.a});var c=n(18);n.d(t,"SurveyNavigationBase",function(){return c.a});var h=n(29);n.d(t,"SurveyNavigation",function(){return h.a});var p=n(31);n.d(t,"SurveyPage",function(){return p.a}),n.d(t,"SurveyRow",function(){return p.b});var d=n(15);n.d(t,"SurveyQuestion",function(){return d.a}),n.d(t,"SurveyQuestionErrors",function(){return d.b});var f=n(4);n.d(t,"SurveyElementBase",function(){return f.a}),n.d(t,"SurveyQuestionElementBase",function(){return f.b});var m=n(12);n.d(t,"SurveyQuestionCommentItem",function(){return m.a}),n.d(t,"SurveyQuestionComment",function(){return m.b});var g=n(41);n.d(t,"SurveyQuestionCheckbox",function(){return g.a}),n.d(t,"SurveyQuestionCheckboxItem",function(){return g.b});var y=n(42);n.d(t,"SurveyQuestionDropdown",function(){return y.a});var v=n(46);n.d(t,"SurveyQuestionMatrixDropdown",function(){return v.a}),n.d(t,"SurveyQuestionMatrixDropdownRow",function(){return v.b});var b=n(45);n.d(t,"SurveyQuestionMatrix",function(){return b.a}),n.d(t,"SurveyQuestionMatrixRow",function(){return b.b});var C=n(44);n.d(t,"SurveyQuestionHtml",function(){return C.a});var w=n(43);n.d(t,"SurveyQuestionFile",function(){return w.a});var x=n(48);n.d(t,"SurveyQuestionMultipleText",function(){return x.a}),n.d(t,"SurveyQuestionMultipleTextItem",function(){return x.b});var V=n(49);n.d(t,"SurveyQuestionRadiogroup",function(){return V.a});var P=n(51);n.d(t,"SurveyQuestionText",function(){return P.a});var T=n(47);n.d(t,"SurveyQuestionMatrixDynamic",function(){return T.a}),n.d(t,"SurveyQuestionMatrixDynamicRow",function(){return T.b});var O=n(30);n.d(t,"SurveyProgress",function(){return O.a});var R=n(50);n.d(t,"SurveyQuestionRating",function(){return R.a});var q=n(40);n.d(t,"SurveyWindow",function(){return q.a});var S=n(5);n.d(t,"ReactQuestionFactory",function(){return S.a}),n.d(t,"QuestionFactory",function(){return S.a})}])});
tests/unit/autoComplete/autoComplete.handleInputFocus.spec.js
Travix-International/travix-ui-kit
import React from 'react'; import { shallow } from 'enzyme'; import AutoComplete from '../../../components/autoComplete/autoComplete'; import AutoCompleteItem from '../../../components/autoComplete/autoCompleteItem'; describe('AutoComplete: handleInputFocus', () => { it('should call selectInput and update state with correct data', () => { AutoComplete.prototype.selectInput = jest.fn(); const onFocus = jest.fn(); const e = { target: {} }; const component = shallow( <AutoComplete name="autocomplete" > <AutoCompleteItem value="value" > item </AutoCompleteItem> </AutoComplete> ); component.instance().handleInputFocus(e); expect(component.instance().state.open).toEqual(true); expect(component.instance().state.activeKey).toEqual(0); expect(component.instance().selectInput).toBeCalled(); expect(onFocus).not.toBeCalled(); }); it('should not update state when open is true', () => { AutoComplete.prototype.selectInput = jest.fn(); const onFocus = jest.fn(); const e = { target: {} }; const component = shallow( <AutoComplete name="autocomplete" > <AutoCompleteItem value="value" > item </AutoCompleteItem> </AutoComplete> ); component.instance().setState({ open: true }); component.instance().handleInputFocus(e); expect(component.instance().state.activeKey).toEqual(undefined); expect(onFocus).not.toBeCalled(); }); it('should call passed onFocus with correct data', () => { AutoComplete.prototype.selectInput = jest.fn(); const onFocus = jest.fn(); const e = { target: {} }; const component = shallow( <AutoComplete name="autocomplete" onFocus={onFocus} > <AutoCompleteItem value="value" > item </AutoCompleteItem> </AutoComplete> ); component.instance().handleInputFocus(e); expect(onFocus).toBeCalledWith(e); }); it('should update state with correct active key info', () => { AutoComplete.prototype.selectInput = jest.fn(); const onFocus = jest.fn(); const e = { target: {} }; const component = shallow( <AutoComplete name="autocomplete" onFocus={onFocus} > <AutoCompleteItem value="value" > item </AutoCompleteItem> </AutoComplete> ); component.instance().setState({ activeKey: 5 }); component.instance().handleInputFocus(e); expect(component.instance().state.activeKey).toEqual(5); }); });
examples/js/column-filter/text-filter-with-default-value.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class TextFilterWithDefaultValue extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' filter={ { type: 'TextFilter', defaultValue: '0' } }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
client/packages/core-dashboard-worona/src/dashboard/loading-dashboard-theme-worona/components/Footer/index.js
worona/worona-dashboard
/* eslint-disable max-len */ import React from 'react'; export const Footer = () => ( <svg width="133px" height="12px" viewBox="0 0 133 12" version="1.1"> <title>powered by worona</title> <g id="logo---1.0" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd"> <g id="Artboard-2" transform="translate(-121.000000, -615.000000)" fill="#9B9B9B"> <g id="Group" transform="translate(101.000000, 247.000000)"> <path d="M25.1634996,373.942 C25.1634996,373.318664 24.9820015,372.827335 24.6189996,372.468 C24.2559978,372.108665 23.8233355,371.929 23.3209996,371.929 C22.8186638,371.929 22.3860015,372.112331 22.0229996,372.479 C21.6599978,372.845668 21.4784996,373.340664 21.4784996,373.964 C21.4784996,374.587336 21.6599978,375.084165 22.0229996,375.4545 C22.3860015,375.824835 22.8168305,376.01 23.3154996,376.01 C23.8141688,376.01 24.2468311,375.821169 24.6134996,375.4435 C24.9801681,375.065831 25.1634996,374.565336 25.1634996,373.942 L25.1634996,373.942 Z M23.5904996,370.84 C24.4045037,370.84 25.0828303,371.12783 25.6254996,371.7035 C26.168169,372.27917 26.4394996,373.027162 26.4394996,373.9475 C26.4394996,374.867838 26.1663357,375.623164 25.6199996,376.2135 C25.0736636,376.803836 24.3971703,377.099 23.5904996,377.099 C23.1138306,377.099 22.6958348,376.987168 22.3364996,376.7635 C21.9771645,376.539832 21.6911674,376.241002 21.4784996,375.867 L21.4784996,379.882 L20.2244996,379.882 L20.2244996,370.939 L21.4784996,370.939 L21.4784996,372.017 C21.683834,371.664998 21.9679978,371.380834 22.3309996,371.1645 C22.6940015,370.948166 23.1138306,370.84 23.5904996,370.84 L23.5904996,370.84 Z M33.4646173,373.964 C33.4646173,373.31133 33.2867858,372.803502 32.9311173,372.4405 C32.5754489,372.077498 32.1446199,371.896 31.6386173,371.896 C31.1326148,371.896 30.7072857,372.077498 30.3626173,372.4405 C30.0179489,372.803502 29.8456173,373.313163 29.8456173,373.9695 C29.8456173,374.625837 30.0142823,375.135498 30.3516173,375.4985 C30.6889524,375.861502 31.1087815,376.043 31.6111173,376.043 C32.1134532,376.043 32.5479488,375.859668 32.9146173,375.493 C33.2812858,375.126331 33.4646173,374.61667 33.4646173,373.964 L33.4646173,373.964 Z M29.4276173,376.2355 C28.8556145,375.65983 28.5696173,374.904505 28.5696173,373.9695 C28.5696173,373.034495 28.864781,372.27917 29.4551173,371.7035 C30.0454536,371.12783 30.7806129,370.84 31.6606173,370.84 C32.5406217,370.84 33.275781,371.12783 33.8661173,371.7035 C34.4564536,372.27917 34.7516173,373.032662 34.7516173,373.964 C34.7516173,374.895338 34.4491204,375.650664 33.8441173,376.23 C33.2391143,376.809336 32.4947884,377.099 31.6111173,377.099 C30.7274462,377.099 29.9996202,376.81117 29.4276173,376.2355 L29.4276173,376.2355 Z M44.196735,370.939 L45.428735,370.939 L43.547735,377 L42.227735,377 L41.006735,372.523 L39.785735,377 L38.465735,377 L36.573735,370.939 L37.849735,370.939 L39.114735,375.812 L40.401735,370.939 L41.710735,370.939 L42.942735,375.79 L44.196735,370.939 Z M50.2098527,377.099 C49.3298483,377.099 48.6148555,376.813003 48.0648527,376.241 C47.51485,375.668997 47.2398527,374.910005 47.2398527,373.964 C47.2398527,373.017995 47.5185166,372.260836 48.0758527,371.6925 C48.6331888,371.124164 49.3536816,370.84 50.2373527,370.84 C51.1210238,370.84 51.83785,371.113164 52.3878527,371.6595 C52.9378555,372.205836 53.2128527,372.918996 53.2128527,373.799 C53.2128527,374.011668 53.1981862,374.209666 53.1688527,374.393 L48.5268527,374.393 C48.5561862,374.899003 48.7266845,375.300499 49.0383527,375.5975 C49.3500209,375.894501 49.740517,376.043 50.2098527,376.043 C50.8918561,376.043 51.3721846,375.760669 51.6508527,375.196 L53.0038527,375.196 C52.8205185,375.753336 52.4868551,376.209832 52.0028527,376.5655 C51.5188503,376.921168 50.9211896,377.099 50.2098527,377.099 L50.2098527,377.099 Z M51.4088527,372.3415 C51.0861844,372.044499 50.693855,371.896 50.2318527,371.896 C49.7698504,371.896 49.3830209,372.044499 49.0713527,372.3415 C48.7596845,372.638501 48.5818529,373.036331 48.5378527,373.535 L51.9038527,373.535 C51.8965193,373.036331 51.731521,372.638501 51.4088527,372.3415 L51.4088527,372.3415 Z M56.9929704,370.939 L56.9929704,371.995 C57.381639,371.224996 57.986633,370.84 58.8079704,370.84 L58.8079704,372.138 L58.4889704,372.138 C57.9976346,372.138 57.6254717,372.262665 57.3724704,372.512 C57.1194691,372.761335 56.9929704,373.193997 56.9929704,373.81 L56.9929704,377 L55.7389704,377 L55.7389704,370.939 L56.9929704,370.939 Z M63.8090881,377.099 C62.9290837,377.099 62.2140908,376.813003 61.6640881,376.241 C61.1140853,375.668997 60.8390881,374.910005 60.8390881,373.964 C60.8390881,373.017995 61.117752,372.260836 61.6750881,371.6925 C62.2324242,371.124164 62.952917,370.84 63.8365881,370.84 C64.7202592,370.84 65.4370853,371.113164 65.9870881,371.6595 C66.5370908,372.205836 66.8120881,372.918996 66.8120881,373.799 C66.8120881,374.011668 66.7974216,374.209666 66.7680881,374.393 L62.1260881,374.393 C62.1554216,374.899003 62.3259199,375.300499 62.6375881,375.5975 C62.9492563,375.894501 63.3397524,376.043 63.8090881,376.043 C64.4910915,376.043 64.97142,375.760669 65.2500881,375.196 L66.6030881,375.196 C66.4197538,375.753336 66.0860905,376.209832 65.6020881,376.5655 C65.1180857,376.921168 64.520425,377.099 63.8090881,377.099 L63.8090881,377.099 Z M65.0080881,372.3415 C64.6854198,372.044499 64.2930904,371.896 63.8310881,371.896 C63.3690858,371.896 62.9822563,372.044499 62.6705881,372.3415 C62.3589199,372.638501 62.1810883,373.036331 62.1370881,373.535 L65.5030881,373.535 C65.4957547,373.036331 65.3307564,372.638501 65.0080881,372.3415 L65.0080881,372.3415 Z M73.8812058,373.964 C73.8812058,373.340664 73.6997076,372.845668 73.3367058,372.479 C72.973704,372.112331 72.5428749,371.929 72.0442058,371.929 C71.5455366,371.929 71.1147076,372.108665 70.7517058,372.468 C70.388704,372.827335 70.2072058,373.318664 70.2072058,373.942 C70.2072058,374.565336 70.388704,375.065831 70.7517058,375.4435 C71.1147076,375.821169 71.5455366,376.01 72.0442058,376.01 C72.5428749,376.01 72.973704,375.824835 73.3367058,375.4545 C73.6997076,375.084165 73.8812058,374.587336 73.8812058,373.964 L73.8812058,373.964 Z M69.7452058,376.2135 C69.195203,375.623164 68.9202058,374.867838 68.9202058,373.9475 C68.9202058,373.027162 69.1933697,372.27917 69.7397058,371.7035 C70.2860418,371.12783 70.9662017,370.84 71.7802058,370.84 C72.2568748,370.84 72.676704,370.948166 73.0397058,371.1645 C73.4027076,371.380834 73.6832048,371.664998 73.8812058,372.017 L73.8812058,368.86 L75.1462058,368.86 L75.1462058,377 L73.8812058,377 L73.8812058,375.867 C73.6758714,376.241002 73.3935409,376.539832 73.0342058,376.7635 C72.6748706,376.987168 72.2568748,377.099 71.7802058,377.099 C70.9735351,377.099 70.2952085,376.803836 69.7452058,376.2135 L69.7452058,376.2135 Z M87.6234412,373.942 C87.6234412,373.318664 87.441943,372.827335 87.0789412,372.468 C86.7159393,372.108665 86.283277,371.929 85.7809412,371.929 C85.2786053,371.929 84.845943,372.112331 84.4829412,372.479 C84.1199393,372.845668 83.9384412,373.340664 83.9384412,373.964 C83.9384412,374.587336 84.1199393,375.084165 84.4829412,375.4545 C84.845943,375.824835 85.276772,376.01 85.7754412,376.01 C86.2741103,376.01 86.7067727,375.821169 87.0734412,375.4435 C87.4401097,375.065831 87.6234412,374.565336 87.6234412,373.942 L87.6234412,373.942 Z M86.0504412,370.84 C86.8644452,370.84 87.5427718,371.12783 88.0854412,371.7035 C88.6281105,372.27917 88.8994412,373.027162 88.8994412,373.9475 C88.8994412,374.867838 88.6262772,375.623164 88.0799412,376.2135 C87.5336051,376.803836 86.8571119,377.099 86.0504412,377.099 C85.5737721,377.099 85.1557763,376.987168 84.7964412,376.7635 C84.437106,376.539832 84.1511089,376.241002 83.9384412,375.867 L83.9384412,377 L82.6844412,377 L82.6844412,368.86 L83.9384412,368.86 L83.9384412,372.017 C84.1437755,371.664998 84.4279393,371.380834 84.7909412,371.1645 C85.153943,370.948166 85.5737721,370.84 86.0504412,370.84 L86.0504412,370.84 Z M93.1085588,376.901 L90.7215588,370.939 L92.1185588,370.939 L93.8235588,375.559 L95.5945588,370.939 L96.8925588,370.939 L93.1745588,379.849 L91.8765588,379.849 L93.1085588,376.901 Z M110.623794,370.862 L112.394794,370.862 L110.557794,377 L108.533794,377 L107.675794,373.37 L106.806794,377 L104.782794,377 L102.945794,370.862 L104.826794,370.862 L105.783794,375.174 L106.729794,370.862 L108.720794,370.862 L109.666794,375.174 L110.623794,370.862 Z M118.605912,373.931 C118.605912,373.432331 118.47758,373.052835 118.220912,372.7925 C117.964244,372.532165 117.659914,372.402 117.307912,372.402 C116.95591,372.402 116.653413,372.532165 116.400412,372.7925 C116.147411,373.052835 116.020912,373.432331 116.020912,373.931 C116.020912,374.429669 116.151077,374.810999 116.411412,375.075 C116.671747,375.339001 116.97791,375.471 117.329912,375.471 C117.681914,375.471 117.982577,375.339001 118.231912,375.075 C118.481246,374.810999 118.605912,374.429669 118.605912,373.931 L118.605912,373.931 Z M114.106912,373.92 C114.106912,372.973995 114.414909,372.216836 115.030912,371.6485 C115.646915,371.080164 116.409574,370.796 117.318912,370.796 C118.22825,370.796 118.989076,371.080164 119.601412,371.6485 C120.213748,372.216836 120.519912,372.973995 120.519912,373.92 C120.519912,374.866005 120.215582,375.628664 119.606912,376.208 C118.998242,376.787336 118.23925,377.077 117.329912,377.077 C116.420574,377.077 115.656082,376.787336 115.036412,376.208 C114.416742,375.628664 114.106912,374.866005 114.106912,373.92 L114.106912,373.92 Z M124.90503,370.862 L124.90503,372.006 C125.345032,371.199329 125.931693,370.796 126.66503,370.796 L126.66503,372.71 L126.20303,372.71 C125.770361,372.71 125.445864,372.812666 125.22953,373.018 C125.013195,373.223334 124.90503,373.582664 124.90503,374.096 L124.90503,377 L123.02403,377 L123.02403,370.862 L124.90503,370.862 Z M133.041147,373.931 C133.041147,373.432331 132.912815,373.052835 132.656147,372.7925 C132.399479,372.532165 132.095149,372.402 131.743147,372.402 C131.391146,372.402 131.088649,372.532165 130.835647,372.7925 C130.582646,373.052835 130.456147,373.432331 130.456147,373.931 C130.456147,374.429669 130.586313,374.810999 130.846647,375.075 C131.106982,375.339001 131.413146,375.471 131.765147,375.471 C132.117149,375.471 132.417813,375.339001 132.667147,375.075 C132.916482,374.810999 133.041147,374.429669 133.041147,373.931 L133.041147,373.931 Z M128.542147,373.92 C128.542147,372.973995 128.850144,372.216836 129.466147,371.6485 C130.08215,371.080164 130.844809,370.796 131.754147,370.796 C132.663485,370.796 133.424311,371.080164 134.036647,371.6485 C134.648984,372.216836 134.955147,372.973995 134.955147,373.92 C134.955147,374.866005 134.650817,375.628664 134.042147,376.208 C133.433478,376.787336 132.674485,377.077 131.765147,377.077 C130.855809,377.077 130.091317,376.787336 129.471647,376.208 C128.851978,375.628664 128.542147,374.866005 128.542147,373.92 L128.542147,373.92 Z M139.340265,370.862 L139.340265,371.764 C139.728934,371.118663 140.348594,370.796 141.199265,370.796 C141.903268,370.796 142.473429,371.030664 142.909765,371.5 C143.3461,371.969336 143.564265,372.607329 143.564265,373.414 L143.564265,377 L141.694265,377 L141.694265,373.667 C141.694265,373.270998 141.589766,372.964834 141.380765,372.7485 C141.171764,372.532166 140.883933,372.424 140.517265,372.424 C140.150596,372.424 139.862766,372.532166 139.653765,372.7485 C139.444764,372.964834 139.340265,373.270998 139.340265,373.667 L139.340265,377 L137.459265,377 L137.459265,370.862 L139.340265,370.862 Z M150.600383,373.931 C150.600383,373.446998 150.464717,373.074835 150.193383,372.8145 C149.922048,372.554165 149.610384,372.424 149.258383,372.424 C148.906381,372.424 148.594717,372.555999 148.323383,372.82 C148.052048,373.084001 147.916383,373.457998 147.916383,373.942 C147.916383,374.426002 148.052048,374.798165 148.323383,375.0585 C148.594717,375.318835 148.906381,375.449 149.258383,375.449 C149.610384,375.449 149.922048,375.317001 150.193383,375.053 C150.464717,374.788999 150.600383,374.415002 150.600383,373.931 L150.600383,373.931 Z M146.002383,373.942 C146.002383,373.025329 146.273713,372.271836 146.816383,371.6815 C147.359052,371.091164 148.020879,370.796 148.801883,370.796 C149.582887,370.796 150.182381,371.085664 150.600383,371.665 L150.600383,370.862 L152.481383,370.862 L152.481383,377 L150.600383,377 L150.600383,376.109 C150.145714,376.754337 149.537053,377.077 148.774383,377.077 C148.011712,377.077 147.359052,376.78367 146.816383,376.197 C146.273713,375.61033 146.002383,374.858671 146.002383,373.942 L146.002383,373.942 Z" id="powered-by-worona" /> </g> </g> </g> </svg> ); export default Footer;
src/Menus/PitchToolBar.js
kevinleclair1/pitch_fx_visualizer
import React from 'react'; import PropTypes from 'prop-types'; import { ToolbarGroup } from 'material-ui/Toolbar'; import Toggle from 'material-ui/Toggle'; import createContainer from '../containers/GenericContainer.js'; import { createStructuredSelector } from 'reselect'; import { selectors as sceneSelectors, actions as sceneActions } from '../redux/scene.js'; const toggleLabelStyle = { color: 'white' }; const PitchToolBar = ({ onToggleClick, toggled }) => { const toggleClicked = (event, isInputChecked) => onToggleClick(isInputChecked) return ( <ToolbarGroup> <Toggle label={'Animate Pitch'} toggled={toggled} onToggle={toggleClicked} labelStyle={toggleLabelStyle} /> </ToolbarGroup> ); }; PitchToolBar.propTypes = { onToggleClick: PropTypes.func.isRequired, toggled: PropTypes.bool.isRequired }; export default createContainer({ actions: { onToggleClick: sceneActions.togglePitchAnimation }, mapStateToProps: createStructuredSelector({ toggled: sceneSelectors.isPitchAnimating }), Component: PitchToolBar });
src/components/Advs/HomeContentRightAdv/HomeContentRightAdv.js
febobo/react-redux-start
import React, { Component } from 'react'; import GoogleAdv from '../../GoogleAdv' import BaseConfig from '../../../BaseConfig'; import OfferWow from '../../OfferWow' import { Tag } from 'antd' import classes from './HomeContentRightAdv.scss' export default class HomeContentRightAdv extends Component { constructor(props){ super(props); this._lu = this._lu.bind(this); this.state = { showLu : false } } // @type Number(1,2,3) => (super,Clix,Ptcw) _lu(type){ this.setState({ showLu : !this.state.showLu, type:type }); } componentWillUnmount() { } showGoogleAdv (){ const advProps = { style : {display:"inline-block",width:"300px",height:"250px"}, client : 'ca-pub-5722932343401905', slot : '9366759071', // advBoxStyle : { paddingTop:"25px", textAlign : "center"} } return ( <GoogleAdv {...advProps} /> ) } render() { const { client , slot , style , advBoxStyle ,user } = this.props; return ( <div> { this.state.showLu ? <OfferWow user={user} config={BaseConfig} lu={this._lu} type={this.state.type} /> : null } { BaseConfig.show_google_adv ? this.showGoogleAdv() :null } { BaseConfig.show_moon_adv ? <div className={classes.buttonWrap}> <div> <span color="blue" onClick={ ()=>this._lu(1)} >SuperReward</span> </div> <div> <span color="blue" onClick={ ()=>this._lu(2)} >PTCWALL</span> </div> <div> <span color="blue" onClick={ ()=>this._lu(3)} >ClixWall</span> </div> </div> :null } </div> ); } }
src/components/Pagination/Pagination.js
colmdoyle/colmdoyle.github.io
// @flow strict import React from 'react'; import classNames from 'classnames/bind'; import { Link } from 'gatsby'; import { PAGINATION } from '../../constants'; import styles from './Pagination.module.scss'; type Props = { prevPagePath: string, nextPagePath: string, hasNextPage: boolean, hasPrevPage: boolean }; const cx = classNames.bind(styles); const Pagination = ({ prevPagePath, nextPagePath, hasNextPage, hasPrevPage }: Props) => { const prevClassName = cx({ 'pagination__prev-link': true, 'pagination__prev-link--disable': !hasPrevPage }); const nextClassName = cx({ 'pagination__next-link': true, 'pagination__next-link--disable': !hasNextPage }); return ( <div className={styles['pagination']}> <div className={styles['pagination__prev']}> <Link rel="prev" to={hasPrevPage ? prevPagePath : '/'} className={prevClassName}>{PAGINATION.PREV_PAGE}</Link> </div> <div className={styles['pagination__next']}> <Link rel="next" to={hasNextPage ? nextPagePath : '/'} className={nextClassName}>{PAGINATION.NEXT_PAGE}</Link> </div> </div> ); }; export default Pagination;
src/svg-icons/action/list.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionList = (props) => ( <SvgIcon {...props}> <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/> </SvgIcon> ); ActionList = pure(ActionList); ActionList.displayName = 'ActionList'; ActionList.muiName = 'SvgIcon'; export default ActionList;
src/js/components/Pagination/stories/NumberMiddlePages.js
grommet/grommet
import React from 'react'; import { Box, Pagination, Text } from 'grommet'; export const NumberMiddlePages = () => ( // Uncomment <Grommet> lines when using outside of storybook // <Grommet theme={...}> <Box pad="small" gap="medium"> <Box> <Text>numberMiddlePages = 4 (number of pages in the middle)</Text> <Pagination numberItems={237} page={10} numberMiddlePages={4} /> </Box> <Box> <Text>numberMiddlePages = 5 (number of pages in the middle)</Text> <Pagination numberItems={237} page={10} numberMiddlePages={5} /> </Box> </Box> // </Grommet> ); NumberMiddlePages.storyName = 'Number middle pages'; export default { title: 'Controls/Pagination/Number middle pages', };
lib/svg-icons/device/bluetooth-connected.js
bdsabian/material-ui-old
'use strict'; var React = require('react'); var PureRenderMixin = require('react-addons-pure-render-mixin'); var SvgIcon = require('../../svg-icon'); var DeviceBluetoothConnected = React.createClass({ displayName: 'DeviceBluetoothConnected', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M7 12l-2-2-2 2 2 2 2-2zm10.71-4.29L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88zM19 10l-2 2 2 2 2-2-2-2z' }) ); } }); module.exports = DeviceBluetoothConnected;
src/modules/editor/components/popovers/formattingTooltip/FormattingTooltipLink/FormattingTooltipLink.js
CtrHellenicStudies/Commentary
import React from 'react' import autoBind from 'react-autobind'; import { connect } from 'react-redux'; // redux import editorActions from '../../../../actions'; // component import FormattingTooltipItemButton from '../FormattingTooltipItemButton'; import { MdInsertLink } from "react-icons/md"; class FormattingTooltipLink extends React.Component { constructor(props) { super(props); autoBind(this); } async promptForLink(e) { e.preventDefault(); const { setTooltip, tooltip } = this.props; await setTooltip({ ...tooltip, mode: 'link' }); } isActive() { const { editorState } = this.props; if (!editorState) { return null; } let selection = editorState.getSelection(); let activeBlockType = editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return 'LINK' === activeBlockType; } render() { return ( <FormattingTooltipItemButton className={`${this.isActive() ? 'active' : ''}`} onClick={this.promptForLink} > <MdInsertLink /> </FormattingTooltipItemButton> ); } } const mapStateToProps = state => ({ ...state.editor, }); const mapDispatchToProps = dispatch => ({ setTooltip: (tooltip) => { dispatch(editorActions.setTooltip(tooltip)); }, }); export default connect( mapStateToProps, mapDispatchToProps, )(FormattingTooltipLink);
sites/all/modules/jquery_update/replace/jquery/1.7/jquery.js
drewzboto/revere
/*! * jQuery JavaScript Library v1.7.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Mon Nov 21 21:11:03 2011 -0500 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return ( new Date() ).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!memory; } }; return self; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, marginDiv, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = marginDiv = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, conMarginTop, ptlm, vb, style, html, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; vb = "visibility:hidden;border:0;"; style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; html = "<div " + style + "><div></div></div>" + "<table " + style + " cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Figure out if the W3C box model works as expected div.innerHTML = ""; div.style.width = div.style.paddingLeft = "1px"; jQuery.boxModel = support.boxModel = div.offsetWidth === 2; if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.style.cssText = ptlm + vb; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); body.removeChild( container ); div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, attr, name, data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { attr = this[0].attributes; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } jQuery._data( this[0], "parsedAttrs", true ); } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var self = jQuery( this ), args = [ parts[0], value ]; self.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( data ) ? parseFloat( data ) : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { for ( var name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // 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" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, 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 i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; // See #9699 for explanation of this approach (setting first, then removal) jQuery.attr( elem, name, "" ); elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /\bhover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Determine handlers that should run if there are delegated events // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** 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( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { // If form was submitted by the user, bubble the event up the tree if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; jQuery.event.simulate( "change", this, event, true ); } }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on.call( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( var type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } 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, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); 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 new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, 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": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } 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 && 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 = Sizzle.attr ? Sizzle.attr( elem, name ) : 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 && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ); 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 ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.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.clean( arguments ); 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.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ]; if ( data && data.events ) { for ( var type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^([\-+])=([\-+.\de]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret === null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ( ret || 0 ); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight, i = 0, len = which.length; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i++ ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i++ ) { val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } } } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } responses.text = xhr.responseText; // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css(elem, "display") === "none" ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || 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 if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { 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._data( this.elem, "fxshow" + 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 p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Adds width/height step functions // Do not set anything below 0 jQuery.each([ "width", "height" ], function( i, prop ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.support.fixedPosition && 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.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.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.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
app/views/FrontPage/Visualizations/Statistics/Statistics.js
RcKeller/STF-Refresh
import React from 'react' import PropTypes from 'prop-types' import { compose } from 'redux' import { connect } from 'react-redux' import { connectRequest } from 'redux-query' import api from '../../../../services' import { Loading } from '../../../../components' import ProposalStatusByQuarter from './ProposalStatusByQuarter/ProposalStatusByQuarter' /* STATISTICAL VISUALIZATIONS Higher order component for general non-fiscal data (% projects funded, types funded...) - Percentage of projects funded (this year) - Categories of funded projects - Current Quarter Status (#drafts, in review, etc) */ @compose( connect(state => ({ statistics: state.db.statistics, year: state.config.year, quarter: state.config.quarter, categories: state.config.enums.categories, statuses: state.config.enums.statuses, screen: state.screen })), connectRequest( (props) => api.get('proposals', { query: { year: props.year }, select: ['title', 'year', 'number', 'quarter', 'status', 'organization', 'category', 'asked', 'received'], transform: statistics => ({ statistics }), update: ({ statistics: (prev, next) => next }), force: true }) ) ) class Statistics extends React.Component { static propTypes = { statistics: PropTypes.array.isRequired, quarter: PropTypes.string, categories: PropTypes.array.isRequired, statuses: PropTypes.array.isRequired, year: PropTypes.number.isRequired, screen: PropTypes.object } static defaultProps = { statistics: [], year: 2018, quarter: 'Autumn', categories: [], statuses: [] } render ( { statistics, quarter, year, categories, statuses } = this.props ) { const data = { statistics } return ( <section> <Loading render={Statistics} title='Statistical Visualization' tip='Visualizing Statistics...' > <ProposalStatusByQuarter {...data} year={year} /> </Loading> </section> ) } } export default Statistics
app/javascript/flavours/glitch/components/display_name.js
im-in-space/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { autoPlayGif } from 'flavours/glitch/util/initial_state'; export default class DisplayName extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map, className: PropTypes.string, inline: PropTypes.bool, localDomain: PropTypes.string, others: ImmutablePropTypes.list, handleClick: PropTypes.func, }; handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } render() { const { account, className, inline, localDomain, others, onAccountClick } = this.props; const computedClass = classNames('display-name', { inline }, className); if (!account) return null; let displayName, suffix; let acct = account.get('acct'); if (acct.indexOf('@') === -1 && localDomain) { acct = `${acct}@${localDomain}`; } if (others && others.size > 0) { displayName = others.take(2).map(a => ( <a href={a.get('url')} target='_blank' onClick={(e) => onAccountClick(a.get('acct'), e)} title={`@${a.get('acct')}`} rel='noopener noreferrer' > <bdi key={a.get('id')}> <strong className='display-name__html' dangerouslySetInnerHTML={{ __html: a.get('display_name_html') }} /> </bdi> </a> )).reduce((prev, cur) => [prev, ', ', cur]); if (others.size - 2 > 0) { displayName.push(` +${others.size - 2}`); } suffix = ( <a href={account.get('url')} target='_blank' onClick={(e) => onAccountClick(account.get('acct'), e)} rel='noopener noreferrer'> <span className='display-name__account'>@{acct}</span> </a> ); } else { displayName = <bdi><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: account.get('display_name_html') }} /></bdi>; suffix = <span className='display-name__account'>@{acct}</span>; } return ( <span className={computedClass} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> {displayName} {inline ? ' ' : null} {suffix} </span> ); } }
pages/board.js
passify/samlify-sp
/* This page is a protected page */ import React, { Component } from 'react'; import Router from 'next/router'; import Link from 'next/link'; import markProtected from '../components/protected'; import { Row, Col } from 'antd'; import { Input } from 'antd'; import { Button } from 'antd'; import { Radio } from 'antd'; const RadioButton = Radio.Button; const RadioGroup = Radio.Group; const { TextArea } = Input; class Board extends Component { static async getInitialProps(ctx) { /* won't run there because it's invoked in parent's one unless invoke ComposedComponent.getInitialProps */ } constructor(props) { super(props); const formData = { metadata: '', privateKey: '', privateKeyPass: '', isAssertionEncrypted: false, wantLogoutRequestSigned: false, wantLogoutResponseSigned: false, encPrivateKey: '', encPrivateKeyPass: '' }; this.state = { formData }; } componentDidMount() { this.setState({ formData: Object.assign(this.state.formData, this.getCachedFormData()) }); window.state = this.state; } getCachedFormData() { if (typeof window !== 'undefined') { return JSON.parse(localStorage.getItem('spconfig') || '{}'); } return {}; } async save() { const config = JSON.stringify(this.state.formData); if (typeof window !== 'undefined') { localStorage.setItem('spconfig', config); } await this.props.authService.fetch('/sp/edit', { method: 'POST', body: { config } }); } getMetadata() { window.open('/metadata'); } handleFormChange(e, field) { console.log(e.target.value, e.target.name, field); this.setState({ formData: { ...this.state.formData, [e.target.name || field]: e.target.value } }) } btoa(context) { if (typeof window !== 'undefined') { // browser return btoa(context); } // server side return Buffer.from(context).toString('base64'); } render() { const formData = this.state.formData; const { metadata, privateKey, privateKeyPass, isAssertionEncrypted, wantLogoutRequestSigned, wantLogoutResponseSigned, encPrivateKey, encPrivateKeyPass } = formData; return ( <div> <div className="ma3 tc center w-60 pa3 bg-light-yellow"> { `In this protected page, you can configure your service provider and the associated identity providers. To keep it simple and easy, we will store all the information in local storage, so it's highly recommended that not to include the secret key used in any dev/staging/production environment, in other words, it is only for testing purpose.` } </div> <div className="mt4 ml4 mr4 mb4 tc"> <div className="mt3 mb5"> <Button className="mr3" onClick={() => this.save()}>Save</Button> <Button className="mr3" onClick={() => this.getMetadata()}>Metadata</Button> <Button className="mr3" disabled onClick={() => {}}>Export</Button> <Button className="mr3" disabled onClick={() => {}}>Import</Button> </div> <Row gutter={24}> <Col className="mb3" xs={24} sm={12}> <div className="mb3"> <p className="tl pb2 b">Metadata for Service Provider</p> <TextArea name="metadata" value={metadata} rows={6} placeholder="Paste your metadata here" onChange={(e) => this.handleFormChange(e)} /> </div> <div className="mb3 pb4"> <Col xs={12} sm={12}> <p className="tl pb2 b">Encrypted assertion (SLO)</p> </Col> <Col className="tr" xs={12} sm={12}> <RadioGroup value={isAssertionEncrypted} name="isAssertionEncrypted" onChange={(e) => this.handleFormChange(e, 'isAssertionEncrypted')}> <RadioButton value={true}>Encrypted</RadioButton> <RadioButton value={false}>Ignore</RadioButton> </RadioGroup> </Col> </div> <div className="mb3 pb4"> <Col xs={12} sm={12}> <p className="tl pb2 b">Signed Request (for SP-initiated SLO)</p> </Col> <Col className="tr" xs={12} sm={12}> <RadioGroup value={wantLogoutRequestSigned} name="wantLogoutRequestSigned" onChange={(e) => this.handleFormChange(e, 'wantLogoutRequestSigned')}> <RadioButton value={true}>Signed</RadioButton> <RadioButton value={false}>Non-signed</RadioButton> </RadioGroup> </Col> </div> <div className="mb3"> <Col xs={12} sm={12}> <p className="tl pb2 b">Signed Response (for IdP-initiated SLO)</p> </Col> <Col className="tr" xs={12} sm={12}> <RadioGroup value={wantLogoutResponseSigned} name="wantLogoutResponseSigned" onChange={(e) => this.handleFormChange(e, 'wantLogoutResponseSigned')}> <RadioButton value={true}>Signed</RadioButton> <RadioButton value={false}>Non-signed</RadioButton> </RadioGroup> </Col> </div> </Col> <Col xs={24} sm={12}> <div className="mb3"> <p className="tl pb2 b">Secret Key (Signature), if has</p> <TextArea value={privateKey} name="privateKey" rows={5} placeholder="Paste your secret key here" onChange={(e) => this.handleFormChange(e)} /> </div> <div className="mb3"> <p className="tl pb2 b">Secret Key (Signature) Passphrase</p> <Input value={privateKeyPass} name="privateKeyPass" placeholder="Passphrase for secret key" onChange={(e) => this.handleFormChange(e)} /> </div> <div className="mb3"> <p className="tl pb2 b">Secret Key (Encryption), if has</p> <TextArea value={encPrivateKey} name="encPrivateKey" rows={5} placeholder="Paste your secret key here" onChange={(e) => this.handleFormChange(e)} /> </div> <div className="mb3"> <p className="tl pb2 b">Secret Key (Encryption) Passphrase</p> <Input value={encPrivateKeyPass} name="encPrivateKeyPass" placeholder="Passphrase for secret key" onChange={(e) => this.handleFormChange(e)} /> </div> </Col> </Row> </div> </div> ); } } export default markProtected(Board);
cm19/ReactJS/your-first-react-app-exercises-master/exercise-7/App.js
Brandon-J-Campbell/codemash
import React, { Component } from 'react'; import './App.css'; import Exercise from './Exercise'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Exercise 7</h1> <h2 className="sub-title">Convert a Component</h2> </header> <div className="exercise"> <Exercise /> </div> </div> ); } } export default App;
ajax/libs/tinymce/3.5.8/plugins/legacyoutput/editor_plugin_src.js
maruilian11/cdnjs
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing * * This plugin will force TinyMCE to produce deprecated legacy output such as font elements, u elements, align * attributes and so forth. There are a few cases where these old items might be needed for example in email applications or with Flash * * However you should NOT use this plugin if you are building some system that produces web contents such as a CMS. All these elements are * not apart of the newer specifications for HTML and XHTML. */ (function(tinymce) { // Override inline_styles setting to force TinyMCE to produce deprecated contents tinymce.onAddEditor.addToTop(function(tinymce, editor) { editor.settings.inline_styles = false; }); // Create the legacy ouput plugin tinymce.create('tinymce.plugins.LegacyOutput', { init : function(editor) { editor.onInit.add(function() { var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', fontSizes = tinymce.explode(editor.settings.font_size_style_values), schema = editor.schema; // Override some internal formats to produce legacy elements and attributes editor.formatter.register({ // Change alignment formats to use the deprecated align attribute alignleft : {selector : alignElements, attributes : {align : 'left'}}, aligncenter : {selector : alignElements, attributes : {align : 'center'}}, alignright : {selector : alignElements, attributes : {align : 'right'}}, alignfull : {selector : alignElements, attributes : {align : 'justify'}}, // Change the basic formatting elements to use deprecated element types bold : [ {inline : 'b', remove : 'all'}, {inline : 'strong', remove : 'all'}, {inline : 'span', styles : {fontWeight : 'bold'}} ], italic : [ {inline : 'i', remove : 'all'}, {inline : 'em', remove : 'all'}, {inline : 'span', styles : {fontStyle : 'italic'}} ], underline : [ {inline : 'u', remove : 'all'}, {inline : 'span', styles : {textDecoration : 'underline'}, exact : true} ], strikethrough : [ {inline : 'strike', remove : 'all'}, {inline : 'span', styles : {textDecoration: 'line-through'}, exact : true} ], // Change font size and font family to use the deprecated font element fontname : {inline : 'font', attributes : {face : '%value'}}, fontsize : { inline : 'font', attributes : { size : function(vars) { return tinymce.inArray(fontSizes, vars.value) + 1; } } }, // Setup font elements for colors as well forecolor : {inline : 'font', attributes : {color : '%value'}}, hilitecolor : {inline : 'font', styles : {backgroundColor : '%value'}} }); // Check that deprecated elements are allowed if not add them tinymce.each('b,i,u,strike'.split(','), function(name) { schema.addValidElements(name + '[*]'); }); // Add font element if it's missing if (!schema.getElementRule("font")) schema.addValidElements("font[face|size|color|style]"); // Add the missing and depreacted align attribute for the serialization engine tinymce.each(alignElements.split(','), function(name) { var rule = schema.getElementRule(name), found; if (rule) { if (!rule.attributes.align) { rule.attributes.align = {}; rule.attributesOrder.push('align'); } } }); // Listen for the onNodeChange event so that we can do special logic for the font size and font name drop boxes editor.onNodeChange.add(function(editor, control_manager) { var control, fontElm, fontName, fontSize; // Find font element get it's name and size fontElm = editor.dom.getParent(editor.selection.getNode(), 'font'); if (fontElm) { fontName = fontElm.face; fontSize = fontElm.size; } // Select/unselect the font name in droplist if (control = control_manager.get('fontselect')) { control.select(function(value) { return value == fontName; }); } // Select/unselect the font size in droplist if (control = control_manager.get('fontsizeselect')) { control.select(function(value) { var index = tinymce.inArray(fontSizes, value.fontSize); return index + 1 == fontSize; }); } }); }); }, getInfo : function() { return { longname : 'LegacyOutput', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/legacyoutput', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('legacyoutput', tinymce.plugins.LegacyOutput); })(tinymce);
src/components/view-flag/index.js
jl-/bronote
/** * disabled * once: false; true to trigger `handleAppear` on appeared & scrolling * handleAppear(currentStatus, previousStatus, flagDOM) * * @TODO add offset support * */ import React, { Component } from 'react'; import cx from 'classnames'; import { throttle } from '../../../utils'; import './style.scss'; const THROTTLE_MS = 100; const FLAG_REF = Symbol('flag'); const STATUS = { INIT: 0, ABOVE_VIEWPORT: 1, WITHIN_VIEWPORT: 2, BENEATH_VIEWPORT: 3 }; class ViewFlag extends Component { constructor(props, context) { super(props, context); this.state = { status: STATUS.INIT }; } componentDidUpdate(prevProps) { const props = this.props; const shouldReSubscribe = props.handleAppear !== prevProps.handleAppear || props.disabled !== prevProps.disabled || props.once !== prevProps.once; if (!shouldReSubscribe) return; if (typeof this.unsubscribe === 'function') this.unsubscribe(); this.subscribe(props); } componentDidMount() { this.subscribe(); } componentWillUnmount() { if (typeof this.unsubscribe === 'function') this.unsubscribe(); } subscribe(props = this.props) { const { disabled, handleAppear, throttleMS = THROTTLE_MS } = props; if (disabled !== true && typeof handleAppear === 'function' && typeof this.unsubscribe !== 'function') { const handler = throttle(this.trigger.bind(this, props), throttleMS); document.addEventListener('scroll', handler, true); this.unsubscribe = () => { document.removeEventListener('scroll', handler, true); delete this.unsubscribe; }; this.trigger(props); } } status(props = this.props) { const { offsetTop = 0, offsetBottom = 0 } = props; const rect = this.refs[FLAG_REF].getBoundingClientRect(); return rect.bottom + offsetTop < 0 ? STATUS.ABOVE_VIEWPORT : rect.top + offsetBottom > window.innerHeight ? STATUS.BENEATH_VIEWPORT : STATUS.WITHIN_VIEWPORT; } trigger(props = this.props) { // as we throttle this function on subscribe, it can be invoked even // after this component did unmount // IN THAT CASE, ABORT. if (!this.refs[FLAG_REF]) return; const { handleAppear, once = true } = props; const { status } = this.state; const newStatus = this.status(props); if (status !== newStatus) this.setState({ status: newStatus }); // (scrolling above | beneath) || (scrolling within viewport but once => donothing) if (status === newStatus && (newStatus !== STATUS.WITHIN_VIEWPORT || once)) return; // initial, but outside viewport if (status === STATUS.INIT && newStatus !== STATUS.WITHIN_VIEWPORT) return; handleAppear(newStatus, status, this.refs[FLAG_REF]); } render() { const { className, children, ...props } = this.props; const { status } = this.state; props.className = cx({ 'view-flag--above-viewport': status === STATUS.ABOVE_VIEWPORT, 'view-flag--within-viewport': status === STATUS.WITHIN_VIEWPORT, 'view-flag--beneath-viewport': status === STATUS.BENEATH_VIEWPORT }, 'view-flag', className); return <div ref={FLAG_REF} {...props}>{children}</div>; } } ViewFlag.STATUS = STATUS; export default ViewFlag;
frontend/src/index.js
miurahr/seahub
// Import React! import React from 'react'; import ReactDOM from 'react-dom'; import MarkdownEditor from './markdown-editor'; import { I18nextProvider } from 'react-i18next'; import i18n from './i18n-seafile-editor'; import './index.css'; ReactDOM.render( <I18nextProvider i18n={ i18n } > <MarkdownEditor /> </I18nextProvider>, document.getElementById('root') );
definitions/npm/react-jss_v6.1.x/test_react-jss_v6.1.x.js
hansonw/flow-typed
// @flow import React from 'react'; import injectSheet, { create } from 'react-jss'; import type { Classes, Sheet } from 'react-jss'; const styles = { root: { backgroundColor: 'red', }, [`@media (min-width: ${10}px)`]: { root: { width: 200 } } }; type Styles = typeof styles; type Props = { classes: Classes<Styles>, sheet: Sheet<Styles>, content: string, } const FunctionComponent = (props: Props) => { if (!props.sheet.attached) { return null; } return <div className={props.classes.root}>{props.content}</div>; }; const FunctionComponentUsesWrongClassname = (props: Props) => { // $ExpectError - property `nonExistentClassName` is not found in "styles" return <div className={props.classes.nonExistentClassName}>{props.content}</div>; }; class ClassComponent extends React.Component { props: Props; render() { const { classes, sheet, content } = this.props; if (!sheet.attached) { return null; } return <div className={classes.root}>{content}</div> } } // =================================== // "create" signature // =================================== const customInjectSheet = create(); // $ExpectError - missing "styles" argument customInjectSheet()(FunctionComponent); // $ExpectError - wrong type of "styles" argument customInjectSheet(123)(FunctionComponent); // no errors customInjectSheet(styles)(FunctionComponent); // =================================== // "injectSheet" signature // =================================== // $ExpectError - missing "styles" argument injectSheet()(FunctionComponent); // $ExpectError - wrong type of "styles" argument injectSheet(123)(FunctionComponent); // no errors injectSheet(styles)(FunctionComponent); // =================================== // Wrapping function components // =================================== const WrappedFunctionComponent = injectSheet(styles)(FunctionComponent); // $ExpectError - missing prop "content" <WrappedFunctionComponent />; // $ExpectError - wrong type of prop "content" <WrappedFunctionComponent content={1} />; // No errors <WrappedFunctionComponent content="Hi there!" />; // =================================== // Wrapping class components // =================================== const WrappedClassComponent = injectSheet({ root: { backgroundColor: 'red' } })(ClassComponent); // $ExpectError - missing prop "content" <WrappedClassComponent />; // $ExpectError - wrong type of prop "content" <WrappedClassComponent content={true} />; // No errors <WrappedClassComponent content="Lorem ipsum!" />; // =================================== // Wrapping Null components // =================================== const GlobalStylesComponent = injectSheet(styles)(); <GlobalStylesComponent />;
src/components/about/About.js
andgiu/lin.bert
import React, { Component } from 'react'; import * as Config from '../actions/Config'; class About extends Component { render(){ let about = Config.getAbout(); return ( <div id="about"> <img id="header" src={Config.getImageFromCache("about").src} /> <div id="content"> <h1><span>{about.title}</span></h1> <div className="row"> <div className="column left"> <p dangerouslySetInnerHTML={{__html:about.description}} /> </div> <div className="column right"> <div className="contact"> <a className="link link--kukuri" href="mailto:linbert.collective@gmail.com" data-letters="linbert.collective@gmail.com">linbert.collective@gmail.com</a> </div> </div> </div> <div className="row"> <div className="column left"> <img className="portrait" src={Config.getImageFromCache("wen").src} /> <h1 className="small"><span>{about.wen.title}</span></h1> <p dangerouslySetInnerHTML={{__html:about.wen.description}} /> <div className="site link" > <span className="icon-link" /> <a href="http://blog.bongiovi.tw/" target="_blank" data-letters="Link to the blog" className="link link--kukuri">Link to the blog</a> <div className="social-holder"> <a className="social icon-github-circled" target="_blank" href="https://github.com/yiwenl"/> <a className="social icon-instagram" target="_blank" href="https://www.instagram.com/yiwen/"/> <a className="social icon-twitter" target="_blank" href="https://twitter.com/yiwen_lin"/> </div> </div> </div> <div className="column right"> <img className="portrait" src={Config.getImageFromCache("bert").src} /> <h1 className="small"><span>{about.bert.title}</span></h1> <p dangerouslySetInnerHTML={{__html:about.bert.description}} /> <div className="site link" > <span className="icon-link" /> <a href="http://www.bertrandcarrara.com" target="_blank" data-letters="Link to the blog" className="link link--kukuri">Link to the blog</a> <div className="social-holder"> <a className="social icon-instagram" target="_blank" href="https://www.instagram.com/bertrandcarrara/"/> <a className="social icon-twitter" target="_blank" href="https://twitter.com/bertrandcarrara"/> </div> </div> </div> </div> <div className="row"> <div className="column left"> <h1 className="small"><span>Friends<br/>& Collaborators</span></h1> {about.friends.map((friend,i) => { return( <div key={i} className="link"> <span className="icon-link" /> <a href={friend.url} target="_blank" data-letters={friend.name} className="link link--kukuri">{friend.name}</a> </div> ); })} </div> </div> </div> </div> ) } } export default About;
__tests__/components/button.js
builderscon/nanp
/* eslint-env jest */ import React from 'react' import Button from '../../src/components/button' // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer' it('renders correctly', () => { const tree = renderer.create( <Button title='button sample' onPress={() => {}} /> ).toJSON() expect(tree).toMatchSnapshot() }) it('renders correctly with buttonStyle', () => { const tree = renderer.create( <Button title='button sample' onPress={() => {}} buttonStyle={{ flex: 1 }} /> ).toJSON() expect(tree).toMatchSnapshot() }) it('renders correctly with titleStyle', () => { const tree = renderer.create( <Button title='button sample' onPress={() => {}} titleStyle={{ color: 'black' }} /> ).toJSON() expect(tree).toMatchSnapshot() })
app/main/GDSearch.js
shaojianye/GD
/** * Created by yeshaojian on 17/3/14. */ import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Image, ListView, Dimensions, Navigator, ActivityIndicator, Modal, AsyncStorage, TextInput, DeviceEventEmitter, } from 'react-native'; const {width, height} = Dimensions.get('window'); // 获取屏幕尺寸 const dismissKeyboard = require('dismissKeyboard'); // 获取键盘回收方法 // 第三方 import {PullList} from 'react-native-pull'; // 引用外部文件 import CommunalNavBar from '../main/GDCommunalNavBar'; import CommunalCell from '../main/GDCommunalCell'; import CommunalDetail from '../main/GDCommunalDetail'; import NoDataView from '../main/GDNoDataView'; export default class GDHome extends Component { // 构造 constructor(props) { super(props); // 初始状态 this.state = { dataSource: new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}), loaded:false, // 是否初始化 ListView }; this.data = []; this.changeText = ''; // 改变后的文本 // 绑定操作 this.loadData = this.loadData.bind(this); this.loadMore = this.loadMore.bind(this); } // 加载最新数据网络请求 loadData(resolve) { // 文本是否为空 if (!this.changeText) return; // 初始化参数对象 let params = { "q" : this.changeText }; // 加载最新数据请求 HTTPBase.get('http://guangdiu.com/api/getresult.php', params) .then((responseData) => { // 清空数组 this.data = []; // 拼接数据 this.data = this.data.concat(responseData.data); // 重新渲染 this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.data), loaded:true, }); // 关闭刷新动画 if (resolve !== undefined){ setTimeout(() => { resolve(); }, 1000); } // 存储数组中最后一个元素的id let searchLastID = responseData.data[responseData.data.length - 1].id; AsyncStorage.setItem('searchLastID', searchLastID.toString()); }) .catch((error) => { }) } // 加载更多数据的网络请求 loadMoreData(value) { // 初始化参数对象 let params = { "q" : this.changeText, "sinceid" : value }; // 加载更多请求 HTTPBase.get('http://guangdiu.com/api/getresult.php', params) .then((responseData) => { // 拼接数据 this.data = this.data.concat(responseData.data); this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.data), loaded:true, }); // 存储数组中最后一个元素的id let searchLastID = responseData.data[responseData.data.length - 1].id; AsyncStorage.setItem('searchLastID', searchLastID.toString()); }) .catch((error) => { }) } // 加载更多数据操作 loadMore() { // 读取id AsyncStorage.getItem('searchLastID') .then((value) => { // 数据加载操作 this.loadMoreData(value); }) } // 返回 pop() { // 回收键盘 dismissKeyboard(); this.props.navigator.pop(); } // 跳转到详情页 pushToDetail(value) { this.props.navigator.push({ component:CommunalDetail, params: { url: 'https://guangdiu.com/api/showdetail.php' + '?' + 'id=' + value } }) } // 返回左边按钮 renderLeftItem() { return( <TouchableOpacity onPress={() => {this.pop()}} > <View style={{flexDirection:'row', alignItems:'center'}}> <Image source={{uri:'back'}} style={styles.navBarLeftItemStyle} /> <Text>返回</Text> </View> </TouchableOpacity> ); } // 返回中间按钮 renderTitleItem() { return( <Text style={styles.navBarTitleItemStyle}>搜索全网折扣</Text> ); } // ListView尾部 renderFooter() { return ( <View style={{height: 100}}> {/* 旋转的小菊花 */} <ActivityIndicator /> </View> ); } // 返回每一行cell的样式 renderRow(rowData) { return( <TouchableOpacity onPress={() => this.pushToDetail(rowData.id)} > <CommunalCell image={rowData.image} title={rowData.title} mall={rowData.mall} pubTime={rowData.pubtime} fromSite={rowData.fromsite} /> </TouchableOpacity> ); } // 根据网络状态决定是否渲染 ListView renderListView() { if (this.state.loaded === false) { // 无数据 return( <NoDataView /> ); }else { return( // 有数据 <PullList onPullRelease={(resolve) => this.loadData(resolve)} // 下拉刷新操作 dataSource={this.state.dataSource} // 设置数据源 renderRow={this.renderRow.bind(this)} // 根据数据创建相应 cell showsHorizontalScrollIndicator={false} // 隐藏水平指示器 style={styles.listViewStyle} // 样式 initialListSize={7} // 优化:一次渲染几条数据 renderHeader={this.renderHeader} // 设置头部视图 onEndReached={this.loadMore} // 当接近底部特定距离时调用 onEndReachedThreshold={60} // 当接近底部60时调用 renderFooter={this.renderFooter} // 设置尾部视图 /> ); } } // 准备加载组件 componentWillMount() { // 发送通知 DeviceEventEmitter.emit('isHiddenTabBar', true); } // 准备销毁组件 componentWillUnmount() { // 发送通知 DeviceEventEmitter.emit('isHiddenTabBar', false); } render() { return ( <View style={styles.container}> {/* 导航栏样式 */} <CommunalNavBar leftItem = {() => this.renderLeftItem()} titleItem = {() => this.renderTitleItem()} /> {/* 顶部工具栏 */} <View style={styles.toolsViewStyle} > {/* 左边 */} <View style={styles.inputViewStyle} > <Image source={{uri:'search_icon_20x20'}} style={styles.searchImageStyle} /> <TextInput style={styles.textInputStyle} keyboardType="default" placeholder="请输入搜索商品关键字" placeholderTextColor='gray' autoFocus={true} clearButtonMode="while-editing" onChangeText={(text) => {this.changeText = text}} onEndEditing={() => this.loadData()} underlineColorAndroid={'transparent'} /> </View> {/* 右边 */} <View style={{marginRight:10}}> <TouchableOpacity onPress={() => this.pop()} > <Text style={{color:'green'}}>取消</Text> </TouchableOpacity> </View> </View> {/* 根据网络状态决定是否渲染 listview */} {this.renderListView()} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: 'white', }, navBarLeftItemStyle: { width:20, height:20, marginLeft:15, }, navBarTitleItemStyle: { fontSize:17, color:'black', marginRight:50 }, toolsViewStyle: { width:width, height:44, flexDirection:'row', alignItems:'center', justifyContent:'space-between', }, inputViewStyle: { height:35, flexDirection:'row', alignItems:'center', justifyContent:'center', backgroundColor:'rgba(239,239,241,1.0)', marginLeft:10, borderRadius:5 }, searchImageStyle: { width:15, height:15, marginLeft:8 }, textInputStyle: { width:width * 0.75, height:35, marginLeft:8 }, listViewStyle: { width:width, }, });
examples/with-custom-babel-config/pages/index.js
dizlexik/next.js
import React from 'react' export default class MyLuckNo extends React.Component { constructor (...args) { super(...args) this.state = { randomNo: null } } componentDidMount () { this.recalculate() } recalculate () { this.setState({ randomNo: Math.ceil(Math.random() * 100) }) } render () { const { randomNo } = this.state if (randomNo === null) { return (<p>Please wait..</p>) } // This is an experimental JavaScript feature where we can get with // using babel-preset-stage-0 const message = do { if (randomNo < 30) { // eslint-disable-next-line no-unused-expressions 'Do not give up. Try again.' } else if (randomNo < 60) { // eslint-disable-next-line no-unused-expressions 'You are a lucky guy' } else { // eslint-disable-next-line no-unused-expressions 'You are soooo lucky!' } } return ( <div> <h3>Your Lucky number is: "{randomNo}"</h3> <p>{message}</p> <button onClick={() => this.recalculate()}>Try Again</button> </div> ) } }
stories/App.js
fateseal/react-mtg-playtester
import React, { Component } from 'react'; import Playtester from '../src'; import { Provider } from 'react-redux'; import { createStore, combineReducers, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { composeWithDevTools } from 'redux-devtools-extension'; import '../src/css/sandbox.css'; import data from './deck.json'; import cardback from './mtgcard-back.png'; import { reducer as sandboxReducer } from '../src'; const store = createStore( combineReducers({ playtester: sandboxReducer }), {}, composeWithDevTools(applyMiddleware(thunk)) ); const getCardsByBoard = (lib, board) => lib.filter(c => c.board === board); const fillItems = (count, cb) => Array(count) .fill() .map(cb); const getPlaytesterCards = cards => getCardsByBoard(cards, 'mainboard').reduce((arr, deckCard, i) => { const items = fillItems(deckCard.quantity, () => ({ ...deckCard, name: deckCard.card.name, imageUrl: deckCard.card.url })); return [...arr, ...items]; }, []); class App extends Component { render() { const { format, cards, featuredCard } = data; const items = getPlaytesterCards(cards); const headerLeft = ( <div style={{ color: 'white' }}>Link back to deck here</div> ); return ( <Provider store={store}> <Playtester headerLeft={headerLeft} cardBackUrl={cardback} cards={items} commander={format === 'Commander ' ? featuredCard : null} /> </Provider> ); } } export default App;
app/components/AboutInstaSection/index.js
yagneshmodh/personalApplication
import React, { PropTypes, } from 'react'; import { CardMedia } from 'material-ui/Card'; const InstaSection = ({ instaImages }) => { return ( <div> { instaImages.map((img, index) => <CardMedia key={index} style={{ height: img.height, width: img.width }} > <img src={img.url} alt="img" /> </CardMedia> ) } </div> ); }; InstaSection.propTypes = { instaImages: PropTypes.array.isRequired, }; export default InstaSection;
src/Frontend/test/components/form/LoadableButtonBarSpec.js
Sententiaregum/Sententiaregum
/* * This file is part of the Sententiaregum project. * * (c) Maximilian Bosch <maximilian@mbosch.me> * (c) Ben Bieler <ben@benbieler.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ 'use strict'; import LoadableButtonBar from '../../../components/form/LoadableButtonBar'; import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import counterpart from 'counterpart'; import { stub } from 'sinon'; describe('LoadableButtonBar', () => { it('renders a button bar', () => { stub(counterpart, 'translate', (arg) => arg); const markup = shallow(<LoadableButtonBar progress={false} btnLabel="Label" />); expect(markup.hasClass('form-group')); const btn = markup.find('button'); expect(btn.prop('type')).to.equal('submit'); expect(btn.hasClass('btn btn-primary spinner-btn')).to.equal(true); expect(btn.contains('Label')).to.equal(true); counterpart.translate.restore(); }); it('changes the progress state', () => { const markup = shallow(<LoadableButtonBar progress={false} btnLabel="Label" />); expect(markup.find('button').prop('disabled')).to.not.equal(true); markup.setProps({ progress: true }); expect(markup.find('button').prop('disabled')).to.equal('disabled'); }); });
ajax/libs/material-ui/4.9.3/esm/Tooltip/Tooltip.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { elementAcceptingRef } from '@material-ui/utils'; import { fade } 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 setRef from '../utils/setRef'; import { useIsFocusVisible } from '../utils/focusVisible'; 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': { flip: false, top: 0, left: 0, marginTop: '-0.95em', marginLeft: 4, marginRight: 4, width: '2em', height: '1em', '&::before': { flip: false, borderWidth: '0 1em 1em 1em', borderColor: 'transparent transparent currentcolor transparent' } }, '&[x-placement*="top"] $arrow': { flip: false, bottom: 0, left: 0, marginBottom: '-0.95em', marginLeft: 4, marginRight: 4, width: '2em', height: '1em', '&::before': { flip: false, borderWidth: '1em 1em 0 1em', borderColor: 'currentcolor transparent transparent transparent' } }, '&[x-placement*="right"] $arrow': { flip: false, left: 0, marginLeft: '-0.95em', marginTop: 4, marginBottom: 4, height: '2em', width: '1em', '&::before': { flip: false, borderWidth: '1em 1em 1em 0', borderColor: 'transparent currentcolor transparent transparent' } }, '&[x-placement*="left"] $arrow': { flip: false, right: 0, marginRight: '-0.95em', marginTop: 4, marginBottom: 4, height: '2em', width: '1em', '&::before': { flip: false, borderWidth: '1em 0 1em 1em', borderColor: 'transparent transparent transparent currentcolor' } } }; } export var styles = function styles(theme) { return { /* Styles applied to the Popper component. */ popper: { zIndex: theme.zIndex.tooltip, pointerEvents: 'none', flip: false // 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: fade(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: "".concat(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: { position: 'absolute', fontSize: 6, color: fade(theme.palette.grey[700], 0.9), '&::before': { content: '""', margin: 'auto', display: 'block', width: 0, height: 0, borderStyle: 'solid' } }, /* 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: "".concat(round(16 / 14), "em"), fontWeight: theme.typography.fontWeightRegular }, /* Styles applied to the tooltip (label wrapper) element if `placement` contains "left". */ tooltipPlacementLeft: _defineProperty({ 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: _defineProperty({ 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: _defineProperty({ 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: _defineProperty({ transformOrigin: 'center top', margin: '24px 0' }, theme.breakpoints.up('sm'), { margin: '14px 0' }) }; }; var hystersisOpen = false; var hystersisTimer = null; export function testReset() { hystersisOpen = false; clearTimeout(hystersisTimer); } var Tooltip = React.forwardRef(function Tooltip(props, ref) { var _props$arrow = props.arrow, arrow = _props$arrow === void 0 ? false : _props$arrow, children = props.children, classes = props.classes, _props$disableFocusLi = props.disableFocusListener, disableFocusListener = _props$disableFocusLi === void 0 ? false : _props$disableFocusLi, _props$disableHoverLi = props.disableHoverListener, disableHoverListener = _props$disableHoverLi === void 0 ? false : _props$disableHoverLi, _props$disableTouchLi = props.disableTouchListener, disableTouchListener = _props$disableTouchLi === void 0 ? false : _props$disableTouchLi, _props$enterDelay = props.enterDelay, enterDelay = _props$enterDelay === void 0 ? 0 : _props$enterDelay, _props$enterTouchDela = props.enterTouchDelay, enterTouchDelay = _props$enterTouchDela === void 0 ? 700 : _props$enterTouchDela, idProp = props.id, _props$interactive = props.interactive, interactive = _props$interactive === void 0 ? false : _props$interactive, _props$leaveDelay = props.leaveDelay, leaveDelay = _props$leaveDelay === void 0 ? 0 : _props$leaveDelay, _props$leaveTouchDela = props.leaveTouchDelay, leaveTouchDelay = _props$leaveTouchDela === void 0 ? 1500 : _props$leaveTouchDela, onClose = props.onClose, onOpen = props.onOpen, openProp = props.open, _props$placement = props.placement, placement = _props$placement === void 0 ? 'bottom' : _props$placement, PopperProps = props.PopperProps, title = props.title, _props$TransitionComp = props.TransitionComponent, TransitionComponent = _props$TransitionComp === void 0 ? Grow : _props$TransitionComp, TransitionProps = props.TransitionProps, other = _objectWithoutProperties(props, ["arrow", "children", "classes", "disableFocusListener", "disableHoverListener", "disableTouchListener", "enterDelay", "enterTouchDelay", "id", "interactive", "leaveDelay", "leaveTouchDelay", "onClose", "onOpen", "open", "placement", "PopperProps", "title", "TransitionComponent", "TransitionProps"]); var theme = useTheme(); var _React$useState = React.useState(), childNode = _React$useState[0], setChildNode = _React$useState[1]; var _React$useState2 = React.useState(null), arrowRef = _React$useState2[0], setArrowRef = _React$useState2[1]; var ignoreNonTouchEvents = React.useRef(false); var closeTimer = React.useRef(); var enterTimer = React.useRef(); var leaveTimer = React.useRef(); var touchTimer = React.useRef(); var _useControlled = useControlled({ controlled: openProp, default: false, name: 'Tooltip' }), _useControlled2 = _slicedToArray(_useControlled, 2), openState = _useControlled2[0], setOpenState = _useControlled2[1]; var open = openState; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks var _React$useRef = React.useRef(openProp !== undefined), isControlled = _React$useRef.current; // eslint-disable-next-line react-hooks/rules-of-hooks React.useEffect(function () { 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]); } var _React$useState3 = React.useState(), defaultId = _React$useState3[0], setDefaultId = _React$useState3[1]; var id = idProp || defaultId; React.useEffect(function () { if (!open || defaultId) { return; } // Fallback to this default id when possible. // Use the random value for client-side rendering only. // We can't use it server-side. setDefaultId("mui-tooltip-".concat(Math.round(Math.random() * 1e5))); }, [open, defaultId]); React.useEffect(function () { return function () { clearTimeout(closeTimer.current); clearTimeout(enterTimer.current); clearTimeout(leaveTimer.current); clearTimeout(touchTimer.current); }; }, []); var handleOpen = function 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); } }; var handleEnter = function handleEnter(event) { var childrenProps = children.props; if (event.type === 'mouseover' && childrenProps.onMouseOver && event.currentTarget === childNode) { 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) { event.persist(); enterTimer.current = setTimeout(function () { handleOpen(event); }, enterDelay); } else { handleOpen(event); } }; var _useIsFocusVisible = useIsFocusVisible(), isFocusVisible = _useIsFocusVisible.isFocusVisible, onBlurVisible = _useIsFocusVisible.onBlurVisible, focusVisibleRef = _useIsFocusVisible.ref; var _React$useState4 = React.useState(false), childIsFocusVisible = _React$useState4[0], setChildIsFocusVisible = _React$useState4[1]; var handleBlur = function handleBlur() { if (childIsFocusVisible) { setChildIsFocusVisible(false); onBlurVisible(); } }; var handleFocus = function handleFocus(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); } var childrenProps = children.props; if (childrenProps.onFocus && event.currentTarget === childNode) { childrenProps.onFocus(event); } }; var handleClose = function handleClose(event) { clearTimeout(hystersisTimer); hystersisTimer = setTimeout(function () { hystersisOpen = false; }, 500); // Use 500 ms per https://github.com/reach/reach-ui/blob/3b5319027d763a3082880be887d7a29aee7d3afc/packages/tooltip/src/index.js#L214 setOpenState(false); if (onClose) { onClose(event); } clearTimeout(closeTimer.current); closeTimer.current = setTimeout(function () { ignoreNonTouchEvents.current = false; }, theme.transitions.duration.shortest); }; var handleLeave = function handleLeave(event) { var childrenProps = children.props; if (event.type === 'blur') { if (childrenProps.onBlur && event.currentTarget === childNode) { childrenProps.onBlur(event); } handleBlur(event); } if (event.type === 'mouseleave' && childrenProps.onMouseLeave && event.currentTarget === childNode) { childrenProps.onMouseLeave(event); } clearTimeout(enterTimer.current); clearTimeout(leaveTimer.current); event.persist(); leaveTimer.current = setTimeout(function () { handleClose(event); }, leaveDelay); }; var handleTouchStart = function handleTouchStart(event) { ignoreNonTouchEvents.current = true; var childrenProps = children.props; if (childrenProps.onTouchStart) { childrenProps.onTouchStart(event); } clearTimeout(leaveTimer.current); clearTimeout(closeTimer.current); clearTimeout(touchTimer.current); event.persist(); touchTimer.current = setTimeout(function () { handleEnter(event); }, enterTouchDelay); }; var handleTouchEnd = function handleTouchEnd(event) { if (children.props.onTouchEnd) { children.props.onTouchEnd(event); } clearTimeout(touchTimer.current); clearTimeout(leaveTimer.current); event.persist(); leaveTimer.current = setTimeout(function () { handleClose(event); }, leaveTouchDelay); }; var handleUseRef = useForkRef(setChildNode, ref); var handleFocusRef = useForkRef(focusVisibleRef, handleUseRef); // can be removed once we drop support for non ref forwarding class components var handleOwnRef = React.useCallback(function (instance) { // #StrictMode ready setRef(handleFocusRef, ReactDOM.findDOMNode(instance)); }, [handleFocusRef]); var 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. var shouldShowNativeTitle = !open && !disableHoverListener; var childrenProps = _extends({ 'aria-describedby': open ? id : null, title: shouldShowNativeTitle && typeof title === 'string' ? title : null }, other, {}, children.props, { className: clsx(other.className, children.props.className) }); if (!disableTouchListener) { childrenProps.onTouchStart = handleTouchStart; childrenProps.onTouchEnd = handleTouchEnd; } if (!disableHoverListener) { childrenProps.onMouseOver = handleEnter; childrenProps.onMouseLeave = handleLeave; } if (!disableFocusListener) { childrenProps.onFocus = handleFocus; childrenProps.onBlur = handleLeave; } var interactiveWrapperListeners = interactive ? { onMouseOver: childrenProps.onMouseOver, onMouseLeave: childrenProps.onMouseLeave, onFocus: childrenProps.onFocus, onBlur: childrenProps.onBlur } : {}; 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 `".concat(children.props.title, "` or the Tooltip component.")].join('\n')); } } // Avoid the creation of a new Popper.js instance at each render. var popperOptions = React.useMemo(function () { return { modifiers: { arrow: { enabled: Boolean(arrowRef), element: arrowRef } } }; }, [arrowRef]); return React.createElement(React.Fragment, null, React.cloneElement(children, _extends({ ref: handleRef }, childrenProps)), React.createElement(Popper, _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, popperOptions: popperOptions }, interactiveWrapperListeners, PopperProps), function (_ref) { var placementInner = _ref.placement, TransitionPropsInner = _ref.TransitionProps; return React.createElement(TransitionComponent, _extends({ timeout: theme.transitions.duration.shorter }, TransitionPropsInner, TransitionProps), React.createElement("div", { className: clsx(classes.tooltip, classes["tooltipPlacement".concat(capitalize(placementInner.split('-')[0]))], ignoreNonTouchEvents.current && classes.touch, arrow && classes.tooltipArrow) }, title, arrow ? React.createElement("span", { className: classes.arrow, ref: setArrowRef }) : null)); })); }); process.env.NODE_ENV !== "production" ? Tooltip.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.isRequired, /** * 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 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']), /** * Props applied to the [`Popper`](/api/popper/) element. */ PopperProps: PropTypes.object, /** * Tooltip title. Zero-length titles string are never displayed. */ title: PropTypes.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' })(Tooltip);
themes/genius/Genius 2.3.1 Bootstrap 4/React_Full_Project/src/components/Header/Header.js
davidchristie/kaenga-housing-calculator
import React, { Component } from 'react'; import { Dropdown, DropdownMenu, DropdownItem } from 'reactstrap'; class Header extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { dropdownOpen: false }; } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } sidebarToggle(e) { e.preventDefault(); document.body.classList.toggle('sidebar-hidden'); } mobileSidebarToggle(e) { e.preventDefault(); document.body.classList.toggle('sidebar-mobile-show'); } asideToggle(e) { e.preventDefault(); document.body.classList.toggle('aside-menu-hidden'); } render() { return ( <header className="app-header navbar"> <button className="navbar-toggler mobile-sidebar-toggler hidden-lg-up" onClick={this.mobileSidebarToggle} type="button">&#9776;</button> <a className="navbar-brand" href="#"></a> <ul className="nav navbar-nav hidden-md-down"> <li className="nav-item"> <a className="nav-link navbar-toggler sidebar-toggler" onClick={this.sidebarToggle} href="#">&#9776;</a> </li> </ul> <form className="form-inline px-2 hidden-md-down"> <div className="input-group"> <div className="input-group-btn"> <button type="button" className="btn dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Search </button> <div className="dropdown-menu"> <a className="dropdown-item" href="#">Action</a> <a className="dropdown-item" href="#">Another action</a> <a className="dropdown-item" href="#">Something else here</a> <a className="dropdown-item" href="#">Separated link</a> </div> </div> <input type="text" className="form-control" aria-label="Text input with dropdown button" placeholder="...."/> <span className="input-group-btn"> <button className="btn" type="button"><i className="fa fa-search"></i></button> </span> </div> </form> <ul className="nav navbar-nav ml-auto"> <li className="nav-item hidden-md-down"> <a className="nav-link" href="#"><i className="icon-bell"></i><span className="badge badge-pill badge-danger">5</span></a> </li> <li className="nav-item hidden-md-down"> <a className="nav-link" href="#"><i className="icon-list"></i></a> </li> <li className="nav-item hidden-md-down"> <a className="nav-link" href="#"><i className="icon-location-pin"></i></a> </li> <li className="nav-item dropdown"> <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}> <a onClick={this.toggle} className="nav-link avatar" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded={this.state.dropdownOpen}> <img src={'img/avatars/6.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> </a> <DropdownMenu className="dropdown-menu-right"> <DropdownItem header className="text-center"><strong>Account</strong></DropdownItem> <DropdownItem><i className="fa fa-bell-o"></i> Updates<span className="badge badge-info">42</span></DropdownItem> <DropdownItem><i className="fa fa-envelope-o"></i> Messages<span className="badge badge-success">42</span></DropdownItem> <DropdownItem><i className="fa fa-tasks"></i> Tasks<span className="badge badge-danger">42</span></DropdownItem> <DropdownItem><i className="fa fa-comments"></i> Comments<span className="badge badge-warning">42</span></DropdownItem> <DropdownItem header className="text-center"><strong>Settings</strong></DropdownItem> <DropdownItem><i className="fa fa-user"></i> Profile</DropdownItem> <DropdownItem><i className="fa fa-wrench"></i> Settings</DropdownItem> <DropdownItem><i className="fa fa-usd"></i> Payments<span className="badge badge-default">42</span></DropdownItem> <DropdownItem><i className="fa fa-file"></i> Projects<span className="badge badge-primary">42</span></DropdownItem> <DropdownItem divider /> <DropdownItem><i className="fa fa-shield"></i> Lock Account</DropdownItem> <DropdownItem><i className="fa fa-lock"></i> Logout</DropdownItem> </DropdownMenu> </Dropdown> </li> <li className="nav-item hidden-md-down"> <a className="nav-link navbar-toggler aside-menu-toggler" onClick={this.asideToggle} href="#">&#9776;</a> </li> </ul> </header> ) } } export default Header;